简体   繁体   English

Python模拟全局变量

[英]Python mocking global variable

I'm using the sys.modules['cv2'] = Mock() to mock the OpenCV module but I'm having trouble to use the assertEqual to test if a variable has been set up correctly with a global variable. 我正在使用sys.modules['cv2'] = Mock()来模拟OpenCV模块,但是我无法使用assertEqual来测试是否已使用全局变量正确设置了变量。 I've simplified the code a bit. 我已经简化了代码。 I'm not sure if my mocking is right. 我不确定我的嘲笑是否正确。

Here is my unit test file: 这是我的单元测试文件:

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

and the file MyClass.py : 和文件MyClass.py

import module

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

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

Maybe the best way to do what you want to do is patch var1 . 也许做您想做的最好的方法是修补var1 Anyway, because I'm not sure about what you want to do I'm proposing to you some solutions: 无论如何,由于我不确定您要做什么,因此我向您提出一些解决方案:

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

Note that in the first case you MUST import MyClass in patch context. 请注意,在第一种情况下,必须在patch上下文中导入MyClass。 The second example just the variable on your module will be patched. 第二个示例只是对模块上的变量进行了修补。

If you must write lot of methods that use a patch like in first example you can use patch as class decorator of unittest class: you will patch cv2 function in all tests. 如果必须像第一个示例一样编写许多使用补丁的方法,则可以将patch用作unittest类的类装饰器:您将在所有测试中对cv2函数进行补丁。

class Chameleon(Mock):
    def __eq__(self, other):
        return True

Also have a look at MagicMock . 也可以看看MagicMock

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM