java_contract_parity.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. r"""P12-A:Java 后端迁移的**裁判**——契约端点逐一比对 Java 与 Python 的响应。
  4. 用途(与前端对拍门同思路:门禁当裁判,逐条收敛):
  5. · 读冻契约 `app_backEnd/.../contract/http_api_v1.json`(42 条);
  6. · 对每条端点,分别请求 Python 侧与 Java 侧,做**深度相等**比较(JSON 归一化后);
  7. · 输出计分板:`已一致 / 有差异 / Java 未实现`,并把"必须一致"的端点清单交给 `--require` 用于门禁。
  8. 用法:
  9. python scripts/java_contract_parity.py [--gateway URL] [--python-base /detail] [--java-base /java]
  10. [--require kpi,fleet,...] [--limit N]
  11. """
  12. from __future__ import annotations
  13. import argparse
  14. import json
  15. import pathlib
  16. import sys
  17. import urllib.error
  18. import urllib.request
  19. ROOT = pathlib.Path(__file__).resolve().parents[1]
  20. CONTRACT = ROOT / 'app_backEnd/app_backEnd_guanlan/contract/http_api_v1.json'
  21. def get(url: str, timeout: float = 60.0):
  22. req = urllib.request.Request(url, headers={'Accept': 'application/json'})
  23. try:
  24. with urllib.request.urlopen(req, timeout=timeout) as r:
  25. body = r.read().decode('utf-8', 'replace')
  26. try:
  27. return r.status, json.loads(body)
  28. except Exception:
  29. return r.status, body[:400]
  30. except urllib.error.HTTPError as e:
  31. return e.code, (e.read().decode('utf-8', 'replace')[:200])
  32. except Exception as e: # noqa: BLE001
  33. return 0, f'{type(e).__name__}: {e}'
  34. def norm(x):
  35. """比较用归一化:字典按键排序;列表保序(顺序也是行为)。"""
  36. if isinstance(x, dict):
  37. return {k: norm(v) for k, v in sorted(x.items())}
  38. if isinstance(x, list):
  39. return [norm(v) for v in x]
  40. return x
  41. def first_diff(a, b, path='$', depth=0):
  42. if depth > 6:
  43. return None
  44. if type(a) is not type(b) and not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
  45. return f'{path}: 类型 {type(a).__name__} ≠ {type(b).__name__}'
  46. if isinstance(a, dict):
  47. for k in sorted(set(a) | set(b)):
  48. if k not in a:
  49. return f'{path}.{k}: Java 多键'
  50. if k not in b:
  51. return f'{path}.{k}: Java 缺键'
  52. d = first_diff(a[k], b[k], f'{path}.{k}', depth + 1)
  53. if d:
  54. return d
  55. return None
  56. if isinstance(a, list):
  57. if len(a) != len(b):
  58. return f'{path}: 长度 {len(a)} ≠ {len(b)}'
  59. for i, (x, y) in enumerate(zip(a, b)):
  60. d = first_diff(x, y, f'{path}[{i}]', depth + 1)
  61. if d:
  62. return d
  63. return None
  64. if a != b:
  65. sa, sb = str(a), str(b)
  66. return f'{path}: {sa[:60]!r} ≠ {sb[:60]!r}'
  67. return None
  68. def main() -> int:
  69. ap = argparse.ArgumentParser()
  70. ap.add_argument('--gateway', default='http://127.0.0.1:28084')
  71. ap.add_argument('--python-base', default='/detail')
  72. ap.add_argument('--java-base', default='/java')
  73. ap.add_argument('--require', default='', help='逗号分隔:这些端点必须一致,否则退出码 1')
  74. ap.add_argument('--limit', type=int, default=0)
  75. ap.add_argument('--java-kinds', default='detail_api',
  76. help='哪些 kind 属于 Java 后端迁移范围(默认 detail_api;逗号分隔)')
  77. a = ap.parse_args()
  78. contract = json.loads(CONTRACT.read_text(encoding='utf-8'))
  79. eps = contract['endpoints']
  80. rows = eps if isinstance(eps, list) else [dict(path=k, **(v if isinstance(v, dict) else {})) for k, v in eps.items()]
  81. if a.limit:
  82. rows = rows[:a.limit]
  83. java_kinds = {x.strip() for x in a.java_kinds.split(',') if x.strip()}
  84. same, diff, missing, skipped, other = [], [], [], [], []
  85. scope_total = 0
  86. for e in rows:
  87. path = str(e.get('path') or e.get('url'))
  88. method = str(e.get('method') or 'GET').upper()
  89. kind = str(e.get('kind') or '?')
  90. if kind not in java_kinds:
  91. other.append((path, kind))
  92. continue
  93. scope_total += 1
  94. if method != 'GET':
  95. skipped.append((path, 'POST 类端点本轮不自动比(需构造请求体)'))
  96. continue
  97. # ★ 一律真的问两侧:Java 走 /java 前缀、Python 走 /detail 前缀(灰度期两个并存入口)
  98. jurl = a.gateway.rstrip('/') + a.java_base + path
  99. purl = a.gateway.rstrip('/') + a.python_base + path
  100. js, jb = get(jurl)
  101. ps, pb = get(purl)
  102. # ★只按 HTTP 状态判定(曾按正文里是否有 "404" 判 ⇒ 把"已实现但正文含该字样"的端点误判为未实现)
  103. if js in (0, 404):
  104. missing.append((path, f'Java HTTP {js}'))
  105. continue
  106. if js != 200 or ps != 200:
  107. diff.append((path, f'HTTP Java {js} / Python {ps}'))
  108. continue
  109. d = first_diff(norm(jb), norm(pb))
  110. if d:
  111. diff.append((path, d))
  112. else:
  113. same.append(path)
  114. print('Java ↔ Python 契约端点比对(裁判:冻契约 %d 条;Java 范围 kind=%s 共 %d 条)'
  115. % (len(rows), ','.join(sorted(java_kinds)), scope_total))
  116. print(' 一致 %d/%d · 有差异 %d · 未实现 %d · 跳过 %d(范围外 %d 条:%s)\n'
  117. % (len(same), scope_total, len(diff), len(missing), len(skipped), len(other),
  118. ', '.join(sorted({k for _, k in other})) or '-'))
  119. if same:
  120. print(' [一致] ' + ', '.join(same[:12]) + (' …' if len(same) > 12 else ''))
  121. for p, why in diff[:10]:
  122. print(' [差异] %-28s %s' % (p, why))
  123. for p, why in missing[:10]:
  124. print(' [未实现] %-26s %s' % (p, why))
  125. for p, why in skipped[:6]:
  126. print(' [跳过] %-28s %s' % (p, why))
  127. need = [x.strip() for x in a.require.split(',') if x.strip()]
  128. bad = [p for p in need if p not in same]
  129. if need:
  130. print('\n门禁要求一致 %d 条 → %s' % (len(need), '通过' if not bad else '未通过: ' + ', '.join(bad)))
  131. print('\n结论: %s' % ('Java 范围端点全部一致' if not diff and not missing else
  132. '迁移进行中(%d/%d 已一致)' % (len(same), scope_total)))
  133. return 0 if not bad else 1
  134. if __name__ == '__main__':
  135. raise SystemExit(main())