Utilizing Spies in Test Driven Development with Pytest Mock
Introduction and Context Setting
Welcome to our third lesson on Test-Driven Development (TDD) with Test Doubles. In this lesson, we focus on Spies, an essential type of test double used to observe interactions with your code's dependencies during testing. By now, you've already been introduced to Dummies and Stubs in previous lessons, which allow you to manage dependencies via test doubles effectively.
Our goal here is to seamlessly integrate Spies into the TDD Red-Green-Refactor cycle: writing tests (Red), creating minimal implementations (Green), and refactoring for better quality without altering behavior. Let's dive into understanding and using Spies within this framework using Python's pytest-mock.
Deep Dive into Spies in Python
Spies are a powerful tool available through Python's pytest-mock module. They allow you to observe and record how functions in your application are used without modifying their behavior. In TDD, Spies help verify that functions are called when and how you expect them to be, which is a vital part of writing reliable tests.
Spies can check:
- If a function was called
- How many times it was called
- With what arguments it was called
They align perfectly with the Red-Green-Refactor cycle:
- Red: Write a failing test to ensure your code's behavior is verified.
- Green: Implement only enough code for the tests to pass.
- Refactor: Clean up the tests and the implementation for better software design.
Let's set up our environment using pytest-mock to harness this powerful tool.
Example: Implementing the First Spy
Let's consider a Notification Service example where we aim to ensure notifications are sent with appropriate priorities. We will begin by implementing a Spy on the send method of the RealNotificationSender. This allows you to use an actual dependency within your test and verify how it was called.
Here's an example test file: test_notification_sender.py.
