首页 > 解决方案 > 如何设置或模拟测试文件中的变量?

问题描述

我有一个看起来像这样的文件:

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_probcalculate_func因为error_prob该文件中的每个函数都使用它。

标签: pythonpython-3.xunit-testingpython-unittest

解决方案


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

import my_project

myproject.prob = 0.1

推荐阅读