0
0
PyTesttesting~15 mins

Test modules in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify pytest test module execution and results
Preconditions (2)
Step 1: Open terminal or command prompt
Step 2: Navigate to the directory containing test_sample.py
Step 3: Run the command 'pytest test_sample.py'
Step 4: Observe the test execution output
Step 5: Verify that all test functions in the module run and their results are displayed
✅ Expected Result: pytest runs all tests in test_sample.py and shows a summary with pass/fail status for each test
Automation Requirements - pytest
Assertions Needed:
Verify that test functions execute without errors
Verify that pytest output includes test names and pass/fail status
Best Practices:
Use descriptive test function names starting with 'test_'
Keep tests independent and isolated
Use assert statements for validation
Organize tests in modules named test_*.py
Automated Solution
PyTest
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.

Common Mistakes - 3 Pitfalls
Not capturing pytest output for verification
Using print statements instead of assert for validation
Running pytest without specifying the test module
Bonus Challenge

Now add data-driven testing with 3 different inputs for one test function in the module

Show Hint