python - 在 pytest 类方法中设置全局变量
问题描述
我有一个应用程序,它在启动时从远程源读取一些配置设置并将它们存储在全局范围内。此应用程序中的函数使用该全局配置中的设置。从功能上讲,它最终看起来像这样......
def define_globals():
global MY_THRESHOLD
MY_THRESHOLD = 123
def my_func(my_input):
return my_input > MY_THRESHOLD
def run():
define_globals()
my_func(122)
我想my_func
使用 pytest 进行测试,但在测试期间未定义 MY_THRESHOLD。对测试有点新,所以稍微研究了一下固定装置。有这样的东西,但在运行测试时仍然没有找到全局。
import pytest
import my_file
@pytest.fixture()
def set_gloabls():
global MY_THRESHOLD
MY_THRESHOLD = 123
class TestMyApplication(object):
@pytest.mark.usefixtures("set_gloabls")
def test_my_func(self):
assert my_file.my_func(122) == False
我想我认为夹具将在被测试文件的范围内工作?IDK 很难弄清楚如何在不更改应用程序代码的情况下做到这一点。
解决方案
重申我在评论中所说的,“全局”变量只是模块中的“全局”。因此,当您尝试MY_THRESHOLD
在测试模块中进行设置时,这将永远不会在您的my_file
模块中可见。
你需要做这样的事情:
import pytest
import my_file
@pytest.fixture()
def set_globals():
my_file.MY_THRESHOLD = 123
class TestMyApplication(object):
@pytest.mark.usefixtures("set_globals")
def test_my_func(self):
assert my_file.my_func(122) == False
事实上,因为它是一个全局的,你也可以这样做(假设MY_THRESHOLD
在你的测试中这是一个常数):
import pytest
import my_file
my_file.MY_THRESHOLD = 123
class TestMyApplication(object):
def test_my_func(self):
assert my_file.my_func(122) == False
推荐阅读
- c# - 如何将多个数据传递给水晶报表参数
- c# - 如何将 WiX 的“产品版本”自动设置为 Asp.NET Core 的“包版本”?
- excel - 嵌套if计算在excel中
- javascript - 在 WordPress 中使用 javascript 的 iframe 动态 url
- uwp - UWP 发布构建失败
- php - 更改字符串php中括号内的所有文本颜色
- delphi - 在 Delphi / C++ Builder 中使用 WebView (EdgeHTML)
- c# - 如何在 void 中返回变量
- javascript - 如何使用 Jest 将 prop 中的 spyOn 方法传递给组件?
- nginx - Tengine Web 服务器默认安装支持哪些脚本语言?