~/talk

Hot-swapping Symbols During Tests: Demystifying unittest.mock[.patch]

Talkat PyCon Italia 2025 · 2025-05-28..05-31· [testing]
links:none on file
slides:none on file

Rebuilds how unittest.mock actually works by coding a minimal patcher, context-manager decorator and callable Mock/MagicMock that match stdlib behavior (but cleaner), demonstrates patch.object vs string patching, shows the crucial gotcha that you must patch the name where code looks it up not where it’s defined, explains side_effect (callable, exception, or iterable) and how call lists record invocations, and notes MagicMock auto-creates about 20 magic methods.

AI-written summary · about

  1. 0:00Introduction to unittest.mock
  2. 1:26Patching vs mocking concepts
  3. 4:17Building mocking implementation
  4. 6:02Manual patching example
  5. 8:11Patcher class and boilerplate
  6. 9:15Context managers for cleanup
  7. 10:41Decorators for patching
  8. 11:47Gotchas in patching attributes
  9. 13:55String-based patching
  10. 15:18patch vs patch.object
  11. 15:59Mocking utilities introduction
  12. 16:20Simple mock class
  13. 17:24Side effects and exceptions
  14. 18:28Callable side effects
  15. 19:10Iterable side effects
  16. 19:52Overloading side effects
  17. 20:14Accessing mock attributes
  18. 21:43MagicMock and defaults
  19. 22:46Spec types for mocks
  20. 23:48Tracking mock calls
  21. 24:30Q&A session
~/search
type to search 6,249 conferences, 138,987 speakers and 185,172 talks
~/help
cmdctrl k
search every conference, speaker and series
/
focus the filter search
h
home
c
conferences
s
speakers
e
series
t
light / dark — the status bar button does the same
?
this help
esc
close this, then clear every filter — or just the search, while you are typing in it

Ignored while you are typing. Pages without a filter rail have no search to focus.