15.10 Mocking external resources
In earlier recipes in this chapter, namely, Testing things that involve dates or times and Testing things that involve randomness, we wrote tests for involving resources with states that we could predict and mock. In one case, we created a mock datetime module that had a fixed response for the current time. In the other case, we created a mock function from the random module.
A Python application can use the os, subprocess, and pathlib modules to make significant changes to the internal states of a running computer. We’d like to be able to test these external requests in a safe environment, using mocked objects, and avoid the horror of corrupting a working system with a misconfigured test. Another example is database access, which requires mock objects to respond to create, retrieve, update, and delete requests.
In this recipe, we’ll look at ways to create more sophisticated mock objects. These will allow the safe...