Testpaths configuration in PyTest - Build an Automation Script
import subprocess import os import sys import tempfile import shutil def test_pytest_runs_only_testpaths(): # Create a temporary directory to simulate project structure temp_dir = tempfile.mkdtemp() try: # Create 'tests/unit' and 'tests/integration' directories unit_dir = os.path.join(temp_dir, 'tests', 'unit') integration_dir = os.path.join(temp_dir, 'tests', 'integration') os.makedirs(unit_dir) os.makedirs(integration_dir) # Create a test file in 'tests/unit' unit_test_file = os.path.join(unit_dir, 'test_unit_sample.py') with open(unit_test_file, 'w') as f: f.write('def test_unit_pass():\n assert True\n') # Create a test file in 'tests/integration' integration_test_file = os.path.join(integration_dir, 'test_integration_sample.py') with open(integration_test_file, 'w') as f: f.write('def test_integration_pass():\n assert True\n') # Create pytest.ini with testpaths set to 'tests/unit' pytest_ini = os.path.join(temp_dir, 'pytest.ini') with open(pytest_ini, 'w') as f: f.write('[pytest]\ntestpaths = tests/unit\n') # Run pytest in the temp_dir result = subprocess.run( [sys.executable, '-m', 'pytest', '--tb=short', '-q'], cwd=temp_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) # Check that test from 'tests/unit' ran assert 'test_unit_pass' in result.stdout, 'Unit test did not run as expected' # Check that test from 'tests/integration' did NOT run assert 'test_integration_pass' not in result.stdout, 'Integration test should not run' # Check pytest exit code is 0 (success) assert result.returncode == 0, f'Pytest failed with exit code {result.returncode}' finally: shutil.rmtree(temp_dir)
This test creates a temporary project structure with two test directories: tests/unit and tests/integration. It writes one simple passing test in each directory.
It then creates a pytest.ini file in the root of this temporary project, configuring testpaths = tests/unit. This tells pytest to only look for tests inside tests/unit.
The test runs pytest as a subprocess in the temporary directory and captures the output.
Assertions check that the test from tests/unit was run (its name appears in output), and the test from tests/integration was not run (its name does not appear). It also checks that pytest exited successfully.
This approach uses temporary directories to avoid affecting the real project and subprocess to run pytest as a user would. It verifies the testpaths configuration works as expected.
Now add data-driven testing with 3 different testpaths configurations and verify pytest runs tests only from those paths each time
Practice
testpaths setting in a pytest.ini file?Solution
Step 1: Understand the role of
Thetestpathstestpathssetting tells pytest where to find test files by listing directories.Step 2: Compare with other options
Other options like test order, timeout, or report format are configured differently, not withtestpaths.Final Answer:
To specify which folders pytest should look in for test files -> Option BQuick Check:
testpaths = test folders [OK]
- Confusing testpaths with test order settings
- Thinking testpaths sets test timeouts
- Assuming testpaths changes report style
testpaths in pytest.ini to look in folders tests and integration?Solution
Step 1: Check pytest.ini syntax for testpaths
Inpytest.ini,testpathslists folders separated by spaces without quotes or commas.Step 2: Validate each option
[pytest] testpaths = tests integration uses space-separated folder names correctly. Options A and D use quotes or brackets incorrectly. [pytest] testpaths = tests,integration uses commas which pytest does not accept here.Final Answer:
[pytest] testpaths = tests integration -> Option AQuick Check:
Space-separated folder names, no quotes [OK]
- Using commas instead of spaces
- Adding quotes or brackets around folder names
- Placing testpaths outside [pytest] section
pytest.ini content:[pytest] testpaths = tests integration
And this folder structure:
project/
tests/
test_alpha.py
integration/
test_beta.py
docs/
test_docs.pyWhich test files will pytest discover and run?
Solution
Step 1: Identify folders listed in testpaths
Thetestpathssetting includestestsandintegrationfolders only.Step 2: Match test files in those folders
Filestest_alpha.pyintestsandtest_beta.pyinintegrationwill be found.test_docs.pyis indocs, which is not listed.Final Answer:
test_alpha.py and test_beta.py only -> Option DQuick Check:
Only testpaths folders' tests run [OK]
- Assuming all test files in project run
- Including tests from folders not in testpaths
- Confusing folder names with test file names
testpaths = tests in pytest.ini but pytest still discovers tests in other folders. What is the most likely cause?Solution
Step 1: Understand pytest config precedence
pytest can read multiple config files liketox.iniorsetup.cfgthat may overridepytest.ini.Step 2: Check for conflicting configs
If tests outsidetestsrun, likely another config file sets differenttestpathsor disables it.Final Answer:
There is another config file overriding testpaths -> Option AQuick Check:
Multiple configs can override testpaths [OK]
- Assuming pytest.ini changes apply without reload
- Thinking testpaths filters test names only
- Believing pytest ignores testpaths by default
unit_tests and api_tests folders, but exclude api_tests/slow. How can you configure pytest.ini using testpaths and other settings to achieve this?Solution
Step 1: Use testpaths to include desired folders
Settestpaths = unit_tests api_teststo include both folders.Step 2: Exclude the slow subfolder with norecursedirs
Usenorecursedirs = api_tests/slowto prevent pytest from searching inside that subfolder.Step 3: Verify other options are incorrect
[pytest] testpaths = unit_tests api_tests/slow norecursedirs = api_tests includes the slow folder in testpaths, which is wrong. [pytest] testpaths = unit_tests norecursedirs = api_tests/slow excludes api_tests entirely. [pytest] testpaths = unit_tests api_tests ignore = api_tests/slow usesignorewhich is not a valid pytest.ini setting.Final Answer:
[pytest] testpaths = unit_tests api_tests norecursedirs = api_tests/slow -> Option CQuick Check:
Include folders with testpaths, exclude subfolders with norecursedirs [OK]
- Including excluded folders in testpaths
- Using invalid config keys like ignore
- Excluding whole folders instead of subfolders
Ready to prove it?
Pass the test and this pattern moves unknown
