0
0
PyTesttesting~15 mins

setup.cfg configuration in PyTest - Build an Automation Script

Choose your learning style9 modes available
Configure pytest options using setup.cfg and verify test discovery
Preconditions (2)
Step 1: Create a setup.cfg file in the project root
Step 2: Add pytest configuration to setup.cfg to specify test paths and markers
Step 3: Run pytest from the command line without additional arguments
Step 4: Observe that pytest discovers and runs tests according to setup.cfg settings
✅ Expected Result: Pytest runs tests found in the configured test paths and applies any specified markers or options from setup.cfg
Automation Requirements - pytest
Assertions Needed:
Verify pytest discovers the test_sample.py test file
Verify the test function inside test_sample.py runs and passes
Verify pytest output includes configured markers or options
Best Practices:
Use setup.cfg for pytest configuration instead of command line flags
Keep test files and functions named according to pytest conventions
Use pytest's capsys or caplog fixtures to capture output for assertions
Automated Solution
PyTest
[pytest]
testpaths = tests
markers =
    smoke: mark a test as smoke test

# test_sample.py file content

def test_example():
    assert 1 + 1 == 2

# Command to run in terminal:
# pytest

# Expected output includes:
# - test discovery in 'tests' folder
# - test_example passes

The setup.cfg file is configured with a [pytest] section. It sets testpaths = tests so pytest looks for tests inside the tests folder. It also defines a custom marker smoke for demonstration.

The test_sample.py file contains a simple test function test_example that asserts 1 + 1 equals 2.

Running pytest in the terminal will use the setup.cfg configuration automatically. Pytest will discover tests in the tests directory and run test_example. The test should pass, confirming the configuration works.

This approach avoids passing command line options every time and centralizes test configuration.

Common Mistakes - 3 Pitfalls
{'mistake': 'Placing pytest configuration in the wrong section or file', 'why_bad': "Pytest will ignore configuration if it's not under the correct [pytest] section in setup.cfg", 'correct_approach': 'Always put pytest options under the [pytest] section in setup.cfg'}
{'mistake': 'Naming test files or functions incorrectly', 'why_bad': "Pytest won't discover tests if files/functions don't follow naming conventions (e.g., test_*.py, test_*)", 'correct_approach': "Name test files starting with 'test_' and test functions starting with 'test_'"}
Running pytest with conflicting command line options overriding setup.cfg
Bonus Challenge

Now add a custom marker 'smoke' in setup.cfg and write a test that uses this marker. Run pytest to verify the marker is recognized.

Show Hint