【发布时间】:2018-06-15 06:43:53
【问题描述】:
我正在使用 Pytest 测试我的代码,但我遇到了一个小问题,但令人恼火。
我的程序做的第一件事就是检查是否有任何设置文件可用。如果没有,则会引发错误并调用exit()。这在正常运行时运行良好,但会与 Pytest 混淆。
我想出的解决方案是通过复制模板设置文件,在测试期间简单地创建一个临时设置文件。我已经编写并成功测试了实现这一目标的代码。
我遇到的问题是我找不到真正先于其他一切触发的 Pytest 钩子。这会导致程序在 Pytest 尝试创建临时设置文件之前抛出错误。这会导致 Pytest 在执行任何测试之前失败。
有人知道在 Pytest 执行或加载任何内容之前触发函数的方法吗?最好在 Pytest 内部。
一些代码上下文:
抛出错误并退出
这个 sn-p 在 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
【问题讨论】:
-
@progmatico 遗憾的是,这些钩子不像我需要的那样工作。就我而言,它们与
pytest_sessionstart和pytest_sessionfinish存在相同的问题,如上所示 -
可能这不是 pytest 问题,而是 python 本身。如果此代码不在 sobroutines 中,则 Python 从您的所有
import运行代码。因此,只需删除该初始化代码并显式调用它。 -
用
conftest.pystackoverflow.com/a/53690092/248616怎么样