The Python Oracle

How do I disable a test using pytest?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Light Drops

--

Chapters
00:00 How Do I Disable A Test Using Pytest?
00:25 Answer 1 Score 55
00:57 Accepted Answer Score 405
01:41 Answer 3 Score 23
01:56 Answer 4 Score 32
02:19 Thank you

--

Full question
https://stackoverflow.com/questions/3844...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #testing #pytest

#avk47



ACCEPTED ANSWER

Score 405


Pytest has the skip and skipif decorators, similar to the Python unittest module (which uses skip and skipIf), which can be found in the documentation here.

Examples from the link can be found here:

@pytest.mark.skip(reason="no way of currently testing this")
def test_the_unknown():
    ...

import sys
@pytest.mark.skipif(sys.version_info < (3,3),
                    reason="requires python3.3")
def test_function():
    ...

The first example always skips the test, the second example allows you to conditionally skip tests (great when tests depend on the platform, executable version, or optional libraries.

For example, if I want to check if someone has the library pandas installed for a test.

import sys
try:
    import pandas as pd
except ImportError:
    pass

@pytest.mark.skipif('pandas' not in sys.modules,
                    reason="requires the Pandas library")
def test_pandas_function():
    ...



ANSWER 2

Score 55


The skip decorator would do the job:

@pytest.mark.skip(reason="no way of currently testing this")
def test_func_one():
    # ...

(reason argument is optional, but it is always a good idea to specify why a test is skipped).

There is also skipif() that allows to disable a test if some specific condition is met.


These decorators can be applied to methods, functions or classes.

To skip all tests in a module, define a global pytestmark variable:

# test_module.py
pytestmark = pytest.mark.skipif(...)



ANSWER 3

Score 32


If you want to skip the test but not hard code a marker, better use keyword expression to escape it.

pytest test/test_script.py -k 'not test_func_one'

Note: Here 'keyword expression' is basically, expressing something using keywords provided by pytest (or python) and getting something done. In above example, 'not' is a keyword.

For more info, refer this link.

More examples of keyword expression can be found in this answer.




ANSWER 4

Score 23


I'm not sure if it's deprecated, but you can also use the pytest.skip function inside of a test:

def test_valid_counting_number():
     number = random.randint(1,5)
     if number == 5:
         pytest.skip('Five is right out')
     assert number <= 3