python - 如何设置或模拟测试文件中的变量?
问题描述
我有一个看起来像这样的文件:
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
该文件中的每个函数都使用它。
解决方案
您可以通过导入模块来重新分配模块范围的变量。
import my_project
myproject.prob = 0.1
推荐阅读
- php - 试图与我的 docker consul 中的外部 ip 通信
- php - 如何获取特定行的总和
- mysql - 使用 Mysql 获取记录的 LoopBack 4 REST API 示例
- hadoop - 如何使用 apache nifi 将多个 json 文件加载到具有正确映射的多个配置单元表中?
- python - 我可以将小图像(13x12)随机添加到像素数组(与我的小图像大小相同的随机像素)吗
- python - 如何在 python 的 sklearn 中使用 gridsearchcv 执行特征选择
- php - 正则表达式匹配(1 个或多个)包含空行的 php heredocs
- r - 从存储在列表中的 data.frame 调用变量
- django - 您在 Django 中创建模型的过程是什么?
- angular - 如何在这个组件中实现这个 ionic 3 无限滚动?