24

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
mattmilten
  • 6,242
  • 3
  • 35
  • 65

3 Answers3

21

A more straightforward solution would be to use pytest.importorskip instead.

Matthew Strawbridge
  • 19,940
  • 10
  • 72
  • 93
The Compiler
  • 11,126
  • 4
  • 40
  • 54
17

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

Conchylicultor
  • 4,631
  • 2
  • 37
  • 40
10

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
mattmilten
  • 6,242
  • 3
  • 35
  • 65