Demystifying the Patch Function
summary
Explains exactly how unittest.mock.patch replaces a target by name (examples with my_module.db_write and from-import vs import cases), when to use context manager, function or class decorator or manual start/stop, and how to avoid false positives with spec / autospec / spec_set. Covers new_callable, new, create and useful kwargs, demonstrates mocking DB writes and builtins, and warns about leaks and autospec introspection side effects so a viewer knows if they need concrete examples and gotchas or can skip it.
AI-written summary · about
chapters (18)
- 0:00Start
- 1:42What does Patch do?
- 2:54When should you mock?
- 6:03What makes it so confusing?
- 6:42Target Must be Importable
- 7:38my_module.py
- 10:39Scope Matters
- 12:11Context Manager
- 13:14Function Decorator
- 14:54Manual Start/Stop
- 16:54spec & autospec & spec_set
- 17:14Mock Problems
- 18:45A MagicMock
- 19:29A Specced MagicMock
- 23:42new_callable & new
- 25:38create
- 26:25kwargs
- 27:33Takeaways
related talks
31mHot-swapping Symbols During Tests: Demystifying unittest.mock[.patch]
20mMock, patch - when and how to use
27mI Dance with Your Shadow: Patch, Stub, Mock
29mUnit testing in the real world with mock
49mFor those about to Mock I salute you!
39mIntro to Mocking: Why Unit Testing Doesn't Have To Be So Hard
26mMocking: virtual reality for your Python tests
23mMocking of mocks. A deep dive into the mock module
