如何在不存在的模块上模拟导入?

时间:2015-07-17 12:43:07

标签: python unit-testing python-3.x import mocking

我在Python 3.4中编写了一些代码,它依赖于尚未编写的模块,因此希望模拟该导入,因此我仍然可以对代码运行测试而不会遇到ImportError 。以下是我想测试的一些代码示例:

foo.py - 检查params然后调用方法的简单类

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

示例测试类:

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

然而,当我运行测试时,我收到以下错误:

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

出于某些原因,isinstance似乎没有Mocked NotCreated有类型,尽管为Bar创建的模拟效果不错。

任何帮助都会让我非常感激。 :)

0 个答案:

没有答案