#!/usr/bin/env python # -*- coding: utf-8 -*- """单测:每条都对应一条判断或一处修复,没有为了凑数而存在的用例。 判断② TTL 与显式清理 -> TestCacheTtl D1 去重窗口按币对隔离 -> TestSlidingWindow D3 getattr 分发与动作缓存 -> TestActionCache 流量形态 加权随机采样器 -> TestWeightedRandom 运行: python -m pytest tests/ -q """ from __future__ import annotations import os import sys import time from collections import Counter sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import pytest # noqa: E402 import config # noqa: E402 from mark_price_service import MarkPriceSubscriber, PriceCache # noqa: E402 from requester import Api, weighted_ops # noqa: E402 @pytest.fixture def subscriber(tmp_path): cache = PriceCache(path=str(tmp_path / "win")) yield MarkPriceSubscriber(cache=cache, window_len=2), cache cache.close() @pytest.fixture def api(tmp_path): a = Api(cache=PriceCache(path=str(tmp_path / "act"))) yield a a.store.close() a.cache.close() # ========================================================================== # 判断②:常驻任务的失败是慢性的——TTL 与显式清理 # ========================================================================== class TestCacheTtl: def test_expired_price_reads_back_empty(self, tmp_path): with PriceCache(path=str(tmp_path / "ttl"), ttl=0.3) as cache: cache.set_price(5, 123.0) assert cache.get_price(5) == 123.0 # TTL 之前还活着 time.sleep(0.6) assert cache.get_price(5) is None # TTL 之后消失 def test_entry_count_does_not_grow_with_runtime(self, tmp_path): with PriceCache(path=str(tmp_path / "grow"), ttl=0.3) as cache: for i in range(120): # 模拟常驻循环写入大量短命键 cache.set(f"tick:{i}", i, ttl=0.3) assert cache.size() >= 100 # 过期前这些条目都在 time.sleep(0.6) assert cache.expire() >= 100 # 清理一次后,大小只跟着**存活**条目走,而不是跟着累计写入量走。 # 这条修复的全部意义就在这——它把「内存随运行时间悄悄膨胀」变成可复现断言。 assert cache.size() <= 20 def test_live_entries_survive_expire(self, tmp_path): with PriceCache(path=str(tmp_path / "mix"), ttl=0.3) as cache: cache.set("short", 1, ttl=0.2) cache.set("long", 2, ttl=30) time.sleep(0.6) cache.expire() assert cache.get("short") is None assert cache.get("long") == 2 # ========================================================================== # D1:滑动窗口去重是按币对的,不是全局的 # ========================================================================== class TestSlidingWindow: def test_interleaved_contracts_are_independent(self, subscriber): sub, cache = subscriber accepts = [ sub.handle_price(4, 10.0), # 币对 4 的首个观测 -> 接受 sub.handle_price(5, 10.0), # 币对 5 的首个观测 -> 接受 sub.handle_price(4, 10.0), # 币对 4 无变化 -> 拒绝 ] # 全局窗口会把第 2 个也拒掉(它上一条也是 10.0),让币对 5 留在未缓存状态。 assert accepts == [True, True, False] assert cache.get_price(4) == 10.0 assert cache.get_price(5) == 10.0 def test_each_contract_tracks_its_own_changes(self, subscriber): sub, cache = subscriber sub.handle_price(4, 100.0) sub.handle_price(5, 200.0) assert sub.handle_price(4, 101.0) is True # 币对 4 变了:只更新 4 assert cache.get_price(4) == 101.0 assert cache.get_price(5) == 200.0 assert sub.handle_price(5, 200.0) is False # 币对 5 重复:不更新 5,也不搅动 4 assert sub.handle_price(4, 101.0) is False def test_windows_are_separate_objects(self, subscriber): sub, _ = subscriber for cid, px in ((4, 1.0), (5, 2.0), (6, 3.0)): sub.handle_price(cid, px) assert set(sub._windows) == {4, 5, 6} assert list(sub._windows[4]) == [1.0] # 每条窗口只装自己币对的历史 assert list(sub._windows[5]) == [2.0] # ========================================================================== # D3:getattr 分发与 @action 缓存 # ========================================================================== class TestActionCache: def test_action_records_produced_order(self, api): spec = api.open_order(user_id="1", contract_id=5) cached = api.cache.get("order_info") assert len(cached) == 1 assert cached[0]["class_name"] == "open_order" assert cached[0]["json"]["contractId"] == 5 assert spec["method"] == "POST" def test_action_accumulates_across_calls(self, api): api.open_order(user_id="1", contract_id=5) api.open_order(user_id="2", contract_id=6) api.market_open_order(user_id="3") assert [c["class_name"] for c in api.cache.get("order_info")] == [ "open_order", "open_order", "market_open_order", ] def test_dispatch_is_getattr_not_eval(self, api): # D3 约定:操作通过属性查找命中 Api 上的方法。 assert callable(getattr(api, "open_order")) # 仅仅解析名字不应有任何副作用。 assert api.cache.get("order_info") is None # ========================================================================== # 流量形态:加权随机采样器 # ========================================================================== class TestWeightedRandom: def test_only_valid_ops_emitted(self): assert set(weighted_ops(2000)) <= {name for name, _ in config.WEIGHTED_OPS} def test_zero_weight_ops_never_sampled(self): zero = {name for name, w in config.WEIGHTED_OPS if w == 0} assert zero, "配置里应当存在权重为 0 的操作(transfer 就是那个哨兵)" assert set(weighted_ops(20000)) & zero == set() def test_weights_drive_relative_frequency(self): counts = Counter(weighted_ops(20000)) # open_order(200) > condition_order(50) > cancel_order(10) assert counts["open_order"] > counts["condition_order"] > counts["cancel_order"] assert counts["open_order"] > counts["cancel_order"] * 5 # 权重 10 的操作罕见但非零。 assert 0 < counts["reverse_position"] < counts["open_order"]