在测试函数中执行脚本
从测试函数调用脚本没有任何问题,因此您的方法非常好。但是,我会使用参数化而不是在 for 循环中运行脚本;这样,每个脚本就可以很好地执行一次测试。如果您不喜欢长回溯,您可以自定义剪切它们pytest_exception_interact https://docs.pytest.org/en/latest/reference.html#_pytest.hookspec.pytest_exception_interacthookimpl。例子:
# conftest.py
def pytest_exception_interact(node, call, report):
excinfo = call.excinfo
if 'script' in node.funcargs:
excinfo.traceback = excinfo.traceback.cut(path=node.funcargs['script'])
report.longrepr = node.repr_failure(excinfo)
参数化测试:
# test_spam.py
import pathlib
import runpy
import pytest
scripts = pathlib.Path(__file__, '..', 'scripts').resolve().glob('*.py')
@pytest.mark.parametrize('script', scripts)
def test_script_execution(script):
runpy.run_path(script)
测试执行产量(为了测试,我创建了带有单行的简单脚本,例如assert False
or 1 / 0
:
$ pytest -v
======================================= test session starts ========================================
platform linux -- Python 3.6.8, pytest-4.6.3, py-1.8.0, pluggy-0.12.0 -- /home/hoefling/projects/.venvs/stackoverflow/bin/python3.6
cachedir: .pytest_cache
rootdir: /home/hoefling/projects/private/stackoverflow/so-56807698
plugins: mock-1.10.4, cov-2.7.1, forked-1.0.2, xdist-1.28.0, django-3.4.8
collected 3 items
test_spam.py::test_script_execution[script0] PASSED
test_spam.py::test_script_execution[script1] FAILED
test_spam.py::test_script_execution[script2] FAILED
============================================= FAILURES =============================================
____________________________________ test_script_runpy[script1] ____________________________________
> assert False
E AssertionError
scripts/script_3.py:1: AssertionError
____________________________________ test_script_runpy[script2] ____________________________________
> 1 / 0
E ZeroDivisionError: division by zero
scripts/script_2.py:1: ZeroDivisionError
================================ 2 failed, 1 passed in 0.07 seconds ================================
定制测试协议
如果您不喜欢上述解决方案,我能想到的另一件事是实现您自己的测试收集和执行协议。例子:
# conftest.py
import pathlib
import runpy
import pytest
def pytest_collect_file(parent, path):
p = pathlib.Path(str(path))
if p.suffix == '.py' and p.parent.name == 'scripts':
return Script(path, parent)
class Script(pytest.File):
def collect(self):
yield ScriptItem(self.name, self)
class ScriptItem(pytest.Item):
def runtest(self):
runpy.run_path(self.fspath)
def repr_failure(self, excinfo):
excinfo.traceback = excinfo.traceback.cut(path=self.fspath)
return super().repr_failure(excinfo)
这将收集每个.py
文件输入scripts
目录,将每个脚本包装在测试用例中并调用runpy
关于测试执行。执行日志看起来几乎相同,只是测试的名称不同。