[TIP] Mocking native Python2/3 code

Chris Down chris at chrisdown.name
Wed Jan 1 00:27:52 PST 2014


Hello,

Currently, I do the following in my code to mock urlopen for Python 3:

    @patch("urllib.request.urlopen")
    def test_something(urlopen_mock):
        ...

This works fine on Python 3, but (for obvious reasons) not on Python 2.
This is a problem, because my code is native to both, by doing the
following in modules requiring it:

    try:
        from urllib.request import urlopen
    except ImportError:  # Python 2 fallback
        from urllib import urlopen

I cannot simply add another decorator to patch urllib.urlopen, because
on Python 3 this results in an AttributeError.

I tried to use patch as a context manager to get around this, but the
exception isn't raised until the context manager is invoked.

What are the best practises when using mock in this scenario?

Thanks.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20140101/3768b00a/attachment.pgp>


More information about the testing-in-python mailing list