0

I set 5 fixtures with function, class, module, package and session scopes to test1() as shown below:

import pytest

@pytest.fixture(scope='function')
def fixture_function():
    print('function')

@pytest.fixture(scope='class')
def fixture_class():
    print('class')

@pytest.fixture(scope='module')
def fixture_module():
    print('module')

@pytest.fixture(scope='package')
def fixture_package():
    print('package')

@pytest.fixture(scope='session')
def fixture_session():
    print('session')

class Test1:
    def test1(
        self,
        fixture_function,
        fixture_class,
        fixture_module,
        fixture_package,
        fixture_session
    ):
        pass

Then, I ran the command below:

pytest -q -rP

Then, each fixture ran once according to the result below:

$ pytest -q -rP
.                               [100%]
=============== PASSES =============== 
____________ Test1.test1 _____________
_______ Captured stdout setup ________
session
package
module
class
function
1 passed in 0.10s

My questions:

  1. What is the difference between function, class, module, package and session for fixture scopes in Pytest?

  2. When should I use fixture scopes in Pytest?

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
  • [Check this page from documentation](https://docs.pytest.org/en/7.4.x/reference/fixtures.html) – Nesi Aug 08 '23 at 11:56

1 Answers1

0

The fixture's state is stored within the designated "scope". The term scope refers to the parameter that determines when the fixture will be invoked. If the scope is set to function, the fixture will be invoked separately for each test as a function. Alternatively, if the scope is set to module, the fixture will only be invoked once for the entire current module.

For costly requests giving the same results, this feature optimizes the test duration.

Fixtures requiring network access depend on connectivity and are usually time-expensive to create. Extending the previous example, we can add a scope="module" parameter to the @pytest.fixture invocation to cause a smtp_connection fixture function, responsible to create a connection to a preexisting SMTP server, to only be invoked once per test module (the default is to invoke once per test function). Multiple test functions in a test module will thus each receive the same smtp_connection fixture instance, thus saving time. Possible values for scope are: function, class, module, package or session.

Source: https://docs.pytest.org/en/6.2.x/fixture.html

Julien Sorin
  • 703
  • 2
  • 12