测试代码是否在py.test会话中执行

Lai*_*zer 38 python pytest

如果我的代码在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)

  • 请注意,此方法仅在运行某些实际测试时才有效!当在 pytest 收集期间导入模块时,此检测将不起作用! (26认同)
  • 谢谢,@kolypto!这解释了为什么模块级“常量”为我设置不正确(就好像没有运行测试一样)。答案应该包括这个重要的事实。 (4认同)
  • 正如我从简短的调查中发现的那样,该变量在装置执行期间不可用。因此,您无法决定选择一个测试数据库来初始化它。 (2认同)

ram*_*nes 37

我找到了一个更简单的解决方案:

import sys

if "pytest" in sys.modules:
    ...
Run Code Online (Sandbox Code Playgroud)

Pytest runner将始终加载pytest模块,使其可用sys.modules.

当然,只有当您尝试测试的代码不使用时,此解决方案才有效pytest.

  • 如果你问我,似乎更清洁/更pythonic解决方案 (5认同)
  • 警告:我从这种方法中得到了误报。在非 pytest 环境中,我在 `sys.modules.keys()` 中看到了 pytest。 (3认同)
  • 更好的答案可以用于其他测试框架,如`nose` (2认同)
  • 同样,这是[用于在Django下检测py.test的推荐方法](https://github.com/pytest-dev/pytest-django/issues/333#issuecomment-302429237)。 (2认同)
  • 用作 [pytest Issue #4843](https://github.com/pytest-dev/pytest/issues/4843) 的解决方法,谢谢! (2认同)
  • @duhaime它在`sys.modules`中的唯一方式是它已经以某种方式直接导入您的代码或通过另一个导入(可能有您使用的库之一确实导入了它) . 正如我所说,“只有当您尝试测试的代码不使用 `pytest` 本身时,此解决方案才有效”。 (2认同)
  • 啊,抱歉,我没看到。我只调用“pytest”来运行我的测试 (2认同)

Lai*_*zer 30

解决方案来自RTFM,虽然不是一个显而易见的地方.该手册在代码中也有错误,在下面更正.

检测是否在pytest运行中运行

通常,如果从测试中调用应用程序代码,则表现不同.但是,如果您必须确定您的应用程序代码是否在测试中运行,您可以执行以下操作:

# 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
Run Code Online (Sandbox Code Playgroud)

然后检查sys._called_from_test标志:

if hasattr(sys, '_called_from_test'):
    # called from within a test run
else:
    # called "normally"
Run Code Online (Sandbox Code Playgroud)

因此在您的申请中.使用自己的应用程序模块而不是sys来处理标志也是一个好主意.

  • 如果您在手动代码中发现错误,请提交补丁.社区将感谢你.:) (3认同)
  • 这可能不起作用 - 在某些情况下 conftest.py 加载得太晚。请参阅https://github.com/pytest-dev/pytest-django/issues/333 (3认同)
  • 完毕。https://bitbucket.org/LevIsrael/pytest/pull-request/1/fix-example-code-in-detect-if-running-from/diff (2认同)
  • 即使上面链接的 PR 没有关闭,文档现在也会更新。这可能是因为 pytest 现在在 GitHub 上,而不是 bitbucket。 (2认同)
  • 如果在调用“pytest_unconfigure”之前崩溃会发生什么? (2认同)

duh*_*ime 9

使用pytest==4.3.1上述方法失败,所以我只是去老学校检查:

if 'pytest' in sys.argv[0]:
  print('pytest was called!')
Run Code Online (Sandbox Code Playgroud)