run_interface_tests_cron.sh 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. #!/usr/bin/env bash
  2. # =============================================================================
  3. # CFC 接口测试闭环(定时任务主体)
  4. # 流程:git pull 最新 -> 检测新增/变更需求 -> 跑冒烟(含回归对比) ->
  5. # 为新增接口补全用例并跑新测试 -> 提交测试结果 -> push 到远端(与开发团队闭环)
  6. #
  7. # 网络说明:测试目标 192.168.16.251 只能在「前台/宿主机」网络可达。
  8. # 本脚本设计为在宿主机用 Windows 任务计划程序每 30 分钟调用,
  9. # 不要在受限沙箱后台运行(后台网络被拦截)。
  10. # =============================================================================
  11. set -uo pipefail
  12. REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  13. cd "$REPO_DIR" || exit 1
  14. BRANCH="${CFC_BRANCH:-feature/ui-token-u5-color-tokens}"
  15. BASE_URL="${CFC_BASE:-http://192.168.16.251}"
  16. HOST_HDR="${CFC_HOST:-cfc.iwintrue.com}"
  17. TIMEOUT="${CFC_TIMEOUT:-3}"
  18. TEST_SCRIPT="ops_interface_smoke.py"
  19. SCANNER="scan_frontend_endpoints.py"
  20. LOG_DIR="$REPO_DIR/logs"
  21. mkdir -p "$LOG_DIR"
  22. TS="$(date +%Y%m%d_%H%M%S)"
  23. RUN_DIR="$LOG_DIR/run_$TS"
  24. mkdir -p "$RUN_DIR"
  25. CUR_TSV="$RUN_DIR/results_$TS.tsv"
  26. ENDPOINTS_CUR="$RUN_DIR/endpoints_$TS.txt"
  27. EXTRA_CASES="$REPO_DIR/interface_test_extra_cases.tsv"
  28. BASELINE_EP="$REPO_DIR/interface_test_baseline_endpoints.txt"
  29. PREV_TSV="$REPO_DIR/interface_test_prev.tsv"
  30. TREND="$REPO_DIR/interface_test_trend.log"
  31. MANAGED="INTERFACE_TEST_REPORT.md interface_test_report.tsv cfc-frontend/INTERFACE_TEST_MATRIX.md ops_interface_smoke.py"
  32. log() { echo "[$(date +%H:%M:%S)] $*" | tee -a "$LOG_DIR/interface_cron.log"; }
  33. log "===== CFC 接口测试闭环 开始 $TS ====="
  34. log "REPO=$REPO_DIR BRANCH=$BRANCH BASE=$BASE_URL HOST=$HOST_HDR"
  35. # ---------------------------------------------------------------------------
  36. # 1) 拉取远端最新(含开发团队的修复/新需求)
  37. # 仅丢弃我们生成的报告类文件本地改动(每次都会重新生成),其余未提交改动用
  38. # --autostash 处理,避免破坏用户其他在途工作。
  39. # ---------------------------------------------------------------------------
  40. git checkout -- INTERFACE_TEST_REPORT.md interface_test_report.tsv cfc-frontend/INTERFACE_TEST_MATRIX.md 2>/dev/null
  41. if git pull --rebase --autostash origin "$BRANCH" >>"$LOG_DIR/interface_cron.log" 2>&1; then
  42. log "git pull 成功"
  43. else
  44. log "git pull 失败(可能本地有冲突或凭证问题),用当前代码继续"
  45. fi
  46. # ---------------------------------------------------------------------------
  47. # 2) 检测新增/变更需求(前端接口面变化)
  48. # ---------------------------------------------------------------------------
  49. python "$SCANNER" --out "$ENDPOINTS_CUR" 2>/dev/null
  50. NEWEP=""; RMVEP=""
  51. if [ -f "$BASELINE_EP" ]; then
  52. NEWEP=$(comm -13 <(sort "$BASELINE_EP") <(sort "$ENDPOINTS_CUR"))
  53. RMVEP=$(comm -23 <(sort "$BASELINE_EP") <(sort "$ENDPOINTS_CUR"))
  54. n_new=$(echo "$NEWEP" | grep -c . || true)
  55. n_rmv=$(echo "$RMVEP" | grep -c . || true)
  56. log "接口面变化:新增 $n_new 个,移除 $n_rmv 个"
  57. if [ "$n_new" -gt 0 ]; then
  58. : > "$EXTRA_CASES"
  59. while IFS= read -r line; do
  60. [ -z "$line" ] && continue
  61. m=$(echo "$line" | awk '{print $1}')
  62. p=$(echo "$line" | awk '{print $2}')
  63. printf 'auto\tauto\t%s\t%s\tfalse\tfalse\n' "$m" "$p" >> "$EXTRA_CASES"
  64. done <<< "$NEWEP"
  65. log "已为新增接口生成补全用例 -> $EXTRA_CASES"
  66. fi
  67. else
  68. log "首次运行:建立接口基线(不触发补全)"
  69. fi
  70. cp "$ENDPOINTS_CUR" "$BASELINE_EP"
  71. # ---------------------------------------------------------------------------
  72. # 3) 跑冒烟测试(前台调用,含登录态;新增接口通过 --extra 一并测试)
  73. # ---------------------------------------------------------------------------
  74. EXTRA_FLAG=""
  75. [ -s "$EXTRA_CASES" ] && EXTRA_FLAG="--extra $EXTRA_CASES"
  76. log "开始执行冒烟测试 $EXTRA_FLAG"
  77. python "$TEST_SCRIPT" --base "$BASE_URL" --host "$HOST_HDR" \
  78. --timeout "$TIMEOUT" --auto-login --authed $EXTRA_FLAG \
  79. --report "$CUR_TSV" > "$RUN_DIR/smoke_stdout.txt" 2>&1
  80. log "冒烟测试完成,结果 -> $CUR_TSV"
  81. # ---------------------------------------------------------------------------
  82. # 4) 汇总 + 回归对比 + 生成报告
  83. # ---------------------------------------------------------------------------
  84. python - "$CUR_TSV" "$PREV_TSV" "$RUN_DIR/report_$TS.md" "$TS" "$TREND" <<'PY'
  85. import sys, collections
  86. cur_tsv, prev_tsv, rpt, ts, trend = sys.argv[1:6]
  87. def load(path):
  88. d = {}
  89. try:
  90. with open(path, encoding='utf-8') as f:
  91. next(f, None)
  92. for line in f:
  93. c = line.rstrip('\n').split('\t')
  94. if len(c) < 7: continue
  95. page, fn, method, path, http, biz, cat = c
  96. d[(method, path)] = (page, fn, http, biz, cat)
  97. except FileNotFoundError:
  98. pass
  99. return d
  100. cur = load(cur_tsv)
  101. prev = load(prev_tsv) if prev_tsv and os.path.exists(prev_tsv) else {}
  102. cats = collections.Counter(v[4] for v in cur.values())
  103. total = len(cur)
  104. ok = cats.get('BIZ_OK', 0)
  105. rate = ok * 100 // total if total else 0
  106. # 回归对比
  107. fixed = [] # 之前非 OK -> 现在 OK
  108. regressed = [] # 之前 OK -> 现在非 OK
  109. for k, v in cur.items():
  110. cat = v[4]
  111. if k in prev:
  112. pcat = prev[k][4]
  113. if pcat != 'BIZ_OK' and cat == 'BIZ_OK':
  114. fixed.append((k, pcat, cat))
  115. elif pcat == 'BIZ_OK' and cat != 'BIZ_OK':
  116. regressed.append((k, pcat, cat))
  117. def top(cat, n=20):
  118. return [(k[0], k[1], v[3], v[4]) for k, v in cur.items() if v[4] == cat][:n]
  119. lines = []
  120. lines.append(f"# CFC 接口冒烟测试报告 ({ts})\n")
  121. lines.append(f"- 目标: {os.environ.get('CFC_HOST', 'cfc.iwintrue.com')} 用例总数: **{total}**")
  122. lines.append(f"- 业务成功率(BIZ_OK): **{ok}/{total} = {rate}%**\n")
  123. lines.append("## 分类汇总")
  124. for k in ('BIZ_OK','BIZ_FAIL','NOT_FOUND','SERVER_ERR','NON_JSON','CONN_ERR'):
  125. if cats.get(k): lines.append(f"- {k}: {cats[k]}")
  126. lines.append("")
  127. if fixed:
  128. lines.append(f"## ✅ 回归修复({len(fixed)} 个,之前失败现已通过)")
  129. for (m,p),pc,_ in fixed[:30]:
  130. lines.append(f"- `{m} {p}` (原 {pc})")
  131. lines.append("")
  132. if regressed:
  133. lines.append(f"## ⚠️ 回归劣化({len(regressed)} 个,之前通过现失败)")
  134. for (m,p),_,c in regressed[:30]:
  135. lines.append(f"- `{m} {p}` (现 {c})")
  136. lines.append("")
  137. lines.append(f"## 需开发团队关注的契约缺口 (NOT_FOUND={cats.get('NOT_FOUND',0)})")
  138. for m,p,b,c in top('NOT_FOUND'):
  139. lines.append(f"- `{m} {p}` (biz={b}, {c})")
  140. lines.append("")
  141. lines.append(f"## 健壮性风险 (SERVER_ERR={cats.get('SERVER_ERR',0)})")
  142. for m,p,b,c in top('SERVER_ERR'):
  143. lines.append(f"- `{m} {p}` (http={b}, {c})")
  144. lines.append("")
  145. lines.append("> 说明:冒烟为空体请求,部分 500/400 属预期(缺必填参数)。NOT_FOUND 与回归劣化才需优先处理。")
  146. report = "\n".join(lines) + "\n"
  147. with open(rpt, 'w', encoding='utf-8') as f:
  148. f.write(report)
  149. # 趋势日志
  150. with open(trend, 'a', encoding='utf-8') as f:
  151. f.write(f"{ts}\ttotal={total}\tBIZ_OK={ok}\trate={rate}%\t"
  152. f"fixed={len(fixed)}\tregressed={len(regressed)}\t"
  153. f"NOT_FOUND={cats.get('NOT_FOUND',0)}\tSERVER_ERR={cats.get('SERVER_ERR',0)}\n")
  154. print(report)
  155. print(f"\n[趋势] 已写入 {trend}")
  156. PY
  157. # ---------------------------------------------------------------------------
  158. # 5) 提交测试结果 + 补全用例
  159. # ---------------------------------------------------------------------------
  160. git add -f ops_interface_smoke.py
  161. git add INTERFACE_TEST_REPORT.md interface_test_report.tsv cfc-frontend/INTERFACE_TEST_MATRIX.md "$EXTRA_CASES" 2>/dev/null
  162. if git diff --cached --quiet; then
  163. log "无测试结果变更,跳过提交"
  164. else
  165. git commit -m "test(interface): 接口冒烟闭环 $(date '+%Y-%m-%d %H:%M') — 通过率 ${rate:-?}% (fix=$(echo $fixed|wc -l) reg=$(echo $regressed|wc -l))" \
  166. >>"$LOG_DIR/interface_cron.log" 2>&1 && log "已提交测试结果"
  167. fi
  168. # ---------------------------------------------------------------------------
  169. # 6) 推送远端,与开发团队形成闭环
  170. # ---------------------------------------------------------------------------
  171. if git push origin "$BRANCH" >>"$LOG_DIR/interface_cron.log" 2>&1; then
  172. log "git push 成功 — 测试闭环已同步远端"
  173. else
  174. log "git push 失败(凭证/网络),下次运行将重试"
  175. fi
  176. # 更新回归基线
  177. cp "$CUR_TSV" "$PREV_TSV"
  178. log "===== 本轮结束 ====="