Hot-swapping Symbols During Tests: Demystifying unittest.mock[.patch]
summary
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
chapters (21)
- 0:00Introduction to unittest.mock
- 1:26Patching vs mocking concepts
- 4:17Building mocking implementation
- 6:02Manual patching example
- 8:11Patcher class and boilerplate
- 9:15Context managers for cleanup
- 10:41Decorators for patching
- 11:47Gotchas in patching attributes
- 13:55String-based patching
- 15:18patch vs patch.object
- 15:59Mocking utilities introduction
- 16:20Simple mock class
- 17:24Side effects and exceptions
- 18:28Callable side effects
- 19:10Iterable side effects
- 19:52Overloading side effects
- 20:14Accessing mock attributes
- 21:43MagicMock and defaults
- 22:46Spec types for mocks
- 23:48Tracking mock calls
- 24:30Q&A session
related talks
20mMock, patch - when and how to use
37mDemystifying the Patch Function
27mI Dance with Your Shadow: Patch, Stub, Mock
39mIntro to Mocking: Why Unit Testing Doesn't Have To Be So Hard
29mUnit testing in the real world with mock
26mMocking: virtual reality for your Python tests
49mFor those about to Mock I salute you!
32mMock It Till You Make It: How to Verify Your External Mocks Without Ever...
