问题描述
如果我的代码在 py.test 下运行,我想连接到不同的数据库.是否有一个可以调用的函数或一个我可以测试的环境变量来告诉我是否在 py.test 会话下运行?处理这个问题的最佳方法是什么?
I'd like to connect to a different database if my code is running under py.test. Is there a function to call or an environment variable that I can test that will tell me if I'm running under a py.test session? What's the best way to handle this?
推荐答案
一个解决方案来自 RTFM,虽然不是在一个明显的地方.手册也有代码错误,在下面更正.
A solution came from RTFM, although not in an obvious place. The manual also had an error in code, corrected below.
检测是否在 pytest 运行中运行
通常让应用程序代码表现不同是个坏主意如果从测试中调用.但是,如果您绝对必须查明您的应用程序代码正在从测试中运行,您可以执行以下操作这个:
Usually it is a bad idea to make application code behave differently if called from a test. But if you absolutely must find out if your application code is running from a test you can do something like this:
# 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._call_from_test 标志:
and then check for the sys._called_from_test flag:
if hasattr(sys, '_called_from_test'):
# called from within a test run
else:
# called "normally"
相应地在您的应用程序中.使用自己的也是一个好主意应用程序模块而不是 sys 用于处理标志.
accordingly in your application. It’s also a good idea to use your own application module rather than sys for handling flag.
这篇关于测试代码是否在 py.test 会话中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!