@pytest.fixture(scope=session) - called multible times im same testrun

47 views Asked by At

Im going to use a pytest fixture, which is created in the begin of my large testrun, used by every test in every file and module and destroyed in the end. How ever, for every file a new instance of the fixture is created.

I would expect that my_fixture is only created once per testrun, as the scope of it is session.

What it actually does is to be created for each file.py and destroy in the end of the session/testrun. Idk why.

How can I implement a fixture, that is called in the begin of a session/testraun and only destroyed in the end?

Like a Serial connection which I'm going to open once per run.

Setup

Directory setup

/test/fixture_1.py
/test/test_1.py
/test/test_2.py
/pytest.ini

Chronological setup plan. Mind that there are SETUP and TEARDOWN steps for every file. I would expect one SETUP and one TEARDOWN per testrun hat the Begin and the end.

(venv) PS C:\tmp_test_pytest> pytest -m single_source  -s --setup-plan                             
============================ test session starts ================================
platform win32 -- Python 3.10.4, pytest-7.4.3, pluggy-1.3.0
rootdir: C:\tmp_test_pytest
configfile: pytest.ini
collected 3 items           

test\test_1.py
SETUP    S my_fixture
        test/test_1.py::test_from_other_file_src1 (fixtures used: my_fixture)
test\test_2.py
SETUP    S my_fixture
        test/test_2.py::test_from_other_file_src21 (fixtures used: my_fixture)
        test/test_2.py::test_from_other_file_src22 (fixtures used: my_fixture)
TEARDOWN S my_fixture
TEARDOWN S my_fixture

file: /test/fixture_1.py

import pytest
import datetime
import time
import sys


@pytest.fixture(scope="session")
def my_fixture():
    stamp = datetime.datetime.now().strftime("%H:%M:%S.%f")
    time.sleep(5)
    print("huhu", file=sys.stderr)
    return stamp

files: /test/test_[1/2].py

from test.fixture_1 import my_fixture
@pytest.mark.single_source
def test_from_other_file_src[1/21,22](my_fixture):
    print(f"test_from_other_file: {my_fixture}", file=sys.stderr)

file pytest.ini

[pytest]
markers =
    single_source: single source, same import path
0

There are 0 answers