With Statement Support for Patching Fakes

Create issue
Issue #3 resolved
Cristian Esquivias created an issue

If you want to monkeypatch an object within a method, you currently have to:

{{{ #!python # from docs

SMTP = fudge.Fake()

rest of SMPT init

patched_smtplib = fudge.patch_object("smtplib", "SMTP", SMTP)

do your stuff



This works fine, but it can look a little cleaner, and always be properly restored, by using context managers and the with statement.

For example:

{{{ #!python #using the example above

with fudge.patch('smtplib', 'SMTP', SMTP): # do your stuff


It's a pretty simple addition. I've included a changeset that adds this functionality.

I wasn't sure what minimum version of Python was supported (context managers were added in 2.5) so the new code fails gracefully if it's an older version of Python.

Comments (2)

  1. Kumar McMillan repo owner

    Hi Cristian. Thanks again, nice patch. I applied this feature but I changed the function name to fudge.patched_context() to give it a more pneumonic quality. Grab an update and you will see it and I added API docs for it too.

    It seems that the @contextmanager decorator triggers what I believe may be an obscure bug in sphinx; I am still puzzled by it. Its only side effect is that doctests for patched_context() are not run, but I can live with that for now.

  2. Log in to comment