Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyTest: skip entire module/file (python 2 and 3)

Tags:

python

pytest

I want to skip an entire test if imports don't work:

try:
  import networkx
except:
  import pytest
  pytest.skip()

This works fine with python-2.7 and python-3.5, both using pytest-2.8.1. When I try to run the code in python-3.6 with pytest-3.0.5 I get the following error:

Using pytest.skip outside of a test is not allowed. If you are trying to decorate a test function, use the @pytest.mark.skip or @pytest.mark.skipif decorators instead.

How can I write code/tests that works on all mentioned environments? I already tried to rewrite the except block like this but then it only works for the newest configuration:

try:
  pytest.skip()
except:
  pytestmark = pytest.mark.skip
like image 787
mattmilten Avatar asked Feb 28 '17 14:02

mattmilten


People also ask

How do I skip files in pytest?

The simplest way to skip a test function is to mark it with the skip decorator which may be passed an optional reason : @pytest. mark.

How do I run a pytest on a specific file?

We can run a specific test file by giving its name as an argument. A specific function can be run by providing its name after the :: characters. Markers can be used to group tests. A marked grouped of tests is then run with pytest -m .

Which decorator is used to skip a test unconditionally with pytest?

You can mark a test with the skip and skipif decorators when you want to skip a test in pytest .

How do you stop a test in pytest?

PyTest offers a command-line option called maxfail which is used to stop test suite after n test failures. For example, to stop the test suite after n test failures, where the value of n is 1.


2 Answers

You can use pytest.skip with allow_module_level=True to skip the remaining tests of a module:

pytest.skip(allow_module_level=True)

See example in: https://docs.pytest.org/en/latest/how-to/skipping.html#skipping-test-functions

like image 133
Conchylicultor Avatar answered Sep 22 '22 00:09

Conchylicultor


I figured it out myself. The skip block needs to check the version of pytest:

if pytest.__version__ < "3.0.0":
  pytest.skip()
else:
  pytestmark = pytest.mark.skip
like image 23
mattmilten Avatar answered Sep 25 '22 00:09

mattmilten