Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest fixture with scope session running for every test

Tags:

python

pytest

Correct me if I'm wrong, but if a fixture is defined with scope="session", shouldn't it be run only once per the whole pytest run?

For example:

import pytest

@pytest.fixture
def foo(scope="session"):
    print('foooooo')


def test_foo(foo):
    assert False

def test_bar(foo):
    assert False

I have some tests that rely on data retrieved from some APIs, and instead of querying the API in each test, I rather have a fixture that gets all the data at once, and then each test uses the data it needs. However, I was noticing that for every test, a request was made to the API.


1 Answers

That's because you're declaring the fixture wrong. scope should go into the pytest.fixture decoraror parameters:

@pytest.fixture(scope="session")
def foo():
    print('foooooo')

In your code, the scope is left to default value function, that's why the fixture is being ran for each test.

like image 61
hoefling Avatar answered Feb 06 '26 05:02

hoefling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!