pytest Study Notes

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 _test are automatically discovered by pytest.
  • Usage examples: pytest -q, pytest path/to/test_file.py
  • Assertions: Use assert directly to verify expected results.

2) Lesson-by-Lesson Summary

  • Lesson1 (Assertion Basics): Use simple assert to 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.fixture to provide object instances required for testing, ensuring each test uses independent resources to avoid interference.
  • Lesson4 (Fixture Teardown / Yield): Use yield in fixtures to write cleanup code after yield (equivalent to teardown), such as clearing state.
  • Lesson5 (Parameterized Testing): Use @pytest.mark.parametrize to pass multiple sets of inputs/expectations at once, enabling bulk testing of function behavior.
  • Lesson6 (Mocking HTTP): Use mocker.patch from pytest-mock to mock requests.get, avoiding real network requests; control response behavior via return_value or side_effect.
  • Lesson7 (Mocking DB): Mock database connections (e.g., patch sqlite3.connect), check whether cursor.execute is 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 :receipt:

  • 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).