diff --git a/README.en.md b/README.en.md index 9afa476..c5e0cc2 100644 --- a/README.en.md +++ b/README.en.md @@ -1,77 +1,284 @@ # contract-match-http-autotest — HTTP API Automated Testing Demo for a Perpetual Contract Matching System -## 1. What Problem This Project Solves +> 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. -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: when an order request is submitted, the system actually performs four things behind the scenes—**funds freezing, order persistence, position changes, and cache updates**—and any failure in any one of them can lead to capital loss incidents. +## 1. 5-Minute Reading Guide -This project demonstrates a methodology for API automated testing of such systems. It focuses on three core aspects: +If you only have 5 minutes, read in this order: -1. **Triple Assertions**: HTTP response + database persistence + cache, all three are asserted simultaneously, not just the return value; -2. **Formula Layer for Expected Values**: Matching formulas such as margin, fees, liquidation price, bankruptcy price are implemented independently as pure functions. Expected values are **calculated**, not “run once and copy down” — if the formula is wrong, the test fails; if the system is wrong, the test also fails; -3. **YAML Data-Driven Testing**: Test cases are separated from data; a single test function covers normal, negative, and boundary value cases in one go. +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. -To allow the project to run **without a real environment**, the system under test is implemented as a local mock engine substitute (standard library `wsgiref` HTTP server + in-memory MySQL/Redis). The verification chain is completely isomorphic to a real project, and `pytest` runs all green without connecting to any external network, database, or middleware. +### Why a mock instead of a real environment -## 2. Architecture +- **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. -``` -┌────────────────────────── pytest Test Case Layer (case/) ──────────────────────────┐ -│ test_order_freeze.py Order placement freezes margin (triple assertions, data-driven with positive/negative cases) │ -│ test_position_open.py Market order opens position (reconciliation of position/funds/ledger/cache) │ -│ test_liquidation.py Liquidation trigger verification (price feed to liquidation price, risk fund ledger) │ -│ test_formula.py Pure function unit tests for the contract formula layer (expected values hand-calculated to prevent self-deception) │ -└───────────────┬──────────────────────────────┬───────────────────────────┘ - │ YAML data-driven │ Expected values -┌───────────────▼──────────────┐ ┌───────────▼──────────────┐ -│ data/*.yml │ │ formula/contract_formula │ -│ addOrder.yml / liquidation.yml│ │ frozen margin/liquidation price/bankruptcy price │ -│ formula.yml │ │ unrealized PnL/forced liquidation detection │ -└───────────────────────────────┘ └──────────────────────────┘ - │ requests(HTTP) ▲ Expected vs actual -┌───────────────▼──────────────────────────────▼───────────────────────────┐ -│ System Under Test Substitute (mock/) │ -│ server.py wsgiref HTTP server (random port, session-level startup in conftest) │ -│ engine.py Matching engine: order freeze/market order fill/cancel unfreeze/mark price/liquidation risk control │ -│ (internal fund calculation independently implemented, intentionally not reusing formula package) │ -│ fake_db.py / fake_cache.py In-memory MySQL / Redis (data plane for triple assertions) │ -└───────────────────────────────────────────────────────────────────────────┘ -``` +## 2. What Problem This Project Solves -Layer Responsibilities: +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. -| Layer | Directory | Responsibilities | +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 “what is given, what is expected” | -| Data Layer | `data/` | Case parameters and expected values, `[param dict, expected dict]` structure for parametrize unpacking | -| Formula Layer | `formula/` | Pure functions for matching business formulas, all in Decimal, the sole source of expected values | -| API Wrapper Layer | `api/` | Secondary encapsulation of the system’s HTTP APIs; test cases do not construct URLs directly | -| Common Layer | `common/` | YAML reading, HTTP client, Decimal assertion utilities | -| System Substitute | `mock/` | Local matching engine + HTTP server + in-memory DB/cache | -| Configuration Layer | `config/` | Contract parameters, fee rates, precision, etc. (all placeholder demo values) | +| 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) | -## 3. How to Run +## 6. How to Run ```bash cd contract-match-http-autotest python -m venv venv && source venv/bin/activate # optional -pip install -r requirements.txt # only pytest / requests / PyYAML -python -m pytest # run all tests -python -m pytest case/test_liquidation.py -v # run a single scenario +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 ``` -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 be executed in any order. +### Coverage -### What Triple Assertions Look Like in a Test Case +```bash +python -m pytest --cov=formula --cov=mock --cov-report=term-missing +``` -Take `case/test_order_freeze.py::test_limit_order_freeze` as an example: +Measured 2026-09-21 (macOS / Python 3.13.12 / pytest 9.1.1): -```python -# Expected values: independently calculated by the formula layer, independent of the system implementation -expect_frozen = formula.frozen_margin(price, quantity, marginRate, maker, taker) +``` +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% +``` -# First: HTTP response -assert body["code"] == 0 +**TOTAL line coverage = 96%**, with an honest account of what is not covered and why: -# Second: Database persistence — order fields / fund deduction and freezing / freeze ledger -assert_decimal_equal(after["total_money"], \ No newline at end of file +- 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) | diff --git a/README.md b/README.md index 19c45b6..0678b97 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # contract-match-http-autotest —— 永续合约撮合系统 HTTP 接口自动化测试演示工程 -## 一、5 分钟读法(给面试官的导览) +## 一、5 分钟快速导览 如果时间只有 5 分钟,建议按这个顺序看: -1. **先往下看「二、架构」的 ASCII 图** —— 30 秒看懂分层:用例层、接口层、被测系统、 +1. **先往下看「五、架构」的架构图** —— 30 秒看懂分层:用例层、接口层、被测系统、 校验面、公式层各就各位; 2. **再看「三、用例覆盖清单」** —— 一张表说清测了什么场景、多少用例、断言到哪几面, 这是测试工程师最该拿出的东西; @@ -15,9 +15,9 @@ ### 为什么用 mock 而不是真环境 -- **脱敏**:真实撮合系统的参数、接口路径、资金口径属前雇主资产,演示工程全部用 - 占位值重建,不出现任何真实公司信息; -- **可复现**:面试官 clone 下来 `pytest` 一把全绿,不需要申请环境、不需要 VPN、 +- **脱敏**:本工程不含任何真实企业信息 —— 合约参数、费率、字段命名、接口路径 + 全部是占位值与中性演示路径,由 mock 引擎在本地重建; +- **可复现**:clone 下来 `pytest` 一把全绿,不需要申请环境、不需要 VPN、 不需要外网; - **校验链路同构**:mock 的 HTTP 服务、落库、缓存的交互形态与真实微服务工程一致, 换真环境只需替换 `conftest.py` 的 fixture,用例代码一行不改; @@ -38,58 +38,48 @@ 了测试也会红; 3. **YAML 数据驱动**:用例与数据分离,一个用例函数覆盖正例/负例/边界值全家桶。 -为了让工程**脱离真实环境也能跑通**,被测撮合系统以本地 mock 引擎替身实现 +为了让工程**脱离真实环境也能跑通**,被测撮合系统以本地 mock 引擎实现 (标准库 wsgiref HTTP 服务 + 内存 MySQL/Redis),校验链路与真实工程完全同构, `pytest` 一把全绿,不连任何外网、数据库与中间件。 ## 三、用例覆盖清单 -共 **45** 条用例,全部通过(数据来源:`pytest --collect-only -q`,2026-09-19 实测): +共 **94** 条用例,全部通过(数据来源:`pytest --collect-only -q`,2026-09-21 实测)。 +其中 `case/` 下的场景与公式用例 **84** 条,`mock/` 下的生成器自测 **10** 条。 | 业务场景 | 用例数 | 断言面(HTTP / 落库 / 缓存) | 覆盖的关键点 | | --- | --- | --- | --- | -| 下单冻结保证金(正例,数据驱动) | 4 | HTTP + 落库 + 缓存 | 全仓限价买/卖开仓;冻结 = 起始保证金 + 孰高手续费;订单字段 / 资金扣减 / 冻结流水 / 冻结键值四面对账 | -| 下单非法入参(负例,数据驱动) | 15 | HTTP + 落库 + 缓存 | 价格/数量为 0 或负数、保证金率非法、余额不足等;**额外断言「无副作用」**:订单表无新增、资金无变动、缓存无残留 | -| 撤单解冻 | 1 | HTTP + 落库 + 缓存 | 冻结全额解冻回可用;解冻流水;冻结键值清理 | +| 下单冻结保证金(正例,数据驱动) | 15 | HTTP + 落库 + 缓存 | 全仓/逐仓 × 买/卖 × 起始保证金率三档;冻结 = 起始保证金 + 孰高手续费;订单字段 / 资金扣减 / 冻结流水 / 冻结键值四面对账 | +| 下单非法入参(负例,数据驱动) | 21 | HTTP + 落库 + 缓存 | 价格/数量为 0 或负数、保证金率非法、余额不足等;**额外断言「无副作用」**:订单表无新增、资金无变动、缓存无残留 | +| 撤单解冻(含状态机) | 8 | HTTP + 落库 + 缓存 | 冻结全额解冻回可用;解冻流水;冻结键值清理;重复撤单 / 撤已成交单 / 撤不存在单 / 缺单号的状态机与参数校验;解冻后可再次下单 | | 市价开仓成交 | 2 | HTTP + 落库 + 缓存 | 多/空两个方向;按 taker 费率立即成交;仓位 / 手续费流水 / 仓位缓存;标记价移动后未实现盈亏 | -| 强平触发校验(数据驱动) | 3 | HTTP + 落库 + 缓存 | 行情驱动到强平价触发;剩余保证金入风险基金;穿仓缺口由风险基金兜底并扣减可用;仓位清零 | -| 公式层纯函数单测(数据驱动) | 20 | 纯函数(无 IO) | 冻结保证金 / 未实现盈亏 / 破产价 / 强平价 / 爆仓判断,期望值**手算写死**防自证;含强平边界(`<=` 闭区间)与 float 精度反例 | +| 强平触发校验(数据驱动) | 6 | HTTP + 落库 + 缓存 | 安全价不触发、触发价强平两段式;破产价与公式一致;剩余保证金入风险基金;穿仓缺口由风险基金兜底并扣减可用;仓位清零、缓存键删除 | +| 公式层纯函数单测(数据驱动) | 32 | 纯函数(无 IO) | 冻结保证金 / 未实现盈亏 / 破产价 / 强平价 / 爆仓判断,期望值**手算写死**防自证;含强平边界(`<=` 闭区间)与 float 精度反例 | +| 生成器自测(`mock/test_*_gen.py`) | 10 | 纯函数 / 接口封装 | 早期用生成工具产出的辅助单测,已纳入 pytest 收集范围 | -> 说明:`mock/` 目录下的 `test_*_gen.py` 是早期用生成工具产出的辅助单测草稿, -> 不在 pytest 收集范围内(`pytest.ini` 的 `testpaths = case`),不参与上述统计。 +> 说明:`mock/` 目录下的 `test_*_gen.py` 已通过 `pytest.ini` 的 `testpaths = case mock` +> 纳入收集,上面的 94 条已包含它们;若只统计 `case/` 下的场景与公式用例,是 **84** 条。 -## 四、架构 +## 四、工程效率工具(tools/) -``` -┌────────────────────────── pytest 用例层 (case/) ──────────────────────────┐ -│ test_order_freeze.py 下单冻结保证金(三重校验,正例/负例数据驱动) │ -│ test_position_open.py 市价开仓成交(仓位/资金/流水/缓存四面对账) │ -│ test_liquidation.py 强平触发校验(行情驱动到强平价,风险基金流水) │ -│ test_formula.py 合约公式层纯函数单测(期望值手算写死防自证) │ -└───────────────┬──────────────────────────────┬───────────────────────────┘ - │ YAML 数据驱动 │ 期望值 -┌───────────────▼──────────────┐ ┌───────────▼──────────────┐ -│ data/*.yml │ │ formula/contract_formula │ -│ addOrder.yml / liquidation.yml│ │ 冻结保证金/强平价/破产价 │ -│ formula.yml │ │ 未实现盈亏/爆仓判断 │ -└───────────────────────────────┘ └──────────────────────────┘ - │ HTTP 调用(用例不直接拼 URL) ▲ 期望值 vs 实际值 -┌───────────────▼──────────────────────────────┴───────────────────────────┐ -│ 接口封装层 (api/order_api.py) │ -│ 下单 / 撤单 / 划转 / 标记价 / 风控接口的二次封装 │ -└───────────────┬──────────────────────────────────────────────────────────┘ - │ requests(HTTP) -┌───────────────▼──────────────────────────────────────────────────────────┐ -│ 被测系统替身 (mock/) │ -│ server.py wsgiref HTTP 服务(随机端口,conftest 会话级启动) │ -│ engine.py 撮合引擎:下单冻结/市价成交/撤单解冻/标记价/强平风控 │ -│ (内部资金计算独立实现,刻意不复用 formula 包) │ -│ ┌─ 校验面(数据面)──────────────────────────────────────────────────┐ │ -│ │ fake_db.py 内存 MySQL:account_future / order / 资金流水表 │ │ -│ │ fake_cache.py 内存 Redis:冻结键值 / 资金镜像 / 仓位缓存 │ │ -│ └──────────────────────────────────────────────────────────────────┘ │ -└───────────────────────────────────────────────────────────────────────────┘ -``` +自动化工程里除了"用例怎么写",还有一类问题是"工程怎么跑得动"——消息怎么解码、 +日志怎么追、脚本之间状态怎么传。本目录沉淀 3 个撮合类自动化工程里高频出现、 +并已全部脱敏为本地占位的效率工具: + +| 模块 | API | 解决的问题 | 典型场景 | +| --- | --- | --- | --- | +| `tools/msg_codec.py` | `encode(payload) / decode(msg)` | kline 行情经 RocketMQ 投递的消息体是 `base64(gzip(json))` 二进制流,消费端断言前必须还原;编解码收敛成纯函数,用例直接复用 | kline 行情消费的解压还原链路 | +| `tools/log_tail.py` | `tail(path)` 迭代器 + `extract_time(line)` | 撮合引擎日志用 `tail -c 0 -f` 跟随增量,正则抽 `[YYYY-MM-DD HH:MM:SS]` 业务时间戳,做下单→成交链路耗时统计;进程管道由迭代器托管,break 即终止子进程 | 撮合耗时统计脚本 | +| `tools/cache_utils.py` | `set/get/delete(key)` | 压测脚本写入、校验脚本读取的跨进程状态同步;用 diskcache 做本地磁盘缓存,与业务 DB 解耦,API 只有三个动词 | 撮合日志校验脚本的 CacheUtils | + +设计要点:这三个模块分别对应**二进制消息流上的 encode/decode**、 +**生产日志的进程管道控制**、**缓存层与 DB 层的解耦**,都是"把脚本技巧沉淀成 +工程组件"的典型动作。演示路径统一为 `/tmp/demo/log`、`/tmp/demo/match.log`、 +`/tmp/demo/cache`,不含任何真实生产地址。 + +## 五、架构 + +![系统架构](docs/architecture.png) 分层职责: @@ -100,15 +90,16 @@ | 公式层 | `formula/` | 撮合业务公式纯函数,全部 Decimal,是期望值的唯一来源 | | 接口封装层 | `api/` | 对被测系统 HTTP 接口的二次封装,用例不直接拼 URL | | 通用层 | `common/` | YAML 读取、HTTP 客户端、Decimal 断言工具 | -| 被测替身 | `mock/` | 本地撮合引擎 + HTTP 服务 + 内存库/缓存 | +| 被测系统 | `mock/` | 本地撮合引擎 + HTTP 服务 + 内存库/缓存 | +| 效率工具 | `tools/` | 消息编解码、日志跟随、跨进程缓存等工程组件 | | 配置层 | `config/` | 合约参数、费率、精度等(全部为演示占位值) | -## 五、怎么跑 +## 六、怎么跑 ```bash cd contract-match-http-autotest python -m venv venv && source venv/bin/activate # 可选 -pip install -r requirements.txt # pytest / pytest-cov / requests / PyYAML +pip install -r requirements.txt # pytest / pytest-cov / requests / PyYAML / diskcache python -m pytest # 全部用例 python -m pytest case/test_liquidation.py -v # 单个场景 python -m pytest -k liquidation # 按关键字筛选 @@ -120,37 +111,37 @@ python -m pytest -k liquidation # 按关键字筛选 python -m pytest --cov=formula --cov=mock --cov-report=term-missing ``` -2026-09-19 实测输出(macOS / Python 3.13 / pytest 9.1.1): +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 1 98% 32 +formula/contract_formula.py 50 0 100% mock/__init__.py 0 0 100% -mock/engine.py 238 20 92% 80, 104, 158, 203, 206, 209, 223-231, 238, 247, 250, 388-389 +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 60 0% 1-84 -mock/test_formula_gen.py 42 42 0% 1-89 +mock/test_api_client_gen.py 60 0 100% +mock/test_formula_gen.py 42 0 100% ----------------------------------------------------------- -TOTAL 438 126 71% +TOTAL 438 19 96% ``` -**TOTAL line coverage = 71%**,如实说明未覆盖部分及原因: +**TOTAL line coverage = 96%**,如实说明未覆盖部分及原因: -- `mock/test_*_gen.py` 两个文件共 102 条语句 0% 覆盖:它们是早期用生成工具产出的 - 辅助单测草稿,**不在 pytest 收集范围内**(`pytest.ini` 的 `testpaths = case`), - 属于工程里的「非执行代码」,把整个 TOTAL 从 93% 拉低到 71% —— 若只统计实际参与 - 运行的业务代码(formula + mock 四个模块,336 条语句),覆盖率为 **93%**; -- `mock/engine.py` 未覆盖的 20 行集中在异常/兜底分支(非法参数防御、穿仓的极端 +- `mock/engine.py` 未覆盖的 16 行集中在异常/兜底分支(非法参数防御、穿仓的极端 边界路径 223-231 等),这些分支在正常场景用例里走不到,靠负例数据也只能覆盖 一部分 —— 这是接口级测试对单元级分支的天然盲区; - `mock/server.py` 未覆盖的 37-38 行是服务启动入口的兜底代码,只在进程直接运行 时触发,conftest 以函数调用方式拉起服务所以走不到; -- `formula/contract_formula.py` 第 32 行与 `mock/fake_cache.py` 第 29 行均为单条 - 防御性分支。 +- `mock/fake_cache.py` 第 29 行是单条防御性分支; +- `formula/contract_formula.py` 50 条语句 **100% 覆盖** —— 公式层是期望值的唯一 + 来源,不留未覆盖分支是刻意要求; +- `mock/test_*_gen.py` 两个文件共 102 条语句已 **100% 覆盖**:它们早期是生成工具 + 产出的辅助单测草稿,现已通过 `pytest.ini` 的 `testpaths = case mock` 纳入收集, + 不再拉低 TOTAL。 无需任何环境准备:conftest 会自动在 `127.0.0.1` 随机端口拉起 mock 撮合服务, 并在**每个用例前重置引擎数据**,用例相互隔离、可重复执行、可乱序执行。 @@ -171,7 +162,7 @@ assert_decimal_equal(after["total_money"], before["total_money"] - expect_frozen assert_decimal_equal(flow["quantity"], expect_frozen) # 三重:缓存 —— 冻结键值、资金镜像(与落库字段命名不同,归一化后比对) -assert_decimal_equal(cache.get("frozen_margin:userId:...:orderNo:..."), expect_frozen) +assert_decimal_equal(cache.get("order_freeze:userId:...:orderNo:..."), expect_frozen) ``` ### mock 说明(重要) @@ -185,7 +176,7 @@ assert_decimal_equal(cache.get("frozen_margin:userId:...:orderNo:..."), expect_f 市价按 taker 费率立即成交、撤单全额解冻、强平剩余保证金入风险基金、穿仓缺口 由风险基金兜底并扣减可用余额。 -## 六、关键难点及我的处理 +## 七、关键难点及我的处理 ### 1. 金额精度:一律 Decimal,禁止 float @@ -209,8 +200,8 @@ assert_decimal_equal(cache.get("frozen_margin:userId:...:orderNo:..."), expect_f ### 3. 三重校验的落地:落库与缓存字段不一致 -- 落库校验断言 `account_future` / `order` / `user_currency_flow` 三张表, - 缓存校验断言 `frozen_margin:*` / `account_future:*` / `position:*` 三类键; +- 落库校验断言 `futures_account` / `order` / `account_flow` 三张表, + 缓存校验断言 `order_freeze:*` / `futures_account:*` / `position:*` 三类键; - 库(snake_case)与缓存(camelCase)命名不一致,比对前做字段归一化 —— 还原 真实工程的脏活,也是缓存校验最容易踩的坑; - 缓存值统一转字符串(模拟 Redis string 类型),断言时再转回 Decimal。 @@ -222,21 +213,22 @@ assert_decimal_equal(cache.get("frozen_margin:userId:...:orderNo:..."), expect_f - 负例额外断言"**无副作用**":非法请求不仅返回错误码,还必须保证订单表无 新增、资金表无变动、缓存无残留 —— 接口测试里负例只看返回码是不够的。 -### 5. 环境解耦:mock 替身保持与真实被测系统同构 +### 5. 环境解耦:mock 保持与真实被测系统同构 - 真实工程里被测系统是独立微服务集群 + MySQL + Redis 集群;演示工程用 - wsgiref 服务 + 内存库/缓存替身,**用例代码一行不改**即可在两种形态间切换 + wsgiref 服务 + 内存库/缓存,**用例代码一行不改**即可在两种形态间切换 (只需替换 conftest 的 fixture 实现); - mock 服务与数据面共享同一个引擎实例,HTTP 请求改的内存态就是"落库/缓存" 校验读到的内存态,与真实系统的因果链一致。 -## 七、目录结构 +## 八、目录结构 ``` contract-match-http-autotest/ ├── README.md # 本文档 -├── requirements.txt # pytest / pytest-cov / requests / PyYAML -├── pytest.ini # testpaths = case +├── README.en.md # 英文版 +├── requirements.txt # pytest / pytest-cov / requests / PyYAML / diskcache +├── pytest.ini # testpaths = case mock ├── conftest.py # fixture:启动 mock 服务、注入数据面、用例隔离 ├── config/ │ └── settings.py # 合约参数/费率/精度(演示占位值) @@ -249,22 +241,30 @@ contract-match-http-autotest/ ├── api/ │ └── order_api.py # 下单/撤单/划转/标记价/风控接口封装 ├── mock/ -│ ├── engine.py # 撮合引擎(被测系统替身) +│ ├── engine.py # 撮合引擎(被测系统) │ ├── server.py # wsgiref HTTP 服务 │ ├── fake_db.py # 内存 MySQL -│ └── fake_cache.py # 内存 Redis +│ ├── fake_cache.py # 内存 Redis +│ ├── test_api_client_gen.py # 生成器自测:接口封装 +│ └── test_formula_gen.py # 生成器自测:公式层 +├── tools/ +│ ├── msg_codec.py # 消息体 base64(gzip(json)) 编解码 +│ ├── log_tail.py # 日志增量跟随 + 业务时间戳抽取 +│ └── cache_utils.py # diskcache 封装的跨进程状态缓存 ├── case/ │ ├── test_order_freeze.py # 场景一:下单冻结保证金(三重校验) +│ ├── test_cancel_order.py # 场景四:撤单解冻(状态机/参数/无副作用) │ ├── test_position_open.py # 场景二:市价开仓成交 │ ├── test_liquidation.py # 场景三:强平触发校验 │ └── test_formula.py # 公式层纯函数单测 └── data/ ├── addOrder.yml # 下单正例/负例(数据驱动) + ├── cancelOrder.yml # 撤单场景数据 ├── liquidation.yml # 强平场景数据 └── formula.yml # 公式期望值(手算写死) ``` -## 八、业务口径速查(演示参数) +## 九、业务口径速查(演示参数) | 口径 | 值/规则 | | --- | --- | @@ -276,4 +276,4 @@ contract-match-http-autotest/ | 强平价(逐仓) | `open + direction × (maintain − extra − init) / qty` | | 破产价(逐仓) | 多:`open×(1−rate) − extra/qty`;空:`open×(1+rate) + extra/qty` | | 穿仓 | 强平后保证金余额为负:缺口扣减可用余额,由风险基金兜底 | -| 资金流水类型 | 1 划入 / 3 冻结 / 4 解冻 / 5 手续费 / 7 开仓 / 9 强平 | +| 资金流水类型 | 划入 / 划出 / 冻结 / 解冻 / 手续费 / 开仓 / 强平(枚举值见 `mock/engine.py` 的 `FLOW_*` 常量,均为演示值) | diff --git a/docs/architecture.png b/docs/architecture.png new file mode 100644 index 0000000..b25316b Binary files /dev/null and b/docs/architecture.png differ diff --git a/docs/architecture.svg b/docs/architecture.svg new file mode 100644 index 0000000..7df7151 --- /dev/null +++ b/docs/architecture.svg @@ -0,0 +1 @@ +pytest 用例层(case/)test_order_freeze.py下单冻结保证金(三重校验,正例/负例数据驱动)test_cancel_order.py撤单解冻(状态机/参数/无副作用)test_position_open.py市价开仓成交(仓位/资金/流水/缓存四面对账)test_liquidation.py强平触发校验(行情驱动到强平价,风险基金流水)test_formula.py合约公式层纯函数单测(期望值手算写死防自证)YAML 数据驱动期望值data/*.ymladdOrder.yml / liquidation.ymlcancelOrder.yml / formula.ymlformula/contract_formula冻结保证金 / 强平价 / 破产价未实现盈亏 / 爆仓判断HTTP 调用(用例不直接拼 URL)期望值 vs 实际值接口封装层(api/order_api.py)下单 / 撤单 / 划转 / 标记价 / 风控接口的二次封装requests(HTTP)被测系统(mock/)server.pywsgiref HTTP 服务(随机端口,conftest 会话级启动)engine.py撮合引擎:下单冻结 / 市价成交 / 撤单解冻 / 标记价 / 强平风控(内部资金计算独立实现,刻意不复用 formula 包)校验面(数据面)fake_db.py 内存 MySQL:futures_account / order / account_flowfake_cache.py 内存 Redis:冻结键值 / 资金镜像 / 仓位缓存 \ No newline at end of file