0
0
PyTesttesting~15 mins

Conftest fixtures (shared across files) in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify shared fixture usage across multiple test files using conftest.py
Preconditions (2)
Step 1: Open conftest.py and define a fixture named 'sample_fixture' that returns the string 'shared data'
Step 2: In test_file1.py, write a test function that uses 'sample_fixture' and asserts the returned value is 'shared data'
Step 3: In test_file2.py, write another test function that uses 'sample_fixture' and asserts the returned value is 'shared data'
Step 4: Run pytest on the test directory to execute both test files
✅ Expected Result: Both test functions in test_file1.py and test_file2.py pass successfully, confirming the shared fixture from conftest.py is used correctly
Automation Requirements - pytest
Assertions Needed:
Assert that the fixture 'sample_fixture' returns the string 'shared data' in both test files
Best Practices:
Define fixtures in conftest.py to share them across multiple test files
Use the pytest fixture decorator properly
Keep test functions simple and focused on assertions
Avoid importing conftest.py explicitly in test files
Automated Solution
PyTest
import pytest

# conftest.py
@pytest.fixture
 def sample_fixture():
     return 'shared data'

# test_file1.py

def test_using_shared_fixture_1(sample_fixture):
    assert sample_fixture == 'shared data'

# test_file2.py

def test_using_shared_fixture_2(sample_fixture):
    assert sample_fixture == 'shared data'

The conftest.py file defines a fixture sample_fixture that returns a string 'shared data'. This fixture is automatically available to all test files in the same directory or subdirectories without importing it explicitly.

In test_file1.py and test_file2.py, test functions accept sample_fixture as a parameter. Pytest injects the fixture value when running the tests.

Each test asserts that the fixture returns the expected string. Running pytest will find and run both tests, confirming the shared fixture works correctly.

Common Mistakes - 3 Pitfalls
Importing conftest.py directly in test files
Defining fixtures inside test files instead of conftest.py when sharing is needed
Using the wrong decorator or missing @pytest.fixture
Bonus Challenge

Now add a fixture in conftest.py that returns different data based on a parameter, and write tests in both files to use this parameterized fixture.

Show Hint