Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python模拟:运行多个测试时模拟对象未更新_Python_Unit Testing_Mocking - Fatal编程技术网

Python模拟:运行多个测试时模拟对象未更新

Python模拟:运行多个测试时模拟对象未更新,python,unit-testing,mocking,Python,Unit Testing,Mocking,我试图模拟调用远程api的函数: def get_remote_value(): ret = make_distant_call() return ret > 0 此函数在另一个函数中调用: from another_file import get_remote_value def check_remote_value(): remote_value = get_remote_value() # Actually do some computation

我试图模拟调用远程api的函数:

def get_remote_value():
    ret = make_distant_call()
    return ret > 0
此函数在另一个函数中调用:

from another_file import get_remote_value

def check_remote_value():
    remote_value = get_remote_value()
    # Actually do some computation but it doesn't change the issue
    return remote_value
这是我的测试:

@mock.patch('another_file.get_remote_value')
class MyTest(TestCase):
    def first_test(self, mock_get_remote_value):
        mock_get_remote_value.return_value = True
        self.assertEqual(check_remote_value(), True)

    def second_test(self, mock_get_remote_value):
        mock_get_remote_value.return_value = False
        self.assertEqual(check_remote_value(), False)
当我单独运行每个测试时,它工作得很好。当我运行整个类时,第二个测试失败,因为
get\u remote\u value
返回
True
而不是
False

我认为,
check\u remote\u value
函数仍在使用旧的mock,这就是问题的原因。我说得对吗?无论如何,我怎样才能改变我的测试,使它顺利运行


我尝试在每个函数上使用decorator,使用补丁上下文管理器,但没有效果。模拟整个
check\u remote\u value
实际上不是一个选项,因为它是我想要测试的。

您需要修补
check\u remote\u value
实际使用的名称

@mock.path('mymodule.utils.another_file.get_remote_value')
class MyTest(TestCase):
    def first_test(self, mock_get_remote_value):
        mock_get_remote_value.return_value = True
        self.assertEqual(check_remote_value(), True)

    def second_test(self, mock_get_remote_value):
        mock_get_remote_value.return_value = False
        self.assertEqual(check_remote_value(), False)

这是由于函数如何查找全局值
check_remote_value
引用的是在
mymodule.utils
中定义的全局作用域,而不是您的测试脚本,因此当它需要查找
get_remote_value

时,它会在此处查找。我怀疑您模拟的是
get_remote_value
的错误实例。如何将
check\u remote\u value
导入测试脚本?如果使用类似mymodule导入的
检查\u remote\u值
,您需要修补
mymodule.Other\u文件。获取\u remote\u值
@chepner,我可能过度简化了测试。我实际上正在测试一个Django视图,它调用
check\u remote\u value
函数。在视图中,我导入的函数如下:
来自mymodule.utils import check\u remote\u value
我刚刚得出了相同的结论:p非常感谢!