1

我的 django 应用程序中有几个 TestCase 类。在其中一些上,我模拟了一个通过使用@mock.patch 装饰类来调用外部资源的函数,效果很好。我的测试套件中的一个TestCase,我们称之为B(),依赖于那个外部资源,所以我不希望它被模拟出来,我也不添加装饰器。它看起来像这样:

@mock.patch("myapp.external_resource_function", new=mock.MagicMock)
class A(TestCase):
    # tests here

class B(TestBase):
    # tests here which depend on external_resource_function

当我独立测试 B 时,事情按预期工作。但是,当我同时运行两个测试时,A 首先运行,但该函数仍然在 B 中模拟出来。我怎样才能取消模拟该调用?我试过重新加载模块,但没有帮助。

4

2 回答 2

5

补丁有启动和停止方法。根据我从您提供的代码中看到的内容,我将删除装饰器并使用您的类链接中的 setUp 和 tearDown 方法。

class A(TestCase):
  def setUp(self):
    self.patcher1 = patch('myapp.external_resource_function', new=mock.MagicMock)
    self.MockClass1 = self.patcher1.start()

  def tearDown(self):
    self.patcher1.stop()

  def test_something(self):
    ...

>>> A('test_something').run()
于 2012-12-04T02:32:55.630 回答
1

很好的答案。关于 Ethereal 的问题,补丁对象的使用非常灵活。

这是处理需要不同补丁的测试的一种方法。您仍然可以使用 setUp 和 tearDown,但不能使用 patch.start/stop 位。

在每个测试中启动()补丁,并使用 finally 子句确保它们被停止()。

补丁还支持上下文管理器的东西,所以这是另一个选项,这里没有显示。

class A(TestCase):
    patcher1 = patch('myapp.external_resource_function', new=mock.MagicMock)
    patcher2 = patch('myapp.something_else', new=mock.MagicMock)


    def test_something(self):

        li_patcher = [self.patcher1]
        for patcher in li_patcher:
            patcher.start()


        try:
            pass
        finally:
            for patcher in li_patcher:
                patcher.stop()


    def test_something_else(self):

        li_patcher = [self.patcher1, self.patcher2]
        for patcher in li_patcher:
            patcher.start()

        try:
            pass
        finally:
            for patcher in li_patcher:
                patcher.stop()
于 2015-09-13T23:55:51.967 回答