8

I am writing some tests using pytest many of which have similar fixtures. I want to put these "global" fixtures in a single file so that they can be reused across multiple test files. My first thought was to create a fixtures.py file such as

import pytest


@pytest.fixture()
def my_fixture():
    # do something

Now how do I use this fixture in my_tests.py?

def test_connect(my_fixture):
    pass

This gives fixture 'my_fixture' not found. I can from fixtures import my_fixture. What is the suggested solution to this situation?

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268

2 Answers2

16

Pytest will share the fixtures in conftest.py automatically. Move the shared fixture from fixtures.py to conftest.py.

Ricardo
  • 587
  • 5
  • 14
  • While this is probably a good idea to avoid lots of database connections, this does not address the issue in my question about how to import the fixture to the test file. – Code-Apprentice Sep 01 '17 at 18:24
  • 1
    Note: you'll want to put these in *conftest.py* inside your tests directory — pytest will search for fixtures in *conftest.py* – theY4Kman Sep 01 '17 at 18:26
  • Pytest does **not** share the fixture automatically in my current code. See the error message in my original question. – Code-Apprentice Sep 01 '17 at 18:32
  • 1
    @Code-Apprentice you need to rename `fixtures.py` to `conftest.py` and add the `scope='session'` parameter. – Ricardo Sep 01 '17 at 18:37
  • 1
    The example database fixture is unimportant to my core question. I have edited your answer with the correct solution, which you mentioned in your last comment. – Code-Apprentice Sep 01 '17 at 18:41
  • Also, FYI: if you ever want to restructure the fixtures out to `fixtures.py`, use `from fixtures import *` in your `conftest.py`. Be wary, though: `from xyz import *` will ignore anything whose name starts with an underscore, unless explicitly noted in `__all__` – theY4Kman Sep 01 '17 at 18:48
  • Is there a way to do the above solution?? I mean instead of putting it in conftest can I put it in some other location?? – Invictus May 24 '18 at 21:52
0

Fixtures located in a conftest.py file have vectical scoping with respect to the visibility of the fixture variable to test modules. This means that all test modules located as a sibling in the directory where the conftest.py file is located, or any subdirectories beneath that directory can all see the fixtures present in the conftest.py module.

That is a particular form of reuse but not always desired. If you want to reuse horizontally across test projects located in entirely different folders then you must put the fixtures within a "plugin module".

Take a look at these answers to get a sense of the possibilities

jxramos
  • 7,356
  • 6
  • 57
  • 105