From c847b83d562e48db4b5f90c4c1bd697dfbf912c1 Mon Sep 17 00:00:00 2001 From: Felipe Dau Date: Wed, 9 Aug 2017 02:51:07 +0000 Subject: [PATCH 1/2] Use `pytest_collection_modifyitems()` in the run/skip option example --- doc/en/example/simple.rst | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/doc/en/example/simple.rst b/doc/en/example/simple.rst index f76d39264..f5162ca44 100644 --- a/doc/en/example/simple.rst +++ b/doc/en/example/simple.rst @@ -127,7 +127,7 @@ Control skipping of tests according to command line option .. regendoc:wipe Here is a ``conftest.py`` file adding a ``--runslow`` command -line option to control skipping of ``slow`` marked tests: +line option to control skipping of ``pytest.mark.slow`` marked tests: .. code-block:: python @@ -136,7 +136,16 @@ line option to control skipping of ``slow`` marked tests: import pytest def pytest_addoption(parser): parser.addoption("--runslow", action="store_true", - help="run slow tests") + default=False, help="run slow tests") + + def pytest_collection_modifyitems(config, items): + if config.getoption("--runslow"): + # --runslow given in cli: do not skip slow tests + return + skip_slow = pytest.mark.skip(reason="need --runslow option to run") + for item in items: + if "slow" in item.keywords: + item.add_marker(skip_slow) We can now write a test module like this: @@ -146,17 +155,11 @@ We can now write a test module like this: import pytest - slow = pytest.mark.skipif( - not pytest.config.getoption("--runslow"), - reason="need --runslow option to run" - ) - - def test_func_fast(): pass - @slow + @pytest.mark.slow def test_func_slow(): pass @@ -170,7 +173,7 @@ and when running it will see a skipped "slow" test:: test_module.py .s ======= short test summary info ======== - SKIP [1] test_module.py:14: need --runslow option to run + SKIP [1] test_module.py:8: need --runslow option to run ======= 1 passed, 1 skipped in 0.12 seconds ======== From acd3c4fbc4eae188d9f3c570c878baaa07f2b9fb Mon Sep 17 00:00:00 2001 From: Felipe Dau Date: Wed, 9 Aug 2017 02:57:36 +0000 Subject: [PATCH 2/2] Update changelog for #2653 --- changelog/2653.doc | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog/2653.doc diff --git a/changelog/2653.doc b/changelog/2653.doc new file mode 100644 index 000000000..202a06da9 --- /dev/null +++ b/changelog/2653.doc @@ -0,0 +1 @@ +In one of the simple examples, use `pytest_collection_modifyitems()` to skip tests based on a command-line option, allowing its sharing while preventing a user error when acessing `pytest.config` before the argument parsing.