0
0
PyTesttesting~15 mins

pyproject.toml configuration in PyTest - Build an Automation Script

Choose your learning style9 modes available
Configure pytest using pyproject.toml and verify test discovery
Preconditions (2)
Step 1: Create a pyproject.toml file in the project root
Step 2: Add pytest configuration section to pyproject.toml to set test paths and markers
Step 3: Run pytest from the command line without additional arguments
Step 4: Observe pytest discovers and runs the test_sample.py test
Step 5: Verify pytest output shows the test passed
✅ Expected Result: pytest discovers tests according to pyproject.toml settings and runs them successfully with a passing result
Automation Requirements - pytest
Assertions Needed:
Verify pytest exit code is 0 (success)
Verify output contains the test function name
Verify output shows tests passed
Best Practices:
Use pyproject.toml for pytest configuration instead of command line flags
Keep test files named with test_ prefix for automatic discovery
Use pytest's built-in assertion introspection
Automated Solution
PyTest
[tool.pytest.ini_options]
testpaths = ["tests"]
markers = ["smoke: quick smoke tests"]

# test_sample.py file content

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

# To run the test, execute in terminal:
# pytest

# The test will be discovered in the 'tests' folder as configured in pyproject.toml

# Sample command line output expected:
# ============================= test session starts =============================
# collected 1 item
#
# tests/test_sample.py .                                                     [100%]
#
# ============================== 1 passed in 0.01s ==============================

The pyproject.toml file configures pytest to look for tests in the tests folder and defines a custom marker smoke. This replaces the need to pass command line options each time.

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

Running pytest in the terminal will automatically discover tests in the tests folder as specified, run them, and show the results.

This setup follows best practices by centralizing configuration and using pytest's default discovery conventions.

Common Mistakes - 3 Pitfalls
Not placing pyproject.toml in the project root directory
Using incorrect section name in pyproject.toml (e.g., [pytest] instead of [tool.pytest.ini_options])
{'mistake': "Not naming test files or functions with the 'test_' prefix", 'why_bad': 'pytest will not discover tests automatically, causing zero tests to run', 'correct_approach': "Name test files and functions starting with 'test_' to enable automatic discovery"}
Bonus Challenge

Now add a custom marker 'slow' in pyproject.toml and write two tests, one marked 'slow' and one normal. Run pytest to only execute the normal tests.

Show Hint