Adam Johnson
Read post

Python: spy on function calls with unittest.mock’s wraps

Python's unittest.mock supports not just mocks but also spies via the wraps argument. A spy wraps a real function, letting calls pass through while recording them for later assertions. The post demonstrates using mock.patch.object() with wraps and autospec=True to spy on a caching function, verifying it calls the underlying compute function only once. It also covers how return_value and side_effect interact with wraps, shows the pytest-mock mocker.spy() shortcut, and provides a reusable spy() context manager helper for non-pytest setups.

    #python#testing
Jul 25•4m read time•From adamj.eu
Post cover image
Table of contents
Configured behaviour beats wrapsIn pytestSimplify with a spy() helperFin
1.3K Impressions
Adam Johnson's image
Adam Johnson

AdamJ's platform covers topics related to software development, technology trends, and coding tutor...

54 Followers

•

444 Upvotes

Would you recommend this post?

Copy link
WhatsApp
Facebook
X
New Squad
  • © 2026 Daily Dev Ltd.
  • Guidelines
  • Explore
  • Tags
  • Sources
  • Squads
  • Leaderboard