Tutorial
Please Learn How To Write Tests in Python… • Pytest Tutorial - YouTube
Code Notes
Notes Outline
1) Basics & Quick Start
- Test file naming: Files starting with
test_or ending with_testare automatically discovered by pytest. - Usage examples:
pytest -q,pytest path/to/test_file.py - Assertions: Use
assertdirectly to verify expected results.
2) Lesson-by-Lesson Summary
- Lesson1 (Assertion Basics): Use simple
assertto verify function return values; learn how to run a single test file. - Lesson2 (Unit Testing & Exception Testing): Test function correctness and edge cases; use
pytest.raises(...)to assert exceptions (e.g., handling division by zero). - Lesson3 (Fixture: Setup): Use
@pytest.fixtureto provide object instances required for testing, ensuring each test uses independent resources to avoid interference. - Lesson4 (Fixture Teardown / Yield): Use
yieldin fixtures to write cleanup code afteryield(equivalent to teardown), such as clearing state. - Lesson5 (Parameterized Testing): Use
@pytest.mark.parametrizeto pass multiple sets of inputs/expectations at once, enabling bulk testing of function behavior. - Lesson6 (Mocking HTTP): Use
mocker.patchfrompytest-mockto mockrequests.get, avoiding real network requests; control response behavior viareturn_valueorside_effect. - Lesson7 (Mocking DB): Mock database connections (e.g., patch
sqlite3.connect), check whethercursor.executeis called correctly, and verify SQL generation logic. - Lesson8 (Dependency Injection & Spec): Create a restricted-interface mock using
mocker.Mock(spec=APIClient), inject it into services to test business logic, and assert call arguments on dependencies.
3) Quick Reference: Common Commands 
- Run all tests:
pytest -q - Run a single file:
pytest path/to/test_file.py - Run only tests matching a keyword:
pytest -k "keyword" - Show verbose output:
pytest -vv
Note: More practices and command records can be found in
lesson/pytest_note.ipynb(notebook-style examples and commands).