[TIP] mock, nosetests, and third-party base classes
fyen at narrativescience.com
Tue Jun 21 10:06:04 PDT 2011
thank you, Michael. following your suggestion, i can mock out the __init__
def test_pymongo_decorator(self, pymongo_connection):
i can also mock base class behavior as you described, e.g.
mymodule.Connection.__bases__ = (MockPymongoConnection,)
was sorely tempted to try Gary's hack, but will try to erase it from my
memory instead :-)
On Mon, Jun 20, 2011 at 5:36 PM, Michael Foord <michael at voidspace.org.uk>wrote:
> On 20/06/2011 23:14, Felix Yen wrote:
> hi, i'm new here and hope my question wasn't answered earlier. (i did look
> at a bunch of archive threads ...) i derived a class from a third-party
> class; it looks a bit like this:
> class Connection(pymongo.Connection):
> def __init__(self, spam):
> # translate spam ...
> pymongo.Connection.__init__(self, host, port)
> If you just want to mock out the call to pymongo.Connection.__init__ here
> (and leave your instances effectively uninitialised) then patching out
> pymongo in the same namespace as Connection should then allow you to do:
> with patch('mymodule.pymongo' as mock_mongo:
> instance = Connection('spam')
> mock_mongo.assert_called_once_with(instance, host, port)
> If you *actually* want to change the base class of Connection then you will
> have to patch Connection.__bases__ before instantiation.
> All the best,
> Michael Foord
> using mock 0.7.2, i wrote a unit test that validates the host and port
> values passed to the base class constructor. however, this test fails when
> nosetests runs it. without nose (1.0.0), i can get the test to succeed in
> two ways:
> 1) assigning pymongo.Connection to a stub connection class, or
> 2) modifying sys.path and importing a fake pymongo package.
> mock's documentation mentions that "nosetests does some manipulation of
> sys.modules (along with sys.path manipulation)." so i think this
> "manipulation" is preventing me from patching my connection.
> has anyone seen this problem before? more generally/importantly, what's a
> good way of mocking third-party base classes?? i'm using Python 2.7 and mock
> usage is optional (though it's hard to imagine *not* using it), but nose
> usage is mandatory.
> testing-in-python mailing listtesting-in-python at lists.idyll.orghttp://lists.idyll.org/listinfo/testing-in-python
> -- http://www.voidspace.org.uk/
> May you do good and not evil
> May you find forgiveness for yourself and forgive others
> May you share freely, never taking more than you give.
> -- the sqlite blessing http://www.sqlite.org/different.html
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the testing-in-python