[TIP] Mocking the .decode(...) method on a string
Alexander O'Donovan-Jones
Alexander at ccpgames.com
Wed Aug 29 07:02:46 PDT 2012
Creating a mock object that raises the exceptions required is exactly the route I'm taking now.
From: Ned Batchelder [mailto:ned at nedbatchelder.com]
Sent: Wednesday, 29 August, 2012 2:00 PM
To: Alexander O'Donovan-Jones
Cc: testing-in-python at lists.idyll.org
Subject: Re: [TIP] Mocking the .decode(...) method on a string
On 8/29/2012 9:34 AM, Alexander O'Donovan-Jones wrote:
Does anyone know of a way to mock out the .decode(...) method on a string?
I have a piece of code which essentially does this:
def CoerceToUnicode(inputString, encoding='cp1252'):
try:
ret = inputString.decode(encoding)
except (UnicodeDecodeError, UnicodeEncodeError):
ret = inputString
return ret
However if I try to mock out the str.decode method I get an exception thrown:
def test_CoerceToUnicode_DecodeException(self):
# we mock out the decoding method to throw an exception and check the return
with mock.patch('__builtin__.str.decode', side_effect=UnicodeDecodeError):
# simple test cases of ascii strings in non-unicode and unicode formats
self.assertEqual(CoerceToUnicode('asdf'), 'asdf')
self.assertEqual(CoerceToUnicode(u'asdf'), u'asdf')
raises:
Traceback (most recent call last):
File "c:\depot\eveLauncher\libs\test\test_localization.py", line 220, in test_CoerceToUnicode_DecodeException
with mock.patch('__builtin__.str.decode', side_effect=UnicodeDecodeError):
File "build\bdist.win32\egg\mock.py", line 1348, in __enter__
setattr(self.target, self.attribute, new_attr)
TypeError: can't set attributes of built-in/extension type 'str'
Does anyone have experience with mocking out things like this?
Thanks!
This doesn't seem like a good use of mocking. Why not just pass in an inputString and encoding that together raise the error?
--Ned.
Alex O'Donovan-Jones
_______________________________________________
testing-in-python mailing list
testing-in-python at lists.idyll.org<mailto:testing-in-python at lists.idyll.org>
http://lists.idyll.org/listinfo/testing-in-python
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20120829/b91fac54/attachment.htm>
More information about the testing-in-python
mailing list