Files
contract-match-http-autotest/README.en.md
T
2026-09-21 22:39:03 +08:00

285 lines
18 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# contract-match-http-autotest — HTTP API Automated Testing Demo for a Perpetual Contract Matching System
> A slightly condensed mirror of the Chinese `README.md`; section structure is kept 1:1
> (9 sections). Terminology: matching engine (撮合), liquidation (强平), freeze (冻结);
> inline code identifiers such as `Decimal` are kept as-is.
## 1. 5-Minute Reading Guide
If you only have 5 minutes, read in this order:
1. **Start with the architecture diagram in "5. Architecture"** — 30 seconds to see the layers:
test case layer, API wrapper layer, system under test, assertion surfaces, formula layer;
2. **Then "3. Test Coverage Checklist"** — one table covering which business scenarios,
how many cases, and which assertion surfaces each one hits;
3. **Then read `case/test_liquidation.py`** — the case that best demonstrates triple
assertions (HTTP response + database + cache): price feed is driven to the liquidation
price, and the risk fund ledger is asserted;
4. **Finally `formula/contract_formula.py`** — why expected values must be computed
independently instead of copied from the system under test.
### Why a mock instead of a real environment
- **Desensitization**: this project contains no real company information — contract
parameters, fee rates, field names and API paths are all placeholder values and
neutral demo paths, rebuilt locally by the mock engine;
- **Reproducibility**: clone it, run `pytest`, everything is green — no environment
requests, no VPN, no external network;
- **Isomorphic verification chain**: the mock's HTTP server, persistence and cache
interactions mirror a real microservice setup; switching to a real environment only
requires replacing the fixtures in `conftest.py` — test code stays untouched;
- **Deliberately not reused**: the mock engine implements its own fund calculations
independently of the `formula/` package, keeping two independent computation chains
(system under test vs. test-side expected values) to avoid self-proving code.
## 2. What Problem This Project Solves
A perpetual contract matching system is composed of multiple microservices — order
acceptance, matching engine, risk control, clearing, etc. — with numerous APIs and
complex business states. Asserting only HTTP status codes is far from enough: behind a
single order request, the system actually performs **funds freezing, order persistence,
position changes, and cache updates** — a failure in any one of them is a capital-loss
incident.
This project demonstrates an API test-automation methodology for such systems, built on
three pillars:
1. **Triple assertions**: HTTP response + database persistence + cache, asserted
together, not just the return value;
2. **Formula layer computes expected values**: margin, fees, liquidation price,
bankruptcy price etc. are implemented as independent pure functions. Expected values
are **calculated**, not "run once and copied" — if the formula is wrong the test goes
red; if the system is wrong the test also goes red;
3. **YAML data-driven**: cases are separated from data; one test function covers
positive / negative / boundary values in one go.
To keep the project runnable **without any real environment**, the matching system is
implemented as a local mock engine (stdlib `wsgiref` HTTP server + in-memory
MySQL/Redis). The verification chain is fully isomorphic to a real project, and `pytest`
runs all green without touching any external network, database or middleware.
## 3. Test Coverage Checklist
**94** cases in total, all passing (source: `pytest --collect-only -q`, measured
2026-09-21): **84** scenario and formula cases under `case/`, plus **10** generator
self-tests under `mock/`.
| Business scenario | Cases | Assertion surfaces (HTTP / DB / cache) | Key points covered |
| --- | --- | --- | --- |
| Order placement freezes margin (positive, data-driven) | 15 | HTTP + DB + cache | Cross/isolated margin × buy/sell × three initial-margin-rate tiers; freeze = initial margin + max(maker, taker) fee; order fields / fund deduction / freeze ledger / freeze key reconciled on four sides |
| Illegal order parameters (negative, data-driven) | 21 | HTTP + DB + cache | Zero/negative price or quantity, illegal margin rate, insufficient balance, etc.; **extra "no side effect" assertions**: no new orders, no fund changes, no cache residue |
| Cancel order unfreeze (incl. state machine) | 8 | HTTP + DB + cache | Frozen amount fully returned to available; unfreeze ledger; freeze key cleaned up; state machine (repeat cancel / cancel a filled order / cancel a non-existent order / missing order number) and re-ordering after unfreeze |
| Market order opens position | 2 | HTTP + DB + cache | Both long and short; immediate fill at taker fee; position / fee ledger / position cache; unrealized PnL after mark price moves |
| Liquidation trigger (data-driven) | 6 | HTTP + DB + cache | Two stages — safe price does not trigger, trigger price liquidates; bankruptcy price matches the formula; remaining margin goes to the risk fund; negative-balance gap covered by the risk fund and deducted from available balance; position cleared, cache key removed |
| Formula layer pure-function unit tests (data-driven) | 32 | Pure functions (no IO) | Frozen margin / unrealized PnL / bankruptcy price / liquidation price / burst detection, with **hand-calculated, hard-coded** expected values to prevent self-deception; includes the liquidation boundary (closed `<=` interval) and a float-precision counter-example |
| Generator self-tests (`mock/test_*_gen.py`) | 10 | Pure functions / API wrapper | Auxiliary unit tests produced earlier with a generation tool; now collected by pytest |
> Note: `mock/test_*_gen.py` are now collected via `testpaths = case mock` in
> `pytest.ini`, so the 94 above already include them; counting only `case/` gives **84**.
## 4. Engineering Efficiency Tools (tools/)
Beyond "how to write a case", automation projects also face "how to make the project
actually run" — decoding messages, following logs, passing state between scripts. This
directory collects 3 tools that recur in matching-system automation work and have been
fully desensitized to local placeholders:
| Module | API | Problem solved | Typical scenario |
| --- | --- | --- | --- |
| `tools/msg_codec.py` | `encode(payload) / decode(msg)` | kline market data delivered over RocketMQ carries a `base64(gzip(json))` binary body; the consumer must restore it before asserting. Encoding/decoding is collapsed into pure functions reused directly by cases | kline market-data consumption |
| `tools/log_tail.py` | `tail(path)` iterator + `extract_time(line)` | The matching engine log is followed incrementally with `tail -c 0 -f`; a regex extracts `[YYYY-MM-DD HH:MM:SS]` business timestamps for order→fill latency statistics. The subprocess pipe is owned by the iterator, so `break` terminates it | Matching latency statistics script |
| `tools/cache_utils.py` | `set/get/delete(key)` | Cross-process state sync: the load-test script writes, the verification script reads. diskcache provides local disk caching decoupled from the business DB; the API is just three verbs | CacheUtils of the matching-log verification script |
Design takeaways: these three modules cover **encode/decode over a binary message
stream**, **subprocess pipe control over production logs**, and **decoupling a cache
layer from the DB** — all typical moves that turn script tricks into engineering
components. Demo paths are unified as `/tmp/demo/log`, `/tmp/demo/match.log` and
`/tmp/demo/cache`; no real production address appears.
## 5. Architecture
![Architecture](docs/architecture.png)
Layer responsibilities:
| Layer | Directory | Responsibility |
| --- | --- | --- |
| Test case layer | `case/` | Organizes business assertions; only cares about "given what, expect what" |
| Data layer | `data/` | Case parameters and expected values, `[param dict, expected dict]` for parametrize unpacking |
| Formula layer | `formula/` | Pure functions for matching-business formulas, all `Decimal`, the sole source of expected values |
| API wrapper layer | `api/` | Secondary encapsulation of the system's HTTP APIs; cases never build URLs directly |
| Common layer | `common/` | YAML reading, HTTP client, `Decimal` assertion utilities |
| System under test | `mock/` | Local matching engine + HTTP server + in-memory DB/cache |
| Efficiency tools | `tools/` | Message codec, log following, cross-process cache |
| Config layer | `config/` | Contract parameters, fee rates, precision (all placeholder demo values) |
## 6. How to Run
```bash
cd contract-match-http-autotest
python -m venv venv && source venv/bin/activate # optional
pip install -r requirements.txt # pytest / pytest-cov / requests / PyYAML / diskcache
python -m pytest # all tests
python -m pytest case/test_liquidation.py -v # a single scenario
python -m pytest -k liquidation # filter by keyword
```
### Coverage
```bash
python -m pytest --cov=formula --cov=mock --cov-report=term-missing
```
Measured 2026-09-21 (macOS / Python 3.13.12 / pytest 9.1.1):
```
Name Stmts Miss Cover Missing
-----------------------------------------------------------
formula/__init__.py 0 0 100%
formula/contract_formula.py 50 0 100%
mock/__init__.py 0 0 100%
mock/engine.py 238 16 93% 80, 158, 223-231, 238, 247, 250, 388-389
mock/fake_cache.py 14 1 93% 29
mock/fake_db.py 10 0 100%
mock/server.py 24 2 92% 37-38
mock/test_api_client_gen.py 60 0 100%
mock/test_formula_gen.py 42 0 100%
-----------------------------------------------------------
TOTAL 438 19 96%
```
**TOTAL line coverage = 96%**, with an honest account of what is not covered and why:
- The 16 missed lines in `mock/engine.py` concentrate in defensive/fallback branches
(illegal-argument guards, extreme negative-balance paths such as 223-231). Normal
scenario cases never reach them, and negative data covers only part — a natural
blind spot of API-level testing against unit-level branches;
- Lines 37-38 of `mock/server.py` are the process-entry fallback, only hit when the
server runs as a script; conftest starts it via a function call;
- Line 29 of `mock/fake_cache.py` is a single defensive branch;
- `formula/contract_formula.py` reaches **100%** across its 50 statements — the formula
layer is the sole source of expected values, so leaving no branch uncovered is
deliberate;
- `mock/test_*_gen.py` (102 statements combined) is now at **100%**: these were auxiliary
unit-test drafts from an earlier code-generation experiment and are now collected via
`testpaths = case mock` in `pytest.ini`, so they no longer drag TOTAL down.
No environment setup is required: `conftest` automatically starts the mock matching
service on a random port at `127.0.0.1`, and resets engine data **before each test
case**, so cases are isolated, repeatable, and can run in any order.
## 7. Key Difficulties and How I Handled Them
### 1. Money precision: `Decimal` everywhere, never float
Contract fund fields routinely carry 8 decimal places; the `0.1 + 0.2 != 0.3` float
trap becomes a false-pass/false-fail incident in fund assertions. Handling:
- The formula layer and assertion utilities all convert via `Decimal(str(value))`
(never `Decimal(float)`, which would import float error first);
- `common/decimal_assert.py::assert_decimal_equal` compares after uniform 8-decimal
quantization — neither pedantic about float representation nor tolerant of real
precision loss;
- `test_formula.py::test_decimal_precision_over_float` pins this rule down with a
float counter-example.
### 2. Where expected values come from: pure functions, hand-calculated cases against self-proof
- Margin / fee / liquidation price / bankruptcy price formulas are extracted into the
`formula/` package as pure functions (no IO, no state); scenario cases always call
them for expected values;
- The formula layer itself has unit tests (`data/formula.yml`) whose expected values
are **hand-calculated and hard-coded**, preventing the formula implementation from
proving itself;
- The liquidation boundary semantics (trigger when margin balance is exactly equal to
the maintenance margin, a closed `<=`) are pinned by a dedicated boundary case — the
single most disputed cell in production.
### 3. Landing triple assertions: DB and cache field names differ
- DB assertions cover three tables: `futures_account` / `order` / `account_flow`;
cache assertions cover three key families: `order_freeze:*` / `futures_account:*` /
`position:*`;
- DB uses snake_case while cache uses camelCase; fields are normalized before
comparison — reproducing the dirty work of real projects, and the most common pitfall
of cache assertions;
- Cache values are stored as strings (simulating the Redis string type) and converted
back to `Decimal` when asserting.
### 4. Case isolation and repeatability
- `engine.reset()` runs before every case (function-level `base_url` fixture in
conftest), eliminating cross-case data contamination — any order, any repetition,
same result;
- Negative cases additionally assert **"no side effects"**: an illegal request must not
only return an error code but also leave the order table without new rows, the fund
table unchanged, and the cache without residue — for negative API tests, checking
only the status code is not enough.
### 5. Environment decoupling: a mock isomorphic to the real system under test
- In a real project the system under test is an independent microservice cluster plus
MySQL/Redis clusters; this demo uses a wsgiref server plus in-memory DB/cache
substitutes, and **test code can switch between the two forms without changing a
single line** (only the fixture implementation in conftest is replaced);
- The mock server and data plane share one engine instance, so the in-memory state
mutated by an HTTP request is exactly the state read by the "persistence/cache"
assertions — the causal chain matches the real system.
## 8. Directory Layout
```
contract-match-http-autotest/
├── README.md # Chinese version (source document)
├── README.en.md # This document
├── requirements.txt # pytest / pytest-cov / requests / PyYAML / diskcache
├── pytest.ini # testpaths = case mock
├── conftest.py # fixtures: start mock server, inject data plane, isolation
├── config/
│ └── settings.py # contract params / fee rates / precision (placeholders)
├── formula/
│ └── contract_formula.py # contract formula layer (pure functions, all Decimal)
├── common/
│ ├── read_yaml.py # YAML data loading
│ ├── http_client.py # requests wrapper
│ └── decimal_assert.py # Decimal money assertion utility
├── api/
│ └── order_api.py # order / cancel / transfer / mark price / risk API wrappers
├── mock/
│ ├── engine.py # matching engine (system under test)
│ ├── server.py # wsgiref HTTP server
│ ├── fake_db.py # in-memory MySQL
│ ├── fake_cache.py # in-memory Redis
│ ├── test_api_client_gen.py # generator self-test: API wrapper
│ └── test_formula_gen.py # generator self-test: formula layer
├── tools/
│ ├── msg_codec.py # base64(gzip(json)) message codec
│ ├── log_tail.py # incremental log follow + business timestamp extraction
│ └── cache_utils.py # diskcache-backed cross-process state cache
├── case/
│ ├── test_order_freeze.py # scenario 1: order placement freezes margin (triple)
│ ├── test_cancel_order.py # scenario 4: cancel order unfreeze (state machine)
│ ├── test_position_open.py # scenario 2: market order opens position
│ ├── test_liquidation.py # scenario 3: liquidation trigger verification
│ └── test_formula.py # formula layer pure-function unit tests
└── data/
├── addOrder.yml # order placement positive/negative data (data-driven)
├── cancelOrder.yml # cancel-order scenario data
├── liquidation.yml # liquidation scenario data
└── formula.yml # formula expected values (hand-calculated)
```
## 9. Business Rules Quick Reference (Demo Parameters)
| Rule | Value / formula |
| --- | --- |
| Contract | Contract #1 BTCUSDT (demo), initial mark price 100 |
| Fee rates | maker 0.0002 / taker 0.0005; limit freeze uses max(maker, taker), market fills use taker |
| Frozen margin | open value × initial margin rate + open value × max(maker, taker) |
| Maintenance margin rate | 0.005 |
| Liquidation condition | extra margin + initial margin + unrealized PnL ≤ maintenance margin |
| Liquidation price (isolated) | `open + direction × (maintain − extra − init) / qty` |
| Bankruptcy price (isolated) | long: `open×(1−rate) − extra/qty`; short: `open×(1+rate) + extra/qty` |
| Negative balance | after liquidation, margin balance goes negative: the gap is deducted from available balance and covered by the risk fund |
| Fund ledger types | transfer-in / transfer-out / freeze / unfreeze / fee / open position / liquidation (enum values are the `FLOW_*` constants in `mock/engine.py`, all demo values) |