Python模拟全局变量 [英] Python mocking global variable

查看:91
本文介绍了Python模拟全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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. 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

和文件MyClass.py:

import module

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

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

推荐答案

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

Maybe the best way to do what you want to do is patch 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

请注意,在第一种情况下,必须在patch上下文中导入MyClass.第二个示例只是对模块上的变量进行修补.

Note that in the first case you MUST import MyClass in patch context. The second example just the variable on your module will be patched.

如果您必须像第一个示例中那样编写许多使用补丁的方法,则可以将patch用作unittest类的类装饰器:您将在所有测试中对cv2函数进行补丁.

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.

这篇关于Python模拟全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆