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

Alexander O'Donovan-Jones Alexander at ccpgames.com
Wed Aug 29 06:34:10 PDT 2012

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'):
        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')


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?

Alex O'Donovan-Jones
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20120829/b0c956d0/attachment.html>

More information about the testing-in-python mailing list