【问题标题】:Python mocking global variablePython模拟全局变量
【发布时间】:2014-10-31 06:12:48
【问题描述】:

我正在使用 sys.modules['cv2'] = Mock() 模拟 OpenCV 模块,但我无法使用 assertEqual 测试是否已使用全局变量正确设置变量。我已经稍微简化了代码。 我不确定我的嘲讽是否正确。

这是我的单元测试文件:

from mock import patch, Mock
sys.modules['cv2'] = Mock()
from MyClass import MyClass
del sys.modules['cv2']

....

def testFunction()
    myObject = MyClass()
    self.assertEqual(myObject.val, ?) # here i don't know how to test the equality

还有文件MyClass.py:

import module

val1 = cv2.function(1)
val2 = cv2.function(2)

class MyClass():
    def _init_(self)
        self.val = val1

【问题讨论】:

  • 如果你正在做 sys.modules['cv2'] = Mock() 然后 del sys.modules['cv2'] 你正在删除 sys.modules['cv2'] (模拟对象) - 没有多大意义......
  • 对我来说,在嘲笑之后进行删除更干净。每个 opencv 函数在导入期间都是模拟的。也许我错了
  • 您在模拟后删除 2 行 - 不使用模拟对象
  • 好的,但即使删除删除行,我如何测试我的相等性?
  • 好吧,从您的代码中不清楚您要比较什么...

标签: python unit-testing mocking


【解决方案1】:

也许做你想做的最好的方法是修补var1。无论如何,因为我不确定你想做什么,所以我向你提出了一些解决方案:

from mock import patch

@patch("cv2.function")
def testfunction(mfun):
    mfun.return_value = 200
    import MyClass
    MyObject = MyClass.MyClass()
    assert MyObject.var == 200


import MyClass
print(MyClass.MyClass().var) #my cv2.function(1) stub return -1... but here you can see the real value

@patch("MyClass.var1")
def testfunction(mvar1):
    mvar1 = 300
    MyObject = MyClass.MyClass()
    assert MyObject.var == 300

请注意,在第一种情况下,您必须在 patch 上下文中导入 MyClass。第二个例子只是你模块上的变量将被修补。

如果您必须编写大量使用补丁的方法,例如第一个示例,您可以使用 patch 作为 unittest 类的类装饰器:您将在所有测试中修补 cv2 函数。

【讨论】:

    【解决方案2】:
    class Chameleon(Mock):
        def __eq__(self, other):
            return True
    

    也可以看看MagicMock

    【讨论】:

      猜你喜欢
      • 2016-11-15
      • 1970-01-01
      • 1970-01-01
      • 2017-03-19
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 2020-07-21
      相关资源
      最近更新 更多