[Python] function vs class vs module vs package vs session for fixture scopes in Pytest

Discussão em 'Python' iniciado por Stack, Setembro 4, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página