Преглед изворни кода

test(ai.aiyunyi.videoPage): S-cfc-456 TDD-RED 契约单测(实现未落地,预期 14 红)

Agnes Agent пре 6 часа
родитељ
комит
659cdfab7f
1 измењених фајлова са 359 додато и 0 уклоњено
  1. 359 0
      cfc-frontend/__tests__/aiyunyi/aiyunyi.videoPage.contract.test.js

+ 359 - 0
cfc-frontend/__tests__/aiyunyi/aiyunyi.videoPage.contract.test.js

@@ -0,0 +1,359 @@
+/**
+ * 契约级单测(TDD-RED)——能力键 ai.aiyunyi.videoPage(任务 S-cfc-456)
+ *
+ * 溯源:
+ *   需求:docs/2026-11-24-爱云医AI检测接入方案.md
+ *         §4.2(新增 pages/health/ai-video-detect.vue:<web-view> 内嵌爱云医视频检测 H5 页,
+ *               URL 取 getPath 返回的 path;pages.json 注册新增页面路由)、
+ *         §8「前端验收」第 3 条(视频类型:进入 web-view 内嵌页;返回后可看到报告)、
+ *         §7 R7(视频检测依赖爱云医 H5 页,小程序 web-view 需域名白名单;
+ *                getPath 返回域名需加入业务域名,若受限则前端降级为「在浏览器打开」提示)。
+ *   设计:同上 §3.4 视频路径(inspectionType 1/2 → getPath 取 data.path → <web-view src={path}>
+ *         内嵌采集 → 完成后回小程序拉报告)、§4.5(错误归一/降级)、附录 A.5
+ *         (GET /detection/package/getPath:detectionPackageItemId、detectionReportUserId 均必填,
+ *          响应 data.path 为 H5 URL);§3.1 安全硬约束(前端只调本系统 /api/aiyunyi/** 代理,
+ *          不直连爱云医、不接触 AppKey/私钥)。
+ *
+ * 说明(沿用 cfc-frontend/__tests__/family-join/join-form.required-info.test.js 与同批
+ *   aiyunyi.detectPage.contract.test.js 的「加载真实 SFC 源码」约定):
+ *   jest 配置为 node 环境、无 vue-jest 组件挂载;本文件直接读取真实
+ *   pages/health/ai-video-detect.vue 与 utils/api.js 源码——
+ *     - <script>:把 import 语句替换为注入桩后求值,得到真实组件的 data()/methods 做行为级断言;
+ *     - <template>:读取模板文本做结构契约断言(<web-view :src>、降级提示)。
+ *   GREEN 阶段按本文件锚定的契约落地实现后断言应可翻绿;当前实现未落地 → 预期 RED。
+ *   本文件只新增 __tests__ 下的测试,不修改 pages/、utils/、pages.json 任何业务代码。
+ */
+
+import fs from 'fs'
+import path from 'path'
+
+// __tests__/aiyunyi → ../.. = cfc-frontend
+const ROOT = path.join(__dirname, '../..')
+const VIDEO_PAGE_PATH = path.join(ROOT, 'pages/health/ai-video-detect.vue')
+const API_PATH = path.join(ROOT, 'utils/api.js')
+const PAGES_JSON_PATH = path.join(ROOT, 'pages.json')
+
+const H5_PATH = 'https://devadmin.aicds.com.cn/video-detect/index.html?token=contract-test'
+const ITEM_ID = 101
+const REPORT_USER_ID = 202
+
+// ---------------------------------------------------------------------------
+// 工具:加载真实 SFC(行为级 <script> + 结构级 <template>),风格对齐 family-join
+// ---------------------------------------------------------------------------
+
+/** 把 ES import 改为从 globalThis[stubKey] 取桩(不解析模块,避免污染业务实现) */
+function stubImports(script, moduleStubs, stubKey) {
+  globalThis[stubKey] = moduleStubs
+  return script.replace(/import\s+([^;]+?)\s+from\s+['"]([^'"]+)['"];?/g, function (m, clause, id) {
+    var names = []
+    var c = clause.trim()
+    var braceIdx = c.indexOf('{')
+    if (braceIdx >= 0) {
+      var def = c.slice(0, braceIdx).replace(/,\s*$/, '').trim()
+      if (def) names.push(def)
+      var named = c.slice(braceIdx + 1, c.lastIndexOf('}'))
+      named.split(',').forEach(function (part) {
+        var p = part.trim()
+        if (!p) return
+        var parts = p.split(/\s+as\s+/)
+        var local = parts.length > 1 ? parts[1].trim() : parts[0].trim()
+        if (local) names.push(local)
+      })
+    } else if (c.indexOf('*') === 0) {
+      var nsMatch = c.match(/\*\s+as\s+(\w+)/)
+      if (nsMatch) names.push(nsMatch[1])
+    } else {
+      names.push(c)
+    }
+    return names.map(function (n) {
+      return 'var ' + n + ' = (globalThis[' + JSON.stringify(stubKey) + '][' + JSON.stringify(id) + '] || {})[' + JSON.stringify(n) + '];'
+    }).join('\n')
+  })
+}
+
+/** 通用 SFC 加载器:文件缺失时抛明确错误(GREEN 未交付的 RED 信号) */
+function loadVideoPage(moduleStubs) {
+  if (!fs.existsSync(VIDEO_PAGE_PATH)) {
+    throw new Error('实现未落地(GREEN 未交付),找不到 SFC:' + VIDEO_PAGE_PATH)
+  }
+  var src = fs.readFileSync(VIDEO_PAGE_PATH, 'utf8')
+  var tmplMatch = src.match(/<template>([\s\S]*?)<\/template>/)
+  var scriptMatch = src.match(/<script>([\s\S]*?)<\/script>/)
+  if (!scriptMatch) throw new Error('无法定位 <script> 块:' + VIDEO_PAGE_PATH)
+  var script = stubImports(scriptMatch[1], moduleStubs, '__aiyunyiVideoPageStubs')
+  script = script.replace(/export default\s*\{/, 'module.exports = {')
+  var mod = { exports: {} }
+  // eslint-disable-next-line no-new-func
+  new Function('module', 'exports', script)(mod, mod.exports)
+  return { component: mod.exports, template: tmplMatch ? tmplMatch[1] : '', source: src }
+}
+
+/** 模拟 Vue 合并 data 与 methods 到实例 */
+function instantiate(component) {
+  var vm = {}
+  var data = typeof component.data === 'function' ? component.data.call(vm) : (component.data || {})
+  Object.keys(data).forEach(function (k) { vm[k] = data[k] })
+  var methods = component.methods || {}
+  Object.keys(methods).forEach(function (k) { vm[k] = methods[k] })
+  return vm
+}
+
+/** 容忍 GREEN 阶段对 H5 URL 字段的命名差异(webViewUrl / h5Url / path 等) */
+function urlKeys(vm) {
+  return ['webViewUrl', 'webviewUrl', 'h5Url', 'videoUrl', 'detectUrl', 'path', 'src']
+}
+function readUrl(vm) {
+  var keys = urlKeys(vm)
+  for (var i = 0; i < keys.length; i++) {
+    if (typeof vm[keys[i]] === 'string' && vm[keys[i]]) return vm[keys[i]]
+  }
+  return ''
+}
+function boundUrlKey(template) {
+  var m = template.match(/<web-view[^>]*?\s:src\s*=\s*["']([A-Za-z_$][\w$]*)["']/)
+  return m ? m[1] : ''
+}
+async function flush() {
+  await Promise.resolve()
+  await Promise.resolve()
+  await Promise.resolve()
+}
+function messagesShown() {
+  var msgs = []
+  global.uni.showToast.mock.calls.forEach(function (c) { msgs.push((c[0] && c[0].title) || '') })
+  global.uni.showModal.mock.calls.forEach(function (c) { msgs.push(JSON.stringify(c[0] || {})) })
+  return msgs.join(' ')
+}
+function callMentionsIds(call) {
+  var text = JSON.stringify(call)
+  return text.indexOf(String(ITEM_ID)) >= 0 && text.indexOf(String(REPORT_USER_ID)) >= 0
+}
+
+// ---------------------------------------------------------------------------
+// 测试夹具:api.js 用 Proxy 容纳 GREEN 阶段任意命名(aiyunyi.getPath / aiyunyiGetPath / 平铺)
+// ---------------------------------------------------------------------------
+
+var stubs
+
+function buildStubs() {
+  var apiSpy = jest.fn(function () {
+    return Promise.resolve({ code: 200, message: 'ok', data: { path: H5_PATH } })
+  })
+  var apiModule = new Proxy({}, {
+    get: function (target, prop) {
+      if (prop === '__spy') return apiSpy
+      if (typeof prop === 'symbol') return undefined
+      if (/member|family/i.test(String(prop))) {
+        return jest.fn(function () { return Promise.resolve({ code: 200, data: [] }) })
+      }
+      return apiSpy
+    }
+  })
+  return {
+    apiSpy: apiSpy,
+    moduleStubs: {
+      '@/utils/api.js': apiModule,
+      '../../utils/api.js': apiModule,
+      '@/utils/image-picker.js': { pickImage: jest.fn() },
+      '@/mixins/font-scale.js': {
+        fontScaleMixin: { data: function () { return { fontScale: 1 } }, onShow: function () {} }
+      }
+    }
+  }
+}
+
+beforeEach(function () {
+  global.uni._storage = {}
+  ;['showToast', 'showModal', 'showLoading', 'hideLoading', 'navigateTo', 'redirectTo',
+    'setClipboardData', 'request'].forEach(function (k) {
+    if (global.uni[k] && global.uni[k].mockReset) global.uni[k].mockReset()
+  })
+  if (!global.uni.setClipboardData) global.uni.setClipboardData = jest.fn()
+  stubs = buildStubs()
+  globalThis.__aiyunyiVideoPageStubs = stubs.moduleStubs
+  jest.useFakeTimers()
+})
+
+afterEach(function () {
+  jest.useRealTimers()
+  delete globalThis.__aiyunyiVideoPageStubs
+})
+
+// ===========================================================================
+// AC-R0 视频页文件存在性(§4.2 改动清单:新增 ai-video-detect.vue)——主 RED 信号
+// ===========================================================================
+
+describe('AC-R0 视频检测页文件存在性契约', function () {
+  it('pages/health/ai-video-detect.vue 必须存在(§4.2)', function () {
+    expect(fs.existsSync(VIDEO_PAGE_PATH)).toBe(true)
+  })
+})
+
+// ===========================================================================
+// AC-R1 <template> 结构:<web-view> 动态绑定 getPath 返回的 H5 URL(§4.2)
+// ===========================================================================
+
+describe('AC-R1 web-view 内嵌结构契约', function () {
+  it('模板包含 <web-view> 且以 :src 动态绑定(不得写死 URL)', function () {
+    var template = loadVideoPage(stubs.moduleStubs).template
+    expect(template).toMatch(/<web-view[^>]*\s:src\s*=/)
+  })
+
+  it(':src 绑定的字段必须由脚本 data 提供(getPath 返回的 path)', function () {
+    var sfc = loadVideoPage(stubs.moduleStubs)
+    var vm = instantiate(sfc.component)
+    var key = boundUrlKey(sfc.template)
+    expect(key).not.toBe('')
+    expect(vm[key]).toBeDefined()
+  })
+})
+
+// ===========================================================================
+// AC-R2 utils/api.js 暴露 aiyunyi.getPath 封装(§4.2 / §A.5 / §3.1 代理约束)
+// ===========================================================================
+
+describe('AC-R2 utils/api.js getPath 封装契约', function () {
+  var apiSrc
+
+  beforeAll(function () {
+    apiSrc = fs.readFileSync(API_PATH, 'utf8')
+  })
+
+  it('存在 getPath 封装(aiyunyi.getPath / aiyunyiGetPath / 平铺导出)', function () {
+    var hasWrapper = /aiyunyi\s*[.:]\s*[\s\S]{0,800}?getPath/i.test(apiSrc)
+      || /aiyunyiGetPath/i.test(apiSrc)
+      || /export\s+(?:const|function)\s+getPath\b/.test(apiSrc)
+    expect(hasWrapper).toBe(true)
+  })
+
+  it('getPath 封装走 /api/aiyunyi/ 代理且透传两个必填 ID(§A.5)', function () {
+    var proxyIdx = apiSrc.indexOf('/api/aiyunyi/')
+    var getPathIdx = apiSrc.toLowerCase().indexOf('getpath')
+    expect(proxyIdx).toBeGreaterThanOrEqual(0)
+    expect(getPathIdx).toBeGreaterThanOrEqual(0)
+    var start = Math.max(0, Math.min(proxyIdx, getPathIdx) - 400)
+    var end = Math.min(apiSrc.length, Math.max(proxyIdx, getPathIdx) + 800)
+    var block = apiSrc.slice(start, end)
+    expect(block).toMatch(/detectionPackageItemId/)
+    expect(block).toMatch(/detectionReportUserId/)
+  })
+})
+
+// ===========================================================================
+// AC-R3 <script> 行为:onLoad 调 getPath 并用 data.path 渲染 web-view(§3.4 第 8/9 步)
+// ===========================================================================
+
+describe('AC-R3 getPath 取路径行为契约', function () {
+  it('onLoad 调用 getPath,并把返回的 data.path 写入 H5 URL 字段', async function () {
+    var vm = instantiate(loadVideoPage(stubs.moduleStubs).component)
+    expect(typeof vm.onLoad).toBe('function')
+    await vm.onLoad({ detectionPackageItemId: ITEM_ID, detectionReportUserId: REPORT_USER_ID })
+    await flush()
+    expect(stubs.apiSpy).toHaveBeenCalled()
+    expect(readUrl(vm)).toBe(H5_PATH)
+  })
+
+  it('detectionPackageItemId 与 detectionReportUserId 同时透传,不交换/不丢弃(§A.5)', async function () {
+    var vm = instantiate(loadVideoPage(stubs.moduleStubs).component)
+    await vm.onLoad({ detectionPackageItemId: ITEM_ID, detectionReportUserId: REPORT_USER_ID })
+    await flush()
+    expect(stubs.apiSpy.mock.calls.length).toBeGreaterThan(0)
+    expect(stubs.apiSpy.mock.calls.some(callMentionsIds)).toBe(true)
+  })
+})
+
+// ===========================================================================
+// AC-R4 R7 降级:域名白名单受限/getPath 失败时提示「在浏览器打开」,不白屏(§7 R7 / §4.5)
+// ===========================================================================
+
+describe('AC-R7 域名白名单降级契约', function () {
+  it('getPath 失败时给出「在浏览器打开」提示,不白屏、不崩溃', async function () {
+    stubs.apiSpy.mockReset()
+    stubs.apiSpy.mockImplementation(function () { return Promise.reject(new Error('network error')) })
+    var vm = instantiate(loadVideoPage(stubs.moduleStubs).component)
+    expect(typeof vm.onLoad).toBe('function')
+    await vm.onLoad({ detectionPackageItemId: ITEM_ID, detectionReportUserId: REPORT_USER_ID })
+    await flush()
+    expect(messagesShown()).toMatch(/浏览器打开/)
+  })
+
+  it('提供降级打开方法(复制 URL / 系统浏览器打开 H5 链接)', function () {
+    var vm = instantiate(loadVideoPage(stubs.moduleStubs).component)
+    var names = ['openInBrowser', 'openBrowser', 'fallbackOpen', 'openH5InBrowser']
+    expect(names.some(function (n) { return typeof vm[n] === 'function' })).toBe(true)
+    var src = fs.readFileSync(VIDEO_PAGE_PATH, 'utf8')
+    expect(/setClipboardData|plus\.runtime\.openURL|window\.open/.test(src)).toBe(true)
+  })
+
+  it('模板包含降级文案(web-view 受限时用户仍可看到提示)', function () {
+    var template = loadVideoPage(stubs.moduleStubs).template
+    expect(template).toMatch(/浏览器打开/)
+  })
+})
+
+// ===========================================================================
+// AC-R5 返回后可看到报告(§8 前端验收第 3 条 / §3.4 第 10/11 步)
+// ===========================================================================
+
+describe('AC-R5 从 web-view 返回后报告可见契约', function () {
+  it('onShow 触发报告状态查询或跳转报告页(首次进入跳过、返回时刷新)', async function () {
+    var vm = instantiate(loadVideoPage(stubs.moduleStubs).component)
+    expect(typeof vm.onLoad).toBe('function')
+    expect(typeof vm.onShow).toBe('function')
+    await vm.onLoad({ detectionPackageItemId: ITEM_ID, detectionReportUserId: REPORT_USER_ID })
+    await flush()
+    stubs.apiSpy.mockClear()
+    global.uni.navigateTo.mockClear()
+    global.uni.redirectTo.mockClear()
+
+    // 首次进入 onShow 可能被 _onLoadFired 跳过;返回时触发——连续两次覆盖两种实现
+    await vm.onShow()
+    await vm.onShow()
+    await flush()
+
+    var nav = (global.uni.navigateTo.mock.calls.concat(global.uni.redirectTo.mock.calls))
+      .map(function (c) { return (c[0] && c[0].url) || '' }).join(' ')
+    expect(stubs.apiSpy.mock.calls.length > 0 || /report/i.test(nav)).toBe(true)
+  })
+
+  it('页面脚本或模板引用报告详情/报告数据(返回后展示报告)', function () {
+    var sfc = loadVideoPage(stubs.moduleStubs)
+    expect(/ai-report-detail|report-detail|报告/.test(sfc.source + sfc.template)).toBe(true)
+  })
+})
+
+// ===========================================================================
+// AC-R6 页面路由注册(§4.2:pages.json 注册新增页面)
+// ===========================================================================
+
+describe('AC-R6 pages.json 视频页路由契约', function () {
+  it('注册 ai-video-detect 路由', function () {
+    var pagesJson = JSON.parse(fs.readFileSync(PAGES_JSON_PATH, 'utf8'))
+    var paths = []
+    ;(pagesJson.pages || []).forEach(function (p) { paths.push(p.path) })
+    ;(pagesJson.subPackages || []).forEach(function (sp) {
+      ;(sp.pages || []).forEach(function (p) { paths.push((sp.root ? sp.root + '/' : '') + p.path) })
+    })
+    expect(paths.some(function (p) { return /(^|\/)ai-video-detect$/.test(p) })).toBe(true)
+  })
+})
+
+// ===========================================================================
+// AC-R8 安全约束:不直连爱云医、不持有签名材料(§3.1)
+// ===========================================================================
+
+describe('AC-R8 前端不直连爱云医/不持有鉴权材料契约', function () {
+  it('视频页源码不得出现爱云医域名或 AppKey/RSA 私钥/签名材料', function () {
+    var src = loadVideoPage(stubs.moduleStubs).source
+    expect(/aicds\.com\.cn|X-App-Key|X-Api-Sign|rsaPrivateKey|rsa-private-key|SHA256withRSA/.test(src)).toBe(false)
+  })
+})
+
+// ===========================================================================
+// 权限流:本能力为 web-view 承载页,鉴权由统一 Bearer Token / 后端代理收口,
+// 无独立角色门禁分支,属《编排派发》中「权限(适用时)」的不适用项,显式记录。
+// ===========================================================================
+
+describe.skip('权限流:ai.aiyunyi.videoPage 无独立角色门禁,不适用', function () {
+  it('占位:鉴权经后端代理 + 统一 Bearer Token,无 role 分支(详见汇报)', function () {})
+})