Verify pytest test module execution and results
Preconditions (2)
✅ Expected Result: pytest runs all tests in test_sample.py and shows a summary with pass/fail status for each test
import subprocess import sys import re def test_pytest_module_execution(): # Run pytest on the test_sample.py module result = subprocess.run([sys.executable, '-m', 'pytest', 'test_sample.py', '--tb=short', '-q'], capture_output=True, text=True) output = result.stdout # Check pytest exited with code 0 (success) assert result.returncode == 0, f"pytest exited with code {result.returncode}" # Check output contains test function names and pass status assert re.search(r'test_function_one', output), "test_function_one not found in output" assert re.search(r'test_function_two', output), "test_function_two not found in output" assert re.search(r'\d+ passed', output), "No tests passed message found"
This test script runs pytest on the module test_sample.py using Python's subprocess module. It captures the output and return code.
We assert that pytest exits with code 0, meaning all tests passed. Then we check the output text to confirm the test function names appear and that the summary shows tests passed.
This approach verifies that the test module runs correctly and pytest reports results as expected.
Now add data-driven testing with 3 different inputs for one test function in the module
test_ or end with _test.py.test_ or end with _test.py. matches the correct naming pattern for pytest to find test modules automatically.test_ or end with _test.py. -> Option Dtest_ automatically as tests.test_, so pytest will recognize it as a test.test_sample.py with these functions:def test_add():
assert 1 + 1 == 2
def add():
return 1 + 1
def test_subtract():
assert 2 - 1 == 1
test_ automatically as tests.test_add and test_subtract start with test_, so pytest runs them. add does not start with test_, so it is ignored.test_add and test_subtract -> Option Ctest_math.py with this code:def test_multiply():
assert 2 * 3 == 5
test_add.py and test_subtract.py. Each file has multiple test functions starting with test_. How does pytest handle these test modules when you run pytest in the folder?test_ prefix and runs all test functions inside them.pytest in the folder, it collects tests from both test_add.py and test_subtract.py and runs all test functions starting with test_.Pass the test and this pattern moves unknown