#1301 closed defect (somebody else's problem)

use a mock decorator for test methods that return Deferreds

Reported by: davidsarah Owned by: somebody
Priority: minor Milestone: undecided
Component: code Version: 1.8.1
Keywords: mock twisted deferred test Cc:
Launchpad Bug:

Description (last modified by zooko)

Using the @mock.patch decorator for Trial test methods that return Deferreds does not work, because the patch will be undone when the method returns synchronously, not when the Deferred chain completes.

We should add a decorator that can be used instead to src/allmydata/test/common_util.py. Something like:

def trialPatch(*patch_args, **patch_kwargs):
    patcher = mock.patch(*patch_args, **patch_kwargs)
    def decorator(f):
        def inner(*test_args, **test_kwargs):
            mock = patcher.__enter__()
            def cleanup(res):
                patcher.__exit__()
                return res
            test_args += (mock,)
            d = f(*test_args, **test_kwargs)
            d.addBoth(cleanup)
            return d
        return inner
    return decorator

This would require mock 0.6, I think. Thanks to ducki2p and voidspace for this code.

Change History (5)

comment:1 Changed at 2011-06-17T06:19:13Z by zooko

Please see #1395 for a working implementation of this and a discussion of whether we should actually maintain it in Tahoe-LAFS source tree or not.

comment:2 Changed at 2011-07-24T22:19:12Z by davidsarah

The test added in #1149 could also benefit from this.

comment:3 follow-up: Changed at 2011-08-09T03:57:17Z by davidsarah

Is this useful? http://twistedmatrix.com/documents/10.1.0/api/twisted.trial.unittest.TestCase.html#patch

It's not as sophisticated as the mock library, but it might suffice for the cases we currently need, until we can depend on a version of mock that automatically handles deferreds.

Last edited at 2011-08-09T03:57:49Z by davidsarah (previous) (diff)

comment:4 in reply to: ↑ 3 Changed at 2011-09-04T04:23:21Z by zooko

Replying to davidsarah:

Is this useful? http://twistedmatrix.com/documents/10.1.0/api/twisted.trial.unittest.TestCase.html#patch

It's not as sophisticated as the mock library, but it might suffice for the cases we currently need, until we can depend on a version of mock that automatically handles deferreds.

Yeah, that looks potentially perfect. :-)

comment:5 Changed at 2013-08-21T15:34:51Z by zooko

  • Description modified (diff)
  • Resolution set to somebody else's problem
  • Status changed from new to closed

Everyone who finds this ticket, please use the Twisted "patch" utility: http://twistedmatrix.com/documents/10.1.0/api/twisted.trial.unittest.TestCase.html#patch for your unit tests.

Note: See TracTickets for help on using tickets.