[TIP] mock, nosetests, and third-party base classes

Michael Foord michael at voidspace.org.uk
Mon Jun 20 15:36:50 PDT 2011


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.
>
>
> Felix
>
>
> _______________________________________________
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
> http://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...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20110620/3236cfb9/attachment.htm>


More information about the testing-in-python mailing list