user4093955
user4093955

Reputation:

pytest fixture with scope session running for every test

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.

Upvotes: 3

Views: 1014

Answers (1)

hoefling
hoefling

Reputation: 66251

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.

Upvotes: 5

Related Questions