我正在使用 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/