AlgoViz

Adapter pattern

easy 50 min

The Adapter pattern makes an existing class fit the interface that its client expects, without changing either of them.

Watch lesson4:39

Contract tests

How to know that a fake, an adapter and the real vendor still agree.

The point: three things must agree: your fake, your adapter, and the vendor. One suite of tests, run at three different times, keeps them together.

TestRuns againstWhenFinds
Translation testAdapter with a recording fake of the vendorEvery commit, millisecondsWrong unit, wrong order, lost error
Contract testEvery implementation of the target, also the in-memory oneEvery commitA fake that is kinder than reality
Recorded testAdapter with saved raw repliesEvery commitParsing of odd replies
Live testAdapter with the vendor's test systemNightlyThe vendor changed
Business testProgram with the in-memory gatewayEvery commitYour own bugs

Code

One suite, many subjects

Python
from abc import ABC, abstractmethodclass NotFound(Exception):    passclass Store(ABC):    @abstractmethod    def put(self, key, text): ...    @abstractmethod    def get(self, key): ...class MemoryStore(Store):               # the fake for all other tests    def __init__(self):        self._data = {}    def put(self, key, text):        self._data[key] = text    def get(self, key):        if key not in self._data:            raise NotFound(key)        return self._data[key]class ByteBox:                          # the vendor: bytes, None, no upper case    def __init__(self):        self._items = {}    def write(self, name, data):        self._items[name.lower()] = bytes(data)    def read(self, name):        return self._items.get(name.lower())class ByteBoxStore(Store):    def __init__(self, box):        self._box = box    def put(self, key, text):        self._box.write(self._name(key), text.encode("utf-8"))    def get(self, key):        data = self._box.read(self._name(key))        if data is None:            raise NotFound(key)        return data.decode("utf-8")    @staticmethod    def _name(key):        return key.encode("utf-8").hex()        # "A" and "a" stay differentclass StoreContract:    def __init__(self, make):        self.make = make    def run(self):        tests = [n for n in dir(self) if n.startswith("test_")]        for name in tests:            getattr(self, name)(self.make())        return len(tests)    def test_round_trip(self, s):        s.put("a", "h\u00e9llo")        assert s.get("a") == "h\u00e9llo"    def test_missing(self, s):        try:            s.get("nothing")            assert False        except NotFound:            pass    def test_overwrite(self, s):        s.put("a", "1")        s.put("a", "2")        assert s.get("a") == "2"    def test_case(self, s):        s.put("a", "small")        s.put("A", "big")        assert (s.get("a"), s.get("A")) == ("small", "big")    def test_empty_is_not_missing(self, s):        s.put("e", "")        assert s.get("e") == ""for make in (MemoryStore, lambda: ByteBoxStore(ByteBox())):    print(StoreContract(make).run(), "promises kept")
test_case and test_empty_is_not_missing are the interesting ones. They come from the gap list: this vendor ignores case, and a careless if not data would report an empty text as missing.
Edit and run it in your browser

Three times, one suite

A mock-based test is green, production fails because the vendor returns an empty list instead of null. What was missing?

BreaksMore mocks
How
Add a mock for the empty list too.
Limit
The mock repeats what we believe. It can not tell us what we do not know.
Choose when
Never as the only answer.
WorksAn end-to-end test of the whole program
How
Real vendor, real browser.
Limit
Slow, and when it fails nobody knows where.
Choose when
One or two main paths.
StrongA contract test against the vendor's test system, nightly, with saved replies for every commit
How
Same suite. When it goes red, save the new reply as a fixture.
Limit
Needs test accounts and some care for data.
Choose when
Whenever the other side can change without you.