0
0
PyTesttesting~15 mins

Project structure for tests in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify pytest project structure with test discovery
Preconditions (7)
Step 1: Open terminal and navigate to project_root directory
Step 2: Run command 'pytest' to execute tests
Step 3: Observe pytest discovers and runs test_sample.py inside tests folder
✅ Expected Result: pytest runs the test function inside tests/test_sample.py and reports test passed
Automation Requirements - pytest
Assertions Needed:
Test function runs and passes
pytest discovers tests only inside the 'tests' folder as configured
Best Practices:
Use a dedicated 'tests' folder for all test files
Name test files starting with 'test_'
Configure pytest.ini with testpaths to limit discovery
Keep test code separate from application code
Automated Solution
PyTest
import subprocess
import sys

def test_pytest_project_structure():
    # Run pytest command in project_root
    result = subprocess.run([sys.executable, '-m', 'pytest'], capture_output=True, text=True)
    output = result.stdout
    # Check pytest ran tests from tests/test_sample.py
    assert 'tests/test_sample.py' in output
    # Check test passed
    assert '1 passed' in output

This test runs the pytest command in the project root folder using Python's subprocess module.

It captures the output and checks that pytest discovered and ran the test file tests/test_sample.py.

It also asserts that the test passed by looking for '1 passed' in the output.

This confirms the project structure is correct and pytest is configured to find tests only in the tests folder.

Common Mistakes - 4 Pitfalls
{'mistake': "Placing test files outside the 'tests' folder", 'why_bad': 'pytest may discover unwanted files or miss tests if not in the configured folder', 'correct_approach': "Always put test files inside a dedicated 'tests' folder"}
{'mistake': "Naming test files without 'test_' prefix", 'why_bad': "pytest by default only discovers files starting with 'test_' or ending with '_test.py'", 'correct_approach': "Name test files starting with 'test_' to ensure discovery"}
{'mistake': 'Not configuring pytest.ini with testpaths', 'why_bad': 'pytest may search entire project and run unintended files', 'correct_approach': "Add pytest.ini with 'testpaths = tests' to limit discovery"}
Mixing test code with application code
Bonus Challenge

Now add a second test file with a different test function and verify pytest runs both tests

Show Hint