Write unit tests with pytest using assert statements
Organize tests in test files and run them from the terminal
Test exception handling and edge cases
Understand test-driven development (TDD) and test coverage
✅ Test Runner Simulator
Click "Run Tests" to simulate running pytest on a set of test cases. Edit which tests pass or fail, then see the output.
Why Test?
Tests are automated checks that your code does what you intend. Without tests, you find bugs by running the whole program and manually checking output. With tests, you can refactor code confidently — if the tests pass, the behavior is unchanged.
Employers expect testing skills. GitHub Actions, CI/CD pipelines, and code reviews all depend on automated tests.
pytest
pytest is the most popular Python testing framework. A test is any function that starts with test_. pytest discovers and runs them automatically. Use assert to check expected values. Run with pytest in the terminal.
assert result == expected — basic assertion. If it fails, pytest shows the actual vs. expected values.
pytest.raises(ExceptionType) — asserts that the code raises a specific exception.
Test-Driven Development
TDD means writing tests before writing the code. Red → Green → Refactor: write a failing test (red), write just enough code to pass it (green), then improve the code without breaking the test (refactor). This forces you to think clearly about requirements before coding.
Quick Check
1. How does pytest find test functions automatically?
You must register each test in a configuration file
It discovers functions whose names start with test_ in files starting with test_
All functions in the tests/ folder are run regardless of name
You import pytest and decorate each test with @pytest.test
2. How do you test that a function raises ValueError for invalid input?
try: func(); except ValueError: pass
with pytest.raises(ValueError): func(bad_input)
assert ValueError == func(bad_input)
pytest.expect(ValueError, func(bad_input))
3. In TDD, what does "Red" mean?
The code has a runtime error
A test is written and fails because the feature doesn't exist yet
pytest output is shown in red terminal colors
The code has been refactored and improved
4. What does test coverage measure?
How many test files you have
What percentage of your source code lines are executed by the test suite