Basic Test Execution
The simplest way to run tests is to execute pytest in your project directory:
pytest
This discovers and runs all tests in the current directory and subdirectories.
Running Specific Files
You can target a specific test file:
pytest tests/test_login.py
Or run a specific test function within a file:
pytest tests/test_login.py::test_valid_login
Useful CLI Flags
pytest offers many command-line options to control test execution:
# Verbose output - show each test name
pytest -v
# Stop after first failure
pytest -x
# Run last failed tests only
pytest --lf
# Show print output (capture off)
pytest -s
# Run tests in parallel (requires pytest-xdist)
pytest -n auto
# Show the N most recent failures
pytest --tb=short
Selecting Tests with -k
The -k flag lets you filter tests by name expression:
# Run tests whose names contain "login"
pytest -k login
# Run tests whose names do NOT contain "slow"
pytest -k "not slow"
# Combine expressions
pytest -k "login or logout"
This is useful when you want to run a subset of tests without modifying your code.
Listing Tests
To see which tests would be run without actually running them:
# List all collected tests
pytest --collect-only
# List tests matching a keyword
pytest --collect-only -k login