thenafter calling our change_status method with known valueswe use the mock class' assert_called_once_with function to ensure that the now function was indeed called exactly once with no arguments we then call it second time to prove that the redis set method was called with arguments that were formatted as we expected them to be the previous example is good indication of how writing tests can guide our api design the flightstatustracker object looks sensible at first glancewe construct redis connection when the object is constructedand we call into it when we need it when we write tests for this codehoweverwe discover that even if we mock out that self redis variable on flightstatustrackerthe redis connection still has to be constructed this call actually fails if there is no redis server runningand our tests also fail we could solve this problem by mocking out the redis strictredis class to return mock in setup method better ideahowevermight be to rethink our example instead of constructing the redis instance inside__init__perhaps we should allow the user to pass one inas in the following exampledef __init__(selfredis_instance=none)self redis redis_instance if redis_instance else redis strictredis(this allows us to pass mock in when we are testingso the strictredis method never gets constructed howeverit also allows any client code that talks to flightstatustracker to pass in their own redis instance there are variety of reasons they might want to do this they may have already constructed one for other parts of their code they may have created an optimized implementation of the redis api perhaps they have one that logs metrics to their internal monitoring systems by writing unit testwe've uncovered use case that makes our api more flexible from the startrather than waiting for clients to demand we support their exotic needs this has been brief introduction to the wonders of mocking code mocks are part of the standard unittest library since python but as you see from these examplesthey can also be used with py test and other libraries mocks have other more advanced features that you may need to take advantage of as your code gets more complicated for exampleyou can use the spec argument to invite mock to imitate an existing class so that it raises an error if code tries to access an attribute that does not exist on the imitated class you can also construct mock methods that return different arguments each time they are called by passing list as the side_effect argument the side_effect parameter is quite versatileyou can also use it to execute arbitrary functions when the mock is called or to raise an exception