如果我的代码在py.test下运行,我想连接到不同的数据库.是否有一个函数可以调用或我可以测试的环境变量会告诉我是否在py.test会话下运行?处理这个问题的最佳方法是什么?
小智 50
手册中还记录了另一种方式:https : //docs.pytest.org/en/latest/example/simple.html#pytest-current-test-environment-variable
Pytest 将设置以下环境变量PYTEST_CURRENT_TEST。
检查所述变量的存在应该可靠地允许人们检测是否正在从 pytest 的保护伞中执行代码。
import os
if "PYTEST_CURRENT_TEST" in os.environ:
# We are running under pytest, act accordingly...
Run Code Online (Sandbox Code Playgroud)
ram*_*nes 37
我找到了一个更简单的解决方案:
import sys
if "pytest" in sys.modules:
...
Run Code Online (Sandbox Code Playgroud)
Pytest runner将始终加载pytest模块,使其可用sys.modules.
当然,只有当您尝试测试的代码不使用时,此解决方案才有效pytest.
Lai*_*zer 30
解决方案来自RTFM,虽然不是一个显而易见的地方.该手册在代码中也有错误,在下面更正.
检测是否在pytest运行中运行
通常,如果从测试中调用应用程序代码,则表现不同.但是,如果您必须确定您的应用程序代码是否在测试中运行,您可以执行以下操作:
Run Code Online (Sandbox Code Playgroud)# content of conftest.py def pytest_configure(config): import sys sys._called_from_test = True def pytest_unconfigure(config): import sys # This was missing from the manual del sys._called_from_test然后检查sys._called_from_test标志:
Run Code Online (Sandbox Code Playgroud)if hasattr(sys, '_called_from_test'): # called from within a test run else: # called "normally"因此在您的申请中.使用自己的应用程序模块而不是sys来处理标志也是一个好主意.
使用pytest==4.3.1上述方法失败,所以我只是去老学校检查:
if 'pytest' in sys.argv[0]:
print('pytest was called!')
Run Code Online (Sandbox Code Playgroud)