I am writing some code, in Python 3.4, that depends on a module that hasn't yet be written so would like to mock that import so I can still run tests on the code without running into an ImportError
. Here is a sample bit of code I would like to test:
foo.py - simple class that checks params and then calls a method
from bar import Bar
from notcreated import NotCreated
class Foo:
def method(self, bar, notCreated):
# check time param is of correct type
if not isinstance(bar, Bar):
raise TypeError("bar of wrong type")
# check notCreated param
if not isinstance(notCreated, NotCreated):
raise TypeError("notCreated of wrong type")
notCreated.callMethod(bar)
bar.py
class Bar:
def __init__(self, param):
self.param = param
And a sample test class:
test_foo.py
from unittest import TestCase
from unittest.mock import patch, MagicMock
from bar import Bar
class TestFoo(TestCase):
def setUp(self):
self.notcreated = MagicMock()
self.notcreated.NotCreated.callMethod.return_value = None
modules = {'notcreated': self.notcreated}
self.patch = patch.dict('sys.modules', modules)
self.patch.start()
from foo import Foo
self.Foo = Foo
def test_time(self):
bar = MagicMock(Bar)
notCreated = self.notcreated.NotCreated
foo = self.Foo()
foo.method(bar, notCreated)
self.notcreated.NotCreated.callMethod.assert_called_with(bar)
def tearDown(self):
self.patch.stop()
However when I run the test I get the following error:
Error
Traceback (most recent call last):
File "C:\Users\Oliver\PycharmProjects\PatchingImports\test_foo.py", line 27, in test_time
foo.method(bar, notCreated)
File "C:\Users\Oliver\PycharmProjects\PatchingImports\foo.py", line 14, in method
if not isinstance(notCreated, NotCreated):
TypeError: isinstance() arg 2 must be a type or tuple of types
For some reason isinstance
doesn't seem to thing that the Mocked NotCreated
has a type although it is fine with the Mock created for Bar
.
Any help would me much appreciated. :)