Imitating expensive objects
Sometimes, we want to test code that requires an object be supplied that is either expensive or difficult to construct. While this may mean your API needs rethinking to have a more testable interface (which typically means a more usable interface), we sometimes find ourselves writing test code that has a ton of boilerplate to set up objects that are only incidentally related to the code under test.
For example, imagine we have some code that keeps track of flight statuses in a key-value store (such as redis
or memcache
) such that we can store the timestamp and the most recent status. A basic version of such code might look like this:
import datetime import redis class FlightStatusTracker: ALLOWED_STATUSES = {'CANCELLED', 'DELAYED', 'ON TIME'} def __init__(self): self.redis = redis.StrictRedis() def change_status(self, flight, status): status = status.upper() if status not in self.ALLOWED_STATUSES: raise ValueError...