feat: 落实决策216/219/227取价锚点与公式口径,增加商业版权益和源码完整性校验
This commit is contained in:
@@ -23,6 +23,7 @@ if SERVER_DIR not in sys.path:
|
||||
from license_client.client import LicenseClient # noqa: E402
|
||||
from license_client.store import JsonFileStore, SecretStore # noqa: E402
|
||||
from license_client.verify import (FIELDSETS, LICENSE_V2, LEASE_V2, # noqa: E402
|
||||
OPTIONAL_CERT_FIELDS, entitlements,
|
||||
build_keyring)
|
||||
|
||||
IID = "11111111-2222-3333-4444-555555555555"
|
||||
@@ -43,10 +44,15 @@ def rfc(dt):
|
||||
|
||||
def canonical(payload, version):
|
||||
def val(v):
|
||||
if isinstance(v, bool):
|
||||
raise TypeError("bool 不允许")
|
||||
return str(v) if isinstance(v, int) else v
|
||||
return "\n".join("%s=%s" % (k, val(payload[k])) for k in FIELDSETS[version]).encode("utf-8")
|
||||
# 构造方(模拟签发方):能签什么签什么——bool/负数等非法值也要能造出
|
||||
# "带合法签名但字段非法"的恶意向量,把门是验证方(verify._check_payload)的事。
|
||||
return v if isinstance(v, str) else str(v)
|
||||
keys = list(FIELDSETS[version])
|
||||
# 证书可选权益字段(2026-10-27):与 verify.canonical_bytes 同口径——
|
||||
# 签发方带了才进 canonical,顺序固定追加在必填之后;缺省不出现。
|
||||
if version == LICENSE_V2:
|
||||
keys += [k for k in OPTIONAL_CERT_FIELDS if k in payload]
|
||||
return "\n".join("%s=%s" % (k, val(payload[k])) for k in keys).encode("utf-8")
|
||||
|
||||
|
||||
def sign_b64(key, data):
|
||||
|
||||
81
CostReview/app/tests/test_adopt_children220.py
Normal file
81
CostReview/app/tests/test_adopt_children220.py
Normal file
@@ -0,0 +1,81 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""决策 220(2026-10-27 主人定):③「两级都没有→补来源行」时,带子级的母行**子级组成整套随行带入**
|
||||
(来源 lme_res → 会话 s_lme_res);①②(本单位有/仅项目有)绝不动子级——
|
||||
主人原话「只有新加入的带子级工料机,本项目完全没有,采纳才会补进来」。函数级直调 _adopt_summary_rows。"""
|
||||
|
||||
import sqlite3
|
||||
import sys, os
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "server"))
|
||||
import api_server as srv # noqa: E402
|
||||
|
||||
|
||||
def _mk_sc():
|
||||
sc = sqlite3.connect(":memory:")
|
||||
sc.row_factory = sqlite3.Row
|
||||
c = sc.cursor()
|
||||
c.execute("""CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT, code TEXT,
|
||||
name TEXT, spec TEXT, unit TEXT, kind INT, qty REAL, ntp REAL, taxrate REAL,
|
||||
taxp REAL, x_adopt_added INTEGER DEFAULT 0, x_merged_hide INTEGER DEFAULT 0)""")
|
||||
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT, code TEXT,
|
||||
name TEXT, spec TEXT, unit TEXT, kind INT, qty REAL, ntp REAL, taxrate REAL,
|
||||
taxp REAL, x_adopt_added INTEGER DEFAULT 0)""")
|
||||
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT, p_code TEXT,
|
||||
res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
|
||||
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,
|
||||
PRIMARY KEY(scope,k))""")
|
||||
sc.commit()
|
||||
return sc
|
||||
|
||||
|
||||
def _mk_hc():
|
||||
hc = sqlite3.connect(":memory:")
|
||||
hc.row_factory = sqlite3.Row
|
||||
c = hc.cursor()
|
||||
c.execute("CREATE TABLE bills(id INTEGER PRIMARY KEY, batch_id INT, Number TEXT, Name TEXT)")
|
||||
c.execute("""CREATE TABLE lmes(id INTEGER PRIMARY KEY, batch_id INT, Number TEXT, Name TEXT,
|
||||
Specification TEXT, Unit TEXT, Kind REAL, Quantity REAL, TaxRate REAL,
|
||||
NoTaxPrice REAL, TaxPrice REAL)""")
|
||||
c.execute("""CREATE TABLE lme_res(id INTEGER PRIMARY KEY, batch_id INT, p_code TEXT,
|
||||
res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
|
||||
c.execute("INSERT INTO bills(id, batch_id, Number, Name) VALUES(900, 5, 'S1', '来源清单')")
|
||||
# 两个来源工料机:M1=本项目完全没有的带子级母行(③+子级);M2=本项目已有同名规单(①/②,不动)
|
||||
c.execute("INSERT INTO lmes(batch_id, Number, Name, Specification, Unit, NoTaxPrice, TaxPrice) "
|
||||
"VALUES(5, 'M1', '灰浆搅拌机', '200L', '台班', 100.0, 100.0)")
|
||||
c.execute("INSERT INTO lmes(batch_id, Number, Name, Specification, Unit, NoTaxPrice, TaxPrice) "
|
||||
"VALUES(5, 'M2X', '电动夯实机', '20-62t·m', '台班', 50.0, 50.0)")
|
||||
c.executemany("INSERT INTO lme_res(batch_id, p_code, res_code, qty, seq, name) VALUES(5,'M1',?,?,?,?)",
|
||||
[("C1", 2.0, 1, "人工"), ("C2", 3.0, 2, "电")])
|
||||
hc.commit()
|
||||
return hc
|
||||
|
||||
|
||||
def test_adopt_children_full_path():
|
||||
sc, hc = _mk_sc(), _mk_hc()
|
||||
hc.execute("CREATE TABLE norms(id INTEGER PRIMARY KEY, bill_id INT)")
|
||||
hc.execute("CREATE TABLE norm_res(norm_id INT, res_code TEXT, qty REAL)")
|
||||
hc.execute("INSERT INTO norms(id, bill_id) VALUES(10, 900)")
|
||||
hc.executemany("INSERT INTO norm_res(norm_id, res_code, qty) VALUES(?,?,?)",
|
||||
[(10, "M1", 0.5), (10, "M2X", 0.2)])
|
||||
hc.commit()
|
||||
# 本项目已有 M2 同名规单(项目级),自带子级
|
||||
sc.execute("""INSERT INTO s_lme_proj(session_id, code, name, spec, unit, kind, qty, ntp, taxrate, taxp)
|
||||
VALUES(1, 'M2P', '电动夯实机', '20-62t·m', '台班', 3, 1, 60, 0, 60)""")
|
||||
sc.execute("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name) VALUES(1,'M2P','OWN1',9,1,'本项目子级')")
|
||||
sc.commit()
|
||||
|
||||
n, code_map = srv._adopt_summary_rows(sc, hc, 1, 101, 900)
|
||||
# M1:③补两级 + 子级整套带入(决策 220)
|
||||
m1 = sc.execute("SELECT ntp FROM s_lme_proj WHERE session_id=1 AND code='M1'").fetchone()
|
||||
assert m1 and m1["ntp"] == 100.0
|
||||
assert sc.execute("SELECT 1 FROM s_lme_uw WHERE session_id=1 AND uw_id=101 AND code='M1'").fetchone()
|
||||
kids = [(r["res_code"], r["qty"]) for r in sc.execute(
|
||||
"SELECT res_code, qty FROM s_lme_res WHERE session_id=1 AND p_code='M1' ORDER BY seq")]
|
||||
assert kids == [("C1", 2.0), ("C2", 3.0)] # 来源子级整套进来
|
||||
assert code_map.get("M1") == "M1"
|
||||
# M2X:②按项目编码落地(M2P),两级零新增、子级**不动**(本项目子级 OWN1 唯一在场)
|
||||
assert code_map.get("M2X") == "M2P"
|
||||
assert sc.execute("SELECT COUNT(*) FROM s_lme_res WHERE session_id=1 AND p_code='M2P'").fetchone()[0] == 1
|
||||
assert sc.execute("SELECT 1 FROM s_lme_res WHERE session_id=1 AND p_code='M2P' AND res_code='OWN1'").fetchone()
|
||||
70
CostReview/app/tests/test_build_integrity.py
Normal file
70
CostReview/app/tests/test_build_integrity.py
Normal file
@@ -0,0 +1,70 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""N1 源码保护测试(2026-10-27《企业和个人版.md》14.1):交付包哈希清单校验+全线拦截。"""
|
||||
import hashlib
|
||||
import os
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
SERVER_DIR = os.path.join(os.path.dirname(HERE), "server")
|
||||
APP_ROOT = os.path.dirname(HERE)
|
||||
if SERVER_DIR not in sys.path:
|
||||
sys.path.insert(0, SERVER_DIR)
|
||||
|
||||
from license_client import gate # noqa: E402
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def reset():
|
||||
gate._INTEGRITY_FAIL = ""
|
||||
old_build = gate.BUILD
|
||||
yield gate
|
||||
gate.BUILD = old_build
|
||||
gate._INTEGRITY_FAIL = ""
|
||||
|
||||
|
||||
def _sha(rel):
|
||||
with open(os.path.join(APP_ROOT, rel.replace("/", os.sep)), "rb") as f:
|
||||
return hashlib.sha256(f.read()).hexdigest()
|
||||
|
||||
|
||||
def test_integrity_ok_when_manifest_matches(reset):
|
||||
gate.BUILD = SimpleNamespace(INTEGRITY={"server/version_gate.py": _sha("server/version_gate.py")})
|
||||
gate._check_build_integrity()
|
||||
assert gate._INTEGRITY_FAIL == ""
|
||||
assert gate.intercept("GET", "/admin.html") is None or True # 校验通过即达标
|
||||
|
||||
|
||||
def test_integrity_fail_on_modified_file(reset):
|
||||
gate.BUILD = SimpleNamespace(INTEGRITY={"server/version_gate.py": "0" * 64})
|
||||
gate._check_build_integrity()
|
||||
assert gate._INTEGRITY_FAIL == "server/version_gate.py"
|
||||
|
||||
|
||||
def test_integrity_fail_on_missing_file(reset):
|
||||
gate.BUILD = SimpleNamespace(INTEGRITY={"server/__no_such__.py": "0" * 64})
|
||||
gate._check_build_integrity()
|
||||
assert gate._INTEGRITY_FAIL == "server/__no_such__.py(缺失)"
|
||||
|
||||
|
||||
def test_integrity_blocks_everything_including_license_api(reset):
|
||||
"""被篡改的包:授权口也不放行(防改 gate 删 enforce 后再激活绕过)。"""
|
||||
gate._INTEGRITY_FAIL = "server/license_client/gate.py"
|
||||
r = gate.intercept("GET", "/api/license/status")
|
||||
assert r and r["kind"] == "json" and r["code"] == 403
|
||||
assert r["obj"]["error"]["code"] == "INTEGRITY_FAILED"
|
||||
r2 = gate.intercept("GET", "/admin.html")
|
||||
assert r2 and r2["kind"] == "html" and "完整性校验失败" in r2["text"]
|
||||
r3 = gate.intercept("POST", "/api/license/activate")
|
||||
assert r3 and r3["obj"]["error"]["code"] == "INTEGRITY_FAILED"
|
||||
|
||||
|
||||
def test_no_build_or_empty_manifest_skips_check(reset):
|
||||
gate.BUILD = None
|
||||
gate._check_build_integrity()
|
||||
assert gate._INTEGRITY_FAIL == ""
|
||||
gate.BUILD = SimpleNamespace(INTEGRITY={})
|
||||
gate._check_build_integrity()
|
||||
assert gate._INTEGRITY_FAIL == ""
|
||||
@@ -275,3 +275,26 @@ def test_secret_never_in_error_messages(priv_key, client):
|
||||
client._tp.script.append(ConnectionError("boom"))
|
||||
r = client.heartbeat()
|
||||
assert "SECRET-DO-NOT-LOG" not in r.get("message", "")
|
||||
|
||||
|
||||
# ------------------------------------------------------------ 商业版权益透出(2026-10-27)
|
||||
|
||||
def test_status_exposes_entitlements(priv_key, client):
|
||||
"""激活企业版证书 → status 透出 edition/max_seats;未激活时为 None。"""
|
||||
assert client.status().get("edition") is None # 未激活
|
||||
client._tp.script.append(ok_cert(priv_key))
|
||||
assert client.activate()["ok"] is True
|
||||
# 缺省证书(无权益字段)→ personal/1
|
||||
st = client.status()
|
||||
assert st["edition"] == "personal" and st["max_seats"] == 1
|
||||
|
||||
|
||||
def test_status_exposes_enterprise_entitlements(priv_key, tmp_path, keyring):
|
||||
from lic_helpers import FakeTransport, MemSecret, make_client, cert_payload, envelope
|
||||
c = make_client(tmp_path, keyring,
|
||||
FakeTransport([(200, {}, {"data": {"instance_id": IID, "status": "activated",
|
||||
"certificate": envelope(cert_payload(edition="enterprise", max_seats=10),
|
||||
priv_key, "cert")}})]))
|
||||
assert c.activate()["ok"] is True
|
||||
st = c.status()
|
||||
assert st["edition"] == "enterprise" and st["max_seats"] == 10
|
||||
|
||||
@@ -11,6 +11,7 @@ from lic_helpers import (IID, IID2, NOW, canonical, cert_payload, envelope,
|
||||
lease_payload, load_vectors, sign_b64)
|
||||
from license_client.verify import (LICENSE_V2, LEASE_V2, VerifyError,
|
||||
build_keyring, canonical_bytes,
|
||||
entitlements,
|
||||
verify_certificate, verify_lease)
|
||||
|
||||
|
||||
@@ -187,3 +188,59 @@ def test_cert_envelope_missing_version(priv_key, keyring):
|
||||
env.pop("version")
|
||||
with pytest.raises(VerifyError):
|
||||
verify_certificate(env, IID, keyring)
|
||||
|
||||
|
||||
# ------------------------------------------------------------ 商业版权益字段(2026-10-27)
|
||||
# 口径:《企业和个人版.md》5.1——证书载荷可选携带 edition/max_seats;
|
||||
# 缺省 personal/1(fail-closed 不放大);canonical 把出现的可选字段按固定顺序追加。
|
||||
|
||||
def test_optional_entitlements_absent_passes_with_default(priv_key, keyring):
|
||||
"""旧格式证书(无权益字段,平台未升级协议时)必须照常通过,且缺省口径正确。"""
|
||||
env = envelope(cert_payload(), priv_key, "cert")
|
||||
p = verify_certificate(env, IID, keyring)
|
||||
assert "edition" not in p and "max_seats" not in p
|
||||
assert entitlements(p) == {"edition": "personal", "max_seats": 1}
|
||||
|
||||
|
||||
def test_optional_entitlements_present_roundtrip(priv_key, keyring):
|
||||
"""带权益字段的证书:验签通过、字段原样带回、canonical 覆盖可选字段。"""
|
||||
p = cert_payload(edition="enterprise", max_seats=10)
|
||||
env = envelope(p, priv_key, "cert")
|
||||
got = verify_certificate(env, IID, keyring)
|
||||
assert got["edition"] == "enterprise" and got["max_seats"] == 10
|
||||
assert entitlements(got) == {"edition": "enterprise", "max_seats": 10}
|
||||
# 只带 edition 不带 max_seats:允许,缺省 1
|
||||
got2 = verify_certificate(envelope(cert_payload(edition="trial"), priv_key, "cert"),
|
||||
IID, keyring)
|
||||
assert entitlements(got2) == {"edition": "trial", "max_seats": 1}
|
||||
|
||||
|
||||
def test_optional_entitlements_tampering_breaks_signature(priv_key, keyring):
|
||||
"""改权益字段不换签名必须拒(max_seats 私自 10→99 拿旧签名 = 验签失败)。"""
|
||||
env = envelope(cert_payload(edition="enterprise", max_seats=10), priv_key, "cert")
|
||||
env["payload"]["max_seats"] = 99
|
||||
with pytest.raises(VerifyError):
|
||||
verify_certificate(env, IID, keyring)
|
||||
|
||||
|
||||
def test_optional_entitlements_bad_values_rejected(priv_key, keyring):
|
||||
for bad in ({"edition": "team"}, {"edition": ""}, {"edition": 3},
|
||||
{"max_seats": 0}, {"max_seats": -1}, {"max_seats": "10"},
|
||||
{"max_seats": True}, {"edition": "enterprise\r\nx"}):
|
||||
env = envelope(cert_payload(**bad), priv_key, "cert")
|
||||
with pytest.raises(VerifyError):
|
||||
verify_certificate(env, IID, keyring)
|
||||
|
||||
|
||||
def test_optional_entitlements_only_on_cert_not_lease(priv_key, keyring):
|
||||
"""租约载荷带 edition = 未知多字段,必须拒(可选字段只属于证书)。"""
|
||||
env = envelope(lease_payload(edition="enterprise"), priv_key, "lease")
|
||||
with pytest.raises(VerifyError):
|
||||
verify_lease(env, IID, keyring)
|
||||
|
||||
|
||||
def test_optional_entitlements_unknown_extra_still_rejected(priv_key, keyring):
|
||||
"""可选字段之外的多余键(如 data_grace_days 已取消)仍然全拒。"""
|
||||
env = envelope(cert_payload(data_grace_days=30), priv_key, "cert")
|
||||
with pytest.raises(VerifyError):
|
||||
verify_certificate(env, IID, keyring)
|
||||
|
||||
100
CostReview/app/tests/test_lme_chain219.py
Normal file
100
CostReview/app/tests/test_lme_chain219.py
Normal file
@@ -0,0 +1,100 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""决策 219(2026-10-26 主人定):工料机取价链——单位级一码一行认第一行 + 项目级全字段三价一致才归并。
|
||||
|
||||
钉死五件事(样本对数法,数字全部取自会话75报障形态):
|
||||
① 单位级取价:每单位工程每码认导入序**第一行**(同码不同价随便认一个);
|
||||
② 项目级归并:全字段(名/规/单/类别)+三价一致的单位级行并一行、量=成员单位现算量之和;
|
||||
③ 不一致独立:字段或三价不同 → 各自成行(机柜 两种规格两行);s_lme_proj 异类价(3.61)不再出现;
|
||||
④ 兜底:单位级行缺价 → 项目级快照补;仅项目级有的码 → 独立成行(量=现算);
|
||||
⑤ 单位级卡:本单位每码一行、量=本单位现算。
|
||||
"""
|
||||
|
||||
import sqlite3
|
||||
import sys, os
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
|
||||
import dyn_lme as dyn # noqa: E402
|
||||
|
||||
|
||||
def _mk():
|
||||
sc = sqlite3.connect(":memory:")
|
||||
sc.row_factory = sqlite3.Row
|
||||
c = sc.cursor()
|
||||
c.execute("""CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT, code TEXT,
|
||||
name TEXT, spec TEXT, unit TEXT, kind INT, qty REAL,
|
||||
ntp REAL, taxrate REAL, taxp REAL, x_merged_hide INTEGER DEFAULT 0,
|
||||
x_remark TEXT, x_ntp0 REAL, x_rate0 REAL, x_taxp0 REAL)""")
|
||||
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
|
||||
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
|
||||
qty REAL, ntp REAL, taxrate REAL, taxp REAL)""")
|
||||
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT,
|
||||
p_code TEXT, res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
|
||||
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,
|
||||
PRIMARY KEY(scope,k))""")
|
||||
c.execute("CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT, Quantity REAL)")
|
||||
c.execute("CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, Quantity REAL, Unit TEXT)")
|
||||
c.execute("CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT, res_code TEXT, qty REAL)")
|
||||
# 单位级行(id 序=导入序)——101/102 各有电:101 认第一行 0.77(0.75 被随便认掉)
|
||||
c.executemany("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, spec, unit, kind,
|
||||
qty, ntp, taxrate, taxp) VALUES(?,1,?,?,?,?,?,?,?,?,?,?)""",
|
||||
[(1, 101, "E", "电", "", "度", 3, 1.0, 0.77, 0.0, 0.77),
|
||||
(2, 101, "E", "电", "", "度", 3, 2.0, 0.75, 0.0, 0.75), # 同单位第二行 → 不认
|
||||
(3, 102, "E", "电", "", "度", 3, 20.0, 0.77, 0.0, 0.77),
|
||||
(4, 102, "G", "镀锌扁钢", "综合", "kg", 3, 5.0, 5.59, 0.0, 5.59),
|
||||
(5, 101, "G", "镀锌扁钢", "综合", "kg", 3, 5.0, 5.59, 0.0, 5.59),
|
||||
(6, 101, "M", "机柜", "", "个", 3, 1.0, 100.0, 0.0, 100.0),
|
||||
(7, 101, "M", "机柜", "42U", "个", 3, 1.0, 100.0, 0.0, 100.0), # 同单位第二行 → 不认
|
||||
(8, 102, "M", "机柜", "24U", "个", 3, 20.0, 100.0, 0.0, 100.0),
|
||||
(9, 101, "P", "型钢", "", "kg", 3, 2.0, None, None, None)]) # 缺价 → 兜底项目级
|
||||
# 项目级:E 是异类价 3.61(报障形态,不得再出现);Z 仅项目级有;P 供缺价兜底
|
||||
c.executemany("""INSERT INTO s_lme_proj(id, session_id, code, name, spec, unit, kind,
|
||||
qty, ntp, taxrate, taxp) VALUES(?,1,?,?,?,?,?,?,?,?,?)""",
|
||||
[(901, "E", "电", "", "度", 3, 999.0, 3.61, 0.0, 0.0),
|
||||
(902, "Z", "支架", "", "kg", 3, 0.0, 9.9, 0.0, 9.9),
|
||||
(903, "P", "型钢", "", "kg", 3, 0.0, 2.0, 0.0, 2.0)])
|
||||
# 现算链:101=3、102=20(E);G 101=5/102=5;M 101=1/102=20;Z 102=10;P 101=2
|
||||
c.executemany("INSERT INTO s_bills(id, session_id, uw_id, Quantity) VALUES(?,1,?,?)",
|
||||
[(1, 101, 1.0), (2, 101, 1.0), (3, 102, 1.0)])
|
||||
c.executemany("INSERT INTO s_norms(id, bill_id, Quantity, Unit) VALUES(?,?,?,NULL)",
|
||||
[(1, 1, 1.0), (2, 2, 1.0), (3, 3, 10.0)])
|
||||
c.executemany("INSERT INTO s_norm_res(norm_id, res_code, qty) VALUES(?,?,?)",
|
||||
[(1, "E", 3.0), (1, "G", 5.0), (1, "M", 1.0), (1, "P", 2.0),
|
||||
(3, "E", 2.0), (3, "G", 0.5), (3, "M", 2.0), (3, "Z", 1.0)])
|
||||
sc.commit()
|
||||
return sc
|
||||
|
||||
|
||||
def _by_code(rows):
|
||||
return {(r[1], r[2], r[3]): r for r in rows}
|
||||
|
||||
|
||||
def test_uw_first_row_and_merge_rules():
|
||||
rows = dyn.dyn_rows(_mk(), 1, None)
|
||||
d = _by_code(rows)
|
||||
# ② 全一致 → 并一行,量=成员单位现算和(101:3 + 102:20),价=单位级 0.77(不是项目级异类 3.61)
|
||||
e = d[("E", "电", "")]
|
||||
assert (e[5], e[6], e[7], e[8]) == (23.0, 0.77, 0.0, 0.77)
|
||||
g = d[("G", "镀锌扁钢", "综合")]
|
||||
assert (g[5], g[6]) == (10.0, 5.59)
|
||||
# ③ 字段不一致 → 各自独立两行(101 认无规格 1、102 是 24U 20)
|
||||
m1 = d[("M", "机柜", "")]
|
||||
m2 = d[("M", "机柜", "24U")]
|
||||
assert m1[5] == 1.0 and m2[5] == 20.0
|
||||
# ④ 兜底:P 单位级行缺价 → 项目级 2.0 补;Z 仅项目级有 → 独立成行(量=现算 10)
|
||||
p = d[("P", "型钢", "")]
|
||||
assert (p[5], p[6]) == (2.0, 2.0)
|
||||
z = d[("Z", "支架", "")]
|
||||
assert (z[5], z[6]) == (10.0, 9.9)
|
||||
# 项目级 E 只有一行(0.75 与 3.61 都不出现在结果里)
|
||||
assert len([r for r in rows if r[1] == "E"]) == 1
|
||||
|
||||
|
||||
def test_uw_view_own_rows():
|
||||
rows = dyn.dyn_uw_rows(_mk(), 1, 101)
|
||||
d = {(r[0], r[1]): r for r in rows}
|
||||
# ①⑤ 本单位每码一行:电认第一行 0.77(0.75 不认)、机柜认无规格;量为本单位现算
|
||||
assert d[("E", "电")][5] == 3.0 and d[("E", "电")][6] == 0.77
|
||||
assert ("M", "机柜") in d and d[("M", "机柜")][5] == 1.0
|
||||
assert d[("P", "型钢")][6] == 2.0 # 缺价兜底
|
||||
assert ("Z", "支架") not in d # 本单位表无行且无现算 → 不出
|
||||
@@ -177,8 +177,8 @@ def test_norm_qty_gcl_formula(server):
|
||||
r = edit("GCL*(5+9.25+6.36)+GCL") # 0.503*20.61 + 0.503 = 10.86983
|
||||
assert r["ok"] is True and abs(r["quantity"] - 10.86983) < 1e-9, r
|
||||
assert row()[0] is None and row()[1] == "GCL*(5+9.25+6.36)+GCL"
|
||||
r = edit("GCL*GCL") # 0.503² = 0.253009
|
||||
assert r["ok"] is True and abs(r["quantity"] - 0.253009) < 1e-9, r
|
||||
r = edit("GCL*GCL") # 决策 216:GCL=清单原值 5.03,结果整体÷10 → 25.3009/10 = 2.53009
|
||||
assert r["ok"] is True and abs(r["quantity"] - 2.53009) < 1e-9, r
|
||||
# 纯字母单位 → GCL=清单工程量
|
||||
con = sqlite3.connect(server["sessdb"])
|
||||
con.execute("UPDATE s_norms SET Unit='t' WHERE id=?", (norm_id,))
|
||||
|
||||
150
CostReview/app/tests/test_version_gate.py
Normal file
150
CostReview/app/tests/test_version_gate.py
Normal file
@@ -0,0 +1,150 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""version_gate 强制更新门禁测试(2026-10-27,《企业和个人版.md》5.9)。
|
||||
|
||||
覆盖:版本比较、开发态旁路、无缓存 fail-open、两段式拦截(GET 页/POST JSON)、
|
||||
缓存落盘回读、拉取失败沿用旧缓存、放行清单、status 形状、非法信息文件拒收。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
SERVER_DIR = os.path.join(os.path.dirname(HERE), "server")
|
||||
if SERVER_DIR not in sys.path:
|
||||
sys.path.insert(0, SERVER_DIR)
|
||||
|
||||
import version_gate as vg # noqa: E402
|
||||
|
||||
|
||||
def make_build(app="1.2.0", url="https://releases.example/prd.json", **kw):
|
||||
return SimpleNamespace(APP_VERSION=app, VERSION_INFO_URL=url, **kw)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fresh(tmp_path):
|
||||
"""每个用例独立 data_dir + 复位全局状态,不起后台线程。"""
|
||||
vg._cache = None
|
||||
vg._cfg.update({"app_version": None, "info_url": None,
|
||||
"interval": vg.DEFAULT_INTERVAL, "data_dir": str(tmp_path)})
|
||||
yield vg
|
||||
vg._cache = None
|
||||
|
||||
|
||||
INFO = {"latest_version": "1.3.0", "min_required_version": "1.2.5",
|
||||
"release_notes": "修复", "package_url": "https://x/pkg.zip", "sha256": "ab"}
|
||||
|
||||
|
||||
def ok_get(url):
|
||||
return dict(INFO)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 版本比较
|
||||
|
||||
def test_vkey():
|
||||
assert vg.vkey("1.2.10") == (1, 2, 10)
|
||||
assert vg.vkey("v1.3") == (1, 3)
|
||||
assert vg.vkey("2.0.0") > vg.vkey("1.9.9")
|
||||
assert vg.vkey("junk") == ()
|
||||
assert vg.vkey(None) == ()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 开发态旁路
|
||||
|
||||
def test_dev_bypass_no_build(tmp_path):
|
||||
vg.init(str(tmp_path), build=None, start_thread=False)
|
||||
assert vg.effective() is False
|
||||
assert vg.intercept("GET", "/admin.html") is None
|
||||
ok, info = vg.check()
|
||||
assert ok and info.get("bypass") == "dev"
|
||||
|
||||
|
||||
def test_dev_bypass_version_dev(tmp_path):
|
||||
vg.init(str(tmp_path), build=make_build(app="dev"), start_thread=False)
|
||||
assert vg.effective() is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- fail-open:无缓存不拦
|
||||
|
||||
def test_no_cache_never_blocks(tmp_path):
|
||||
vg.init(str(tmp_path), build=make_build(app="1.0.0"), start_thread=False)
|
||||
assert vg.intercept("GET", "/admin.html") is None # 从未拉到且无快照 → 不拦
|
||||
|
||||
|
||||
def test_bad_min_required_fail_open(tmp_path):
|
||||
vg.init(str(tmp_path), build=make_build(app="1.0.0"), start_thread=False)
|
||||
vg._save_cache({"latest_version": "9", "min_required_version": "x.y",
|
||||
"fetched_at": "t"}) # 最低要求解析失败
|
||||
assert vg.intercept("GET", "/admin.html") is None # 视为 0,不拦
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 两段式拦截
|
||||
|
||||
def test_forced_blocks_pages_and_api(tmp_path):
|
||||
vg.init(str(tmp_path), build=make_build(app="1.2.0"), start_thread=False)
|
||||
vg.fetch_once(http_get=ok_get) # min_required=1.2.5 > 1.2.0
|
||||
g = vg.intercept("GET", "/admin.html")
|
||||
assert g and g["kind"] == "html" and "升级" in g["text"]
|
||||
p = vg.intercept("POST", "/api/session/bill/op")
|
||||
assert p and p["kind"] == "json" and p["code"] == 403
|
||||
assert p["obj"]["error"]["code"] == "UPDATE_REQUIRED" # API 绝不回 HTML
|
||||
|
||||
|
||||
def test_ok_version_passes(tmp_path):
|
||||
vg.init(str(tmp_path), build=make_build(app="1.3.0"), start_thread=False)
|
||||
vg.fetch_once(http_get=ok_get) # 1.3.0 >= 1.2.5
|
||||
assert vg.intercept("GET", "/admin.html") is None
|
||||
assert vg.intercept("POST", "/api/session/save") is None
|
||||
|
||||
|
||||
def test_always_paths_pass_even_when_forced(tmp_path):
|
||||
vg.init(str(tmp_path), build=make_build(app="1.0.0"), start_thread=False)
|
||||
vg.fetch_once(http_get=ok_get)
|
||||
assert vg.intercept("GET", "/api/license/status") is None
|
||||
assert vg.intercept("GET", "/api/version") is None
|
||||
assert vg.intercept("GET", "/api/version_info") is None
|
||||
assert vg.intercept("POST", "/api/license/activate") is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 拉取与缓存
|
||||
|
||||
def test_fetch_persists_cache(tmp_path):
|
||||
vg.init(str(tmp_path), build=make_build(app="1.3.0"), start_thread=False)
|
||||
assert vg.fetch_once(http_get=ok_get) is True
|
||||
fp = os.path.join(str(tmp_path), vg.CACHE_NAME)
|
||||
d = json.load(open(fp, encoding="utf-8"))
|
||||
assert d["min_required_version"] == "1.2.5" and d["fetched_at"]
|
||||
# 重启(重新 init/load)后缓存仍生效
|
||||
vg._cache = None
|
||||
vg.load_cache()
|
||||
assert vg.status()["min_required"] == "1.2.5"
|
||||
|
||||
|
||||
def test_fetch_failure_keeps_old_cache(tmp_path):
|
||||
vg.init(str(tmp_path), build=make_build(app="1.2.0"), start_thread=False)
|
||||
assert vg.fetch_once(http_get=ok_get) is True
|
||||
def dead(url):
|
||||
raise OSError("断网")
|
||||
assert vg.fetch_once(http_get=dead) is False # 失败静默
|
||||
assert vg.intercept("GET", "/admin.html") is not None # 旧缓存仍判强制
|
||||
|
||||
|
||||
def test_fetch_rejects_malformed_info(tmp_path):
|
||||
vg.init(str(tmp_path), build=make_build(app="1.2.0"), start_thread=False)
|
||||
for bad in ({"latest_version": 3}, {"min_required_version": None}, [1, 2], "x"):
|
||||
assert vg.fetch_once(http_get=lambda u, b=bad: b) is False
|
||||
assert vg._cache is None # 非法信息绝不落缓存
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- status
|
||||
|
||||
def test_status_shape(tmp_path):
|
||||
vg.init(str(tmp_path), build=make_build(app="1.2.8"), start_thread=False)
|
||||
vg.fetch_once(http_get=ok_get)
|
||||
s = vg.status()
|
||||
assert s["current"] == "1.2.8" and s["latest"] == "1.3.0"
|
||||
assert s["min_required"] == "1.2.5" and s["forced"] is False
|
||||
assert s["update_available"] is True # 1.2.8 < 1.3.0 有新版
|
||||
assert s["package_url"] == INFO["package_url"]
|
||||
Reference in New Issue
Block a user