Reputation: 185
I know I can specify a single test to run in PyTest with the following command:
py.test test.py::my_test_class::my_test_function
.
Is there a way to explicitly specify multiple tests to run, without running ALL the tests?
I could run the py.test
command in a for loop specifying a different test each time, but is there a better solution?
Upvotes: 2
Views: 2596
Reputation: 10592
You can put your tests in a file, implement the modifier hook to filter the tests to execute based on whether or not they are present in the file. Here's an example:
Test file# 1
$ cat test_foo.py
def test_001():
pass
def test_002():
pass
$
Test file# 2
$ cat test_bar.py
def test_001():
pass
def test_003():
pass
$
Source file containing tests to execute
$ cat my_tests
test_001
test_002
$
Modifier hook
$ 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))
$
Execution output
$ 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
$
Upvotes: 2