我知道我可以使用以下命令指定在PyTest中运行的单个测试:
py.test test.py::my_test_class::my_test_function
。
有没有办法显式指定要运行的多个测试,而不运行所有测试?
我可以在for循环中运行py.test
命令,每次指定一个不同的测试,但是有更好的解决方案吗?
答案 0 :(得分:2)
您可以将测试放在一个文件中,实现修饰符挂钩,根据文件中是否存在测试来过滤测试。这是一个例子:
测试文件#1
$ cat test_foo.py
def test_001():
pass
def test_002():
pass
$
测试文件#2
$ cat test_bar.py
def test_001():
pass
def test_003():
pass
$
包含要执行的测试的源文件
$ cat my_tests
test_001
test_002
$
修改器挂钩
$ cat conftest.py
import pytest
def pytest_addoption(parser):
parser.addoption("--testsource", action="store", default=None,
help="File containing tests to run")
def pytest_collection_modifyitems(session, config, items):
testsource = config.getoption("--testsource")
if not testsource:
return
my_tests = []
with open(testsource) as ts:
my_tests = list(map(lambda x: x.strip(),ts.readlines()))
selected = []
deselected = []
for item in items:
deselected.append(item) if item.name not in my_tests else selected.append(item)
if deselected:
config.hook.pytest_deselected(items=deselected)
items[:] = selected
print('Deselected: {}'.format(deselected))
print('Selected: {}'.format(items))
$
执行输出
$ py.test -vs --testsource my_tests
Test session starts (platform: linux, Python 3.5.1, pytest 2.8.7, pytest-sugar 0.5.1)
cachedir: .cache
rootdir: /home/sharad/tmp, inifile:
plugins: cov-2.2.1, timeout-1.0.0, sugar-0.5.1, json-0.4.0, html-1.8.0, spec-1.0.1
Deselected: [<Function 'test_003'>]
Selected: [<Function 'test_001'>, <Function 'test_001'>, <Function 'test_002'>]
test_bar.pytest_001 ✓ 33% ███▍
test_foo.pytest_001 ✓ 67% ██████▋
test_foo.pytest_002 ✓ 100% ██████████
Results (0.05s):
3 passed
1 deselected
$