Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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_Python 3.x_Unit Testing_Python Unittest - Fatal编程技术网

Python 如何从测试文件中设置或模拟变量?

Python 如何从测试文件中设置或模拟变量?,python,python-3.x,unit-testing,python-unittest,Python,Python 3.x,Unit Testing,Python Unittest,我有一个文件如下所示: prob = 0.05 def calculate_func(arg1, arg2): if random.random > prob: # Do stuff else: # Do other things # Lots more functions from my_project import calculate_func def test_calculate_func(): arg1, arg2 =

我有一个文件如下所示:

prob = 0.05

def calculate_func(arg1, arg2):
    if random.random > prob:
        # Do stuff
    else:
        # Do other things

# Lots more functions
from my_project import calculate_func

def test_calculate_func():
    arg1, arg2 = 1, 2
    assert calculate_func(arg1, arg2) == 'Desired value'
还有一个测试文件,如下所示:

prob = 0.05

def calculate_func(arg1, arg2):
    if random.random > prob:
        # Do stuff
    else:
        # Do other things

# Lots more functions
from my_project import calculate_func

def test_calculate_func():
    arg1, arg2 = 1, 2
    assert calculate_func(arg1, arg2) == 'Desired value'
但是当前测试文件从主文件导入
错误\u prob
。我希望能够从测试文件中设置或模拟
error\u prob
,以测试不同的行为。我该怎么做

我不想将
error\u prob
传递到
calculate\u func
,因为该文件中的每个函数都使用
error\u prob

我不想将error\u prob传递给calculate\u func,因为该文件中的每个函数都使用error\u prob


如果需要注入依赖项,那么就需要注入依赖项。一种可能的简化方法是将这些函数移动到一个类中,并在实例化时将
error\u prob
实现设置为成员。

您可以通过导入模块来重新分配模块范围的变量

import my_project

myproject.prob = 0.1

导入变量,为其指定另一个值。有什么问题吗?@Goyo,那不行。重新分配prob在测试文件中,测试文件调用calculate_func(),calculate_func()使用主文件中的prob定义。哦,您需要导入模块,而不是变量。