Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse pytest fixtures

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?

like image 235
Code-Apprentice Avatar asked Sep 01 '17 18:09

Code-Apprentice


People also ask

Can a pytest fixture use another fixture?

A fixture can use multiple other fixtures. Just like a test method can take multiple fixtures as arguments, a fixture can take multiple other fixtures as arguments and use them to create the fixture value that it returns.

Are pytest fixtures cached?

Pytest only caches one instance of a fixture at a time, which means that when using a parametrized fixture, pytest may invoke a fixture more than once in the given scope.

Can you import a pytest fixture?

Use Pytest Fixtures Across Multiple Test Files With conftest.py. To make it easier on ourselves, we can define a fixture to use across multiple test files. These fixtures are defined by creating a file called conftest.py. Additionally, we can call separate files that also import the fixture from our configuration file.

How often is a fixture function in pytest executed?

Fixtures with scope session will only be executed once per session. Every time you run pytest , it's considered to be one session.


1 Answers

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

like image 197
Ricardo Avatar answered Sep 28 '22 19:09

Ricardo