Unit testing in the real world with mock
summary
Uses Python's unittest.mock (stdlib since 3.3, backport for 2.6+) to unit-test IO-heavy code by replacing names the module imports. Demonstrates patch.dict to fake os.environ, patch to substitute a language function and a Google Translate client, and Mock.return_value / side_effect to return specific JSON and raise errors. Verifies behavior with call counts and assert_called_with, checks random.seed and print calls, and warns a mocked API hid a real bug—advocates create_autospec plus integration tests.
AI-written summary · about
chapters (16)
- 0:00Introduction to unit testing
- 1:00Why unit testing matters
- 2:25Real world testing challenges
- 3:53Enterprise guessing game example
- 5:59Testing simple calculations
- 7:03Mocking environment variables
- 9:12Introduction to mocking library
- 11:44Testing language-specific features
- 13:33Understanding mock objects
- 16:18Patching functions with mocks
- 17:21Mocking cloud API calls
- 20:31Testing random and print functions
- 21:57Verifying function calls
- 23:23Limitations of mocking
- 24:28Conclusion and next steps
- 27:24Q&A and closing
related talks
49mFor those about to Mock I salute you!
26mMocking: virtual reality for your Python tests
39mIntro to Mocking: Why Unit Testing Doesn't Have To Be So Hard
32mMock It Till You Make It: How to Verify Your External Mocks Without Ever...
20mMock, patch - when and how to use
31mHot-swapping Symbols During Tests: Demystifying unittest.mock[.patch]
24mTesting Your Python Code
27mI Dance with Your Shadow: Patch, Stub, Mock
