如何设置或模拟测试文件中的变量?
How can I set or mock a variable from a test file?
我有一个如下所示的文件:
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'
但目前测试文件从主文件导入 error_prob
。我希望能够从测试文件中设置或模拟 error_prob
以测试不同的行为。我该怎么做?
我不想将 error_prob
传递给 calculate_func
,因为 error_prob
被该文件中的每个函数使用。
I don't want to pass error_prob into calculate_func, because error_prob is used by every function in that file.
如果你需要注入一个依赖,那么你需要注入它。一种可能会简化事情的可能性是将这些函数移动到 class 中,并在实例化时将 error_prob
实现设置为成员。
您可以通过导入模块来重新分配模块范围的变量。
import my_project
myproject.prob = 0.1
我有一个如下所示的文件:
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'
但目前测试文件从主文件导入 error_prob
。我希望能够从测试文件中设置或模拟 error_prob
以测试不同的行为。我该怎么做?
我不想将 error_prob
传递给 calculate_func
,因为 error_prob
被该文件中的每个函数使用。
I don't want to pass error_prob into calculate_func, because error_prob is used by every function in that file.
如果你需要注入一个依赖,那么你需要注入它。一种可能会简化事情的可能性是将这些函数移动到 class 中,并在实例化时将 error_prob
实现设置为成员。
您可以通过导入模块来重新分配模块范围的变量。
import my_project
myproject.prob = 0.1