What is Unit Testing?
Unit testing is the practice of writing small, automated scripts to verify that individual "units" of your code (like a single function or a specific class method) work exactly as intended. This is crucial for catching bugs in large projects and when refactoring your code.
python
Testing with unittest (Standard Library)
Python comes with a built-in testing framework called
unittest. It uses a class-based structure based on the JUnit framework.python
Modern Testing with pytest (The Standard!)
While
unittest is built-in, most Python developers use pytest. It's much simpler to write and has far more powerful features like "fixtures" and "parameterization".python
To run your tests:
bash
Fixtures: Setting up Test Data
What if your tests need a database connection, or a complex object, before they run? A fixture is a function that prepares state for a test.
python
Mocking: Simulating Real Services
Sometimes your tests shouldn't actually call an external API or write to a real database. Mocking allows you to replace a real function or object with a "mock" that returns whatever you want.
python
Test-Driven Development (TDD)
TDD is a development process where you write the test first, then the code to pass it.
- Red: Write a test for a feature that doesn't exist yet (it will fail).
- Green: Write the minimum code possible to make the test pass.
- Refactor: Clean up the code without breaking the test.
Common Assertions
| Assertion | Purpose |
|---|---|
| assert x == y | Check equality |
| assert x != y | Check inequality |
| assert x is True | Check boolean |
| assert x in y | Check membership |
| pytest.raises(Error) | Verify code raises a specific error |
Summary
| Term | Description |
|---|---|
| unittest | Built-in, class-based testing framework |
| pytest | Most popular, function-based framework |
| Assertion | A statement that checks if something is true |
| Fixture | Setup/teardown logic for test data |
| Mocking | Simulating external dependencies |
| Coverage | Measure how much of your code is tested |
| Best For | Bug prevention, code reliability, refactoring |
| Integration Test | Testing multiple units together |
| Regression Test | Testing old bugs to ensure they don't return |
| Monkeypatch | Dynamically modifying modules/classes during tests |
| Assertion Message | assert condition, "Message if fail" |
| Skip Testing | @pytest.mark.skip(reason="...") |
| Execution | Run with pytest -v for verbose output |
| conftest.py | Store global fixtures for pytest projects |
| pytest-cov | Package to generate code coverage reports |