1

I would like to use a "helper" decorator in multiple pytest test files:

min311 = pytest.mark.skipif(sys.version_info < (3,11), reason="You need at least Python v3.11 to run this test")

...
@min311
def test_...

Which is the best place for min311? It is not imported automatically from conftest.py.

FERcsI
  • 388
  • 1
  • 10

1 Answers1

0

Given this layout:

.
├── src
│   ├── conftest.py
│   └── mycode
│       ├── __init__.py
│       └── main.py
└── tests
    ├── conftest.py
    ├── __init__.py
    └── test_mycode.py

4 directories, 6 files

If I define min311 in tests/conftest.py, then in test_mycode.py I can write:

from tests.conftest import min311

@min311
def test_something():
  ...

This assumes that we are running pytest from the top-level directory.

This also works for the simpler layout:

.
├── conftest.py
├── mycode
│   ├── __init__.py
│   └── main.py
└── tests
    ├── conftest.py
    ├── __init__.py
    └── test_mycode.py

If you don't want to import from conftest directly, just move the decorator definition somewhere more palatable. I've seen a number of projects that include something like a test_helpers module in their code:

.
├── conftest.py
├── mycode
│   ├── __init__.py
│   ├── main.py
│   └── test_helpers.py
└── tests
    ├── conftest.py
    └── test_mycode.py

Then you can:

from mycode.test_helpers import min311
larsks
  • 277,717
  • 41
  • 399
  • 399
  • Yes, I can import conftest directly, but I found multiple counter-recommendations to import conftest explicitely into test files. – FERcsI Jan 27 '23 at 16:37