[TIP] Mocking the .decode(...) method on a string

Ned Batchelder ned at nedbatchelder.com
Wed Aug 29 06:59:55 PDT 2012


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
> 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/215e09cd/attachment-0001.htm>


More information about the testing-in-python mailing list