Testing Integrations: Contract Tests and Shared State
Why This Matters
Unit tests with an in-memory ERP are fast, but they cannot tell you whether the real HTTP call works: the URL, the JSON, the status codes. Contract tests check exactly that, against a real server. They also have a classic trap, which we fell into while building this project.
A contract test
tests/test_erp_contract.py starts the fake ERP on a free port, uses the real ErpClient against it, and stops the server afterwards:
@pytest.fixture
def erp_url():
server = serve(port=0) # port 0: the OS picks a free port
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
yield f"http://127.0.0.1:{server.server_port}"
server.shutdown()
def test_booking_returns_an_erp_id(erp_url):
assert ErpClient(erp_url).book_order(ORDER) == "ERP-1001"
def test_booking_the_same_order_twice_is_refused(erp_url):
client = ErpClient(erp_url)
client.book_order(ORDER)
with pytest.raises(ErpError, match="409"):
client.book_order(ORDER)
Everything after yield is cleanup: it runs after the test, also when the test fails.
The trap: shared state
The first version of fake_erp.py kept its orders in a variable at the top of the file. Each test started a new server, but all servers shared that one variable. This is the real output we got:
The second test failed on its first booking, because the first test had already booked PO-20417. Each test passed on its own; together, one failed. In a bigger suite this shows up as a “flaky” test that fails depending on the order tests run in.
The fix gives every server its own order book:
def serve(port: int = 8765) -> HTTPServer:
"""A fresh fake ERP with its own empty order book."""
handler = type("FreshHandler", (Handler,), {"ids": count(1001), "orders": {}})
return HTTPServer(("127.0.0.1", port), handler)
The rule: every test starts from a known, clean state, and never depends on what another test did.
Contract tests against the real system
Against a real ERP test environment, contract tests check the parts you rely on: the fields you send are accepted, the status codes are what your code expects (201, 409, 4xx for bad data), and the response contains the id you store. Run them less often than unit tests (for example nightly), and keep them separate with a marker: this project marks them with @pytest.mark.contract, so python -m pytest -m "not contract" skips them.
Exercise
- Run only the contract tests:
python -m pytest -m contract -v. - Reproduce the bug: in
serve(), share one dictionary between all servers again, run the contract tests, and see the failure. Restore withgit restore fake_erp.py. - Add a contract test: an order posted to a wrong path (for example
/order) gets a 404. Which part ofErpClientwould you change to test that?
Key Takeaways
- Contract tests use the real client against a real (fake or test) server.
- Fixtures with
yieldstart and clean up what a test needs. - Shared state between tests causes failures that depend on test order.
- Every test starts from a known, clean state.
