0
0
PyTesttesting~15 mins

Running tests (pytest command) - Build an Automation Script

Choose your learning style9 modes available
Run pytest tests and verify output
Preconditions (3)
Step 1: Open a terminal or command prompt
Step 2: Navigate to the directory containing test_sample.py
Step 3: Run the command: pytest
Step 4: Observe the test execution output in the terminal
✅ Expected Result: pytest runs all tests in test_sample.py and shows a summary with number of tests passed or failed
Automation Requirements - pytest
Assertions Needed:
Verify that pytest command runs without errors
Verify that the test output contains '1 passed' for the sample test
Best Practices:
Use assert statements inside test functions
Keep test files and functions named with 'test_' prefix
Run pytest from the command line in the correct directory
Automated Solution
PyTest
import subprocess
import sys

def test_run_pytest_command():
    # Run pytest command on test_sample.py
    result = subprocess.run([sys.executable, '-m', 'pytest', 'test_sample.py'], capture_output=True, text=True)
    # Check that pytest exited with code 0 (success)
    assert result.returncode == 0, f"pytest failed with code {result.returncode}"
    # Check output contains '1 passed' indicating one test passed
    assert '1 passed' in result.stdout, "Expected '1 passed' in pytest output"

This test runs the pytest command on the test_sample.py file using Python's subprocess module.

We capture the output and check the return code to ensure pytest ran successfully.

Then we assert that the output contains '1 passed' which means one test passed as expected.

This simulates running pytest from the command line and verifies the test execution result.

Common Mistakes - 3 Pitfalls
Not capturing output from the pytest command
Running pytest without specifying the test file or directory
Not checking the return code of the pytest command
Bonus Challenge

Now add data-driven testing by running pytest on three different test files and verify each output

Show Hint