python - 在 Pytest 运行之前执行一些代码

标签 python pytest

我正在使用 Pytest 测试我的代码,我遇到了一个小问题,但这是一个令人恼火的问题。

我的程序做的第一件事就是检查是否有可用的设置文件。如果没有,它会抛出错误并调用 exit()。这在正常运行时运行良好,但会混淆 Pytest。

我想到的解决方案是通过复制模板设置文件,在测试期间简单地创建一个临时设置文件。我已经编写并成功测试了实现该目标的代码。

我遇到的问题是我找不到真正先于其他一切触发的 Pytest Hook 。这会导致程序在 Pytest 尝试创建临时设置文件之前抛出错误。这导致 Pytest 在执行任何测试之前失败。

有谁知道在 Pytest 执行或加载任何内容之前触发函数的方法吗?最好在 Pytest 本身内。

一些代码上下文:

抛出错误并退出

此代码段在导入 settings 模块时运行。

if len(cycles) == 0:
    log.error("No setting files found. Please create a file " +
              "in the `settings` folder using the Template.py.")
    exit()

创建临时设置文件

这段代码应该是 Pytest 运行的第一件事。

def pytest_sessionstart(session):
    """ Create a test settings file """
    folderPath = os.path.dirname(os.path.abspath(__file__))
    folderPath = os.path.split(folderPath)[0] + "/settings"

    srcfile = folderPath + '/Template.py'
    dstfile = folderPath + '/test.py'

    shutil.copy(srcfile, dstfile)

删除临时设置文件

这段代码应该是 Pytest 运行的最后一件事。

def pytest_sessionfinish(session, exitstatus):
    """ Delete the test settings file """
    folderPath = os.path.dirname(os.path.abspath(__file__))
    folderPath = os.path.split(folderPath)[0] + "/settings"

    os.remove(folderPath + "/test.py")

Pytest 输出

禁用了对 exit() 的调用,因此您可以看到执行顺序。

Lakitna$ pytest -v -s
 No setting files found. Please create a file in the `settings` folder using the Template.py. 
TEMPORARY SETTINGS FILE CREATED
========================= test session starts ==========================
platform darwin -- Python 3.6.4, pytest-3.3.1, py-1.5.2, pluggy-0.6.0 -- /usr/local/opt/python3/bin/python3.6
cachedir: .cache
rootdir: /Users/lakitna/Documents/Github/Onaeri-tradfri/Onaeri, inifile:
collected 24 items

最佳答案

使用以下代码将 conftest.py 添加到您的项目并将您的代码添加到方法 pytest_configure

def pytest_configure(config):
    pass # your code goes here

# other config

关于python - 在 Pytest 运行之前执行一些代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48113848/

相关文章:

python - Matrix (scipy sparse) - Matrix (dense; numpy array) 乘法效率

python - 合并组内连续的记录

python - 运行 pytest 测试套件时的初始和最终检查

python - 如何在pytest中monkeypatch动态类属性

python - 如何将字典的字典传递给 pytest

python - pytest.main ('-s' ) 应该运行两次测试吗?

python - 在 python 包中使用另一个文件中的类并在 __init__() 中发生冲突

python - 如何阻止非数字输入导致 Python 程序崩溃?

python - 如何编写一个Python程序来读取输入并将其转换为带有 turtle 图形的预定义14段字符?

python - 为什么 py.test 将我的 xfail 测试显示为已跳过?