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

Michael Foord michael at voidspace.org.uk
Tue Jun 21 09:56:51 PDT 2011


On 21/06/2011 02:20, Gary Bernhardt wrote:
> On Mon, Jun 20, 2011 at 3:14 PM, Felix Yen<fyen at narrativescience.com>  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:
> I feel compelled to show this because of how awful it is. It's the
> first thing that came to mind:
>
> # at the top level of your test module
> mock.patch("pymongo.Connection", object)(lambda: __import__("mymodule"))()
> # then import everything as normal
>
> *ducks*
>
> (It does work. Please don't ever do this.)
>
Hah. Similar effect, marginally less evil:

with patch('mymodule.Connection.__bases__', (object,)):
     with patch('mymodule.pymongo') as mock_pymongo:
         ... # my tests

All the best,

Michael

-- 
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




More information about the testing-in-python mailing list