由 neevop 七月 3, 2023
test fixture - setup
# define
import pytest
@pytest.fixture
def fixture_1():
return value()
# access
def test_1(fixture_1):
assert fixture_1 == "demo_value"
Setup, Teardown
@pytest.fixture
def fixture_1():
some_methods()
...
yield fixture_1
fixture_1.cleanup()
# usage
@pytest.fixture
def fixture():
fixture = component1()
yield fixture
fixture.cleanup()
to enable a teardown section, use yield to return the value and then add the tear down code after.
- returns the created / configured component
- tear down happens after the
yield
code
scope
@pytest.fixture(scope='function')
def component_1():
...
define the scope or lifetime of a fixture.
fixture are only created once in a given scope. function
is the default scope.
shared fixtures / conftest.py
place fixtures that are shared across test files into conftest.py
.
# conftest.py
@pytest.fixture
def shared_fixture_1():
return ...
fixture defined in the conftest.py
in the root test folder are shared across all test files.
fixture defined in the conftest.py
in a module folder are only accessiable from tests in that folder.