[TIP] New alpha of Mock
Michael Foord
fuzzyman at voidspace.org.uk
Mon Apr 13 09:00:01 PDT 2009
Hello all,
I've done a bit more work on Mock and would appreciate some feedback
before I do a new release.
Specifically I've implemented simple object wrapping which I would like
feedback on. The wrapping *doesn't* wrap return values (my thinking is
that you use it when you need the call to really go ahead and the code
you are testing needs the return value). It does wrap attribute access,
so that method calls are wrapped and recorded. If you need to track the
use of the returned values then use a normal mock.
The updated version is available at:
http://code.google.com/p/mock/source/browse/trunk/mock.py
I've built a PDF of docs for the new version available from:
http://www.voidspace.org.uk/downloads/mock.pdf
I'm afraid this version *isn't* a drop-in replacement, there are a few
API changes. The major changes are:
* patch and patch_object are now context managers and can be used with
the with statement (not backwards incompatible)
* ``side_effect`` is now called with the same arguments as the mock is
called with and
if returns a non-DEFAULT value that is automatically set as the
mock.return_value. (Probably will require changes to your side_effect
functions)
* The methods keyword argument to Mock has been removed and merged with
spec. The spec
argument can now be a list of methods or an object to take the spec
from. (Just change 'methods' to 'spec' if you were using it)
* ``wraps`` keyword argument used for wrapping objects (and passing
calls through to the wrapped object).
* Mock.reset renamed to Mock.reset_mock, as reset is a common API name.
The full list of changes (in the changelog file in the docs) are:
* Made DEFAULT part of the public api.
* Documentation built with Sphinx.
* A new 'create' keyword argument to patch and patch_object that allows
them to patch
(and unpatch) attributes that don't exist. (Potentially unsafe to use
- it can allow
you to have tests that pass when they are testing an API that doesn't
exist - use at
your own risk!)
* Nested patches may now be applied in a different order (created mocks
passed
in the opposite order). This is actually a bugfix.
* patch and patch_object now take a spec keyword arguments. If spec is
passed in as 'True' then the Mock created will take the object it is
replacing
as its spec object. If the object being replaced is a class, then the
return
value for the mock will also use the class as a spec.
The version in SVN (and the docs) have some support for mocking magic
methods. I'm really not sure about the technique I've chosen - it's very
clean but I'm not sure how useful it is. I'll probably rip this out
before doing the release and create a branch with the magic method
support in it. Feedback on that also welcomed.
All the best,
Michael Foord
--
http://www.ironpythoninaction.com/
http://www.voidspace.org.uk/blog
More information about the testing-in-python
mailing list