1 hour ago · Tech · hide · 0 comments

Testing terminology distinguishes between different kinds of test doubles, including: mocks, which replace the real behaviour of a function. spies, which wrap a function, recording calls for later assertions. Despite its name, unittest.mock is not just for mocks: it can also create spies, through the wraps argument of its Mock classes. Calls to such a Mock pass through to the wrapped object and return its real results, while the mock records the calls for later assertions. For example, say we wanted to test the caching in this module, which computes the sound that an owl makes based on its name: sound_cache: dict[str, str] = {} def owl_sound(name: str) -> str: if name not in sound_cache: sound_cache[name] = compute_owl_sound(name) return sound_cache[name] def compute_owl_sound(name: str) -> str: firsts = ("Hoo", "Hoot", "Toot", "Hooo") seconds = ("hoo", "hoot", "toot", "hooo") first = firsts[len(name) % len(firsts)] second = seconds[ord(name[0]) % len(seconds)] return…

No comments yet. Log in to reply on the Fediverse. Comments will appear here.