PYTEST FIXTURE | TEST AUTOMATION| QA SDET

Опубликовано: 05 Июль 2026
на канале: Viplove QA - SDET
5,513
like

✅ Pytest Fixtures – Summary

Fixtures in pytest are used to manage setup and teardown logic for tests. They help reduce redundancy and keep test code clean and maintainable.

🔹 Basic Usage:

Defined using the @pytest.fixture decorator.

Injected into tests by naming them as parameters.

Can return data, objects, or resources needed by tests.


🔹 Example:

@pytest.fixture
def sample_data():
return [1, 2, 3]

def test_sum(sample_data):
assert sum(sample_data) == 6


---

🔸 Fixture Features

Scope Control:

Use scope to control lifespan:
function (default), class, module, session.


Autouse Fixtures:

Automatically apply a fixture to all tests in its scope without being passed explicitly.
Example: @pytest.fixture(autouse=True)


Teardown with yield:

Code after yield runs after the test finishes — useful for cleanup.


Parametrization:

Run the same test with different inputs using params:


@pytest.fixture(params=[1, 2, 3])
def val(request):
return request.param

Fixture Dependencies:

Fixtures can call other fixtures by declaring them as arguments.


Shared Fixtures with conftest.py:

Place common fixtures in conftest.py for reuse across test files — no import needed.




---

🔹 When to Use Fixtures

Use fixtures for:

Setting up test data or environment

Connecting to databases or APIs

Launching browsers or services

Cleaning up resources after test execution