Skip to content

Instantly share code, notes, and snippets.

@dhermes
Last active September 30, 2017 19:26
Show Gist options
  • Save dhermes/fc2c198ca2ebece79d0a05d20a5106b4 to your computer and use it in GitHub Desktop.
Save dhermes/fc2c198ca2ebece79d0a05d20a5106b4 to your computer and use it in GitHub Desktop.
pytest: optional parameter (https://github.com/jonparrott/nox/issues/62)

By default, the "extra" test is skipped:

$ py.test test.py -vv
================== test session starts ==================
platform linux -- Python 3.6.2, ...
cachedir: .../.cache
rootdir: ${ROOTDIR}, inifile: setup.cfg
plugins: cov-2.5.1
collected 3 items

test.py::test_it[40-42] PASSED
test.py::test_it[0-2] SKIPPED
test.py::test_too[11-12-23] PASSED

========== 2 passed, 1 skipped in 0.01 seconds ==========

However, if the flag to activate it is used, the second test is run:

$ py.test test.py --hey-you-guys -vv
================== test session starts ==================
platform linux -- Python 3.6.2, ...
cachedir: .../.cache
rootdir: ${ROOTDIR}, inifile: setup.cfg
plugins: cov-2.5.1
collected 4 items

test.py::test_it[40-42] PASSED
test.py::test_it[0-2] PASSED
test.py::test_too[11-12-23] PASSED
test.py::test_too[20-31.5-51.5] PASSED

================ 4 passed in 0.01 seconds ===============

Also note the "magical" appearance of a fourth test test_too[20-31.5-51.5]. This is due to a different approach than was used to skip test_it[0-2]. Instead of using a pytest.mark to skip the case, it was instead omitted from the cases passed to pytest.mark.parametrize.

def pytest_addoption(parser):
parser.addoption(
'--hey-you-guys',
dest='hey_you_guys',
action='store_false',
help='Conditional inlcude.',
)
import pytest
HEY_YOU_GUYS = pytest.config.getoption('--hey-you-guys')
HEY_MARK = pytest.mark.skipif(
HEY_YOU_GUYS,
reason='Conditional include requested.',
)
OPTIONS = [
(11, 12, 23),
]
if not HEY_YOU_GUYS:
OPTIONS.append(
(20, 31.5, 51.5),
)
def f(n):
return n + 2
def g(x, y):
return x + y
@pytest.mark.parametrize(
'test_input,expected',
[
(40, 42),
pytest.param(0, 2, marks=HEY_MARK),
]
)
def test_it(test_input, expected):
assert f(test_input) == expected
@pytest.mark.parametrize('first,second,result', OPTIONS)
def test_too(first, second, result):
assert g(first, second) == result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment