sleep-config-sc-c26.spec.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. /**
  2. * SC-C-26 睡眠打卡「正常」选项由后台配置驱动 · 正常/异常/权限三流 e2e spec
  3. * =====================================================================
  4. * 能力键:sleep.config.tags(sc-key-map SC-C-26;SC-A-27 同键运营侧)
  5. * 目标:孩子/不能登录视角——「正常」选项由后台配置驱动。
  6. *
  7. * 真实契约来源(2026-12-06 远程 cfc.iwintrue.com 忽略型探针 _probe_sc_c26.spec.js 实跑,
  8. * 探针文件被 tests/e2e/api/.gitignore 的 _probe_*.spec.js 规则忽略,不入库):
  9. * N 正常:
  10. * - /api/admin/config/list(admin token)→ code 200,含
  11. * {configKey:"sleep.config.tags", configValue:'["正常",...9项]'}(探针实测 id=8768)。
  12. * - /api/health/sleep/create(家长代管不能登录孩子)remark="正常" → code 200,
  13. * data.remark="正常";/list 可读回同 remark。
  14. * - 多选按前端 buildRemark() 以「,」拼接("正常,入睡困难")整体落 remark。
  15. * E 异常:
  16. * - /api/config/public/value 缺 key / key="" / key=" " → HTTP 200 {code:500,"message":"key is required"}
  17. * (B-37 已收紧 trim 判空)。
  18. * - 非法 JSON body → HTTP 200 {code:400,"message":"请求参数格式错误,请检查请求体 JSON 或字段类型"}。
  19. * - /api/admin/config/update 缺 configKey → HTTP 200 {code:400,"message":"数据不完整或格式错误:…"}(NOT NULL 兜底,无写入)。
  20. * - /api/health/sleep/create 缺 sleepTime → HTTP 200 {code:500,"message":"请选择入睡时间"}
  21. * (业务错误码承载在 HTTP 200,非裸 HTTP 500)。
  22. * P 权限:
  23. * - 同家庭能登录家长(parent A)代管不能登录孩子(/api/family/member/list 返回 memberType="local"):
  24. * A 读孩子睡眠记录 → 200(允许路径)。
  25. * - 匿名 /api/health/sleep/list → 实测 200 且返回记录(应为 401,鉴权缺口)。
  26. * - 匿名 /api/health/sleep/create(不传 memberId)→ 实测业务 500 "memberId不能为空"(应为 401)。
  27. * - 跨家庭 parent B 读/写 A 家孩子睡眠记录 → 实测均 200(读返回数据、写成功 id=35,应为 401/403)→ G-304-1。
  28. * - 非 admin parent 调 /api/admin/config/list → 实测 200 全量配置(应为 403)→ G-304-1/D-A27-2。
  29. * - 匿名 /api/admin/config/list → 401 {"code":401,"message":"请先登录"}(已强制登录)。
  30. *
  31. * 已知 blocker(承袭·真实缺陷未修,不造绿、不写放水断言):
  32. * - C-26/G-07 契约缺口:cfc-frontend/pages/growth/sleep-checkin.vue 的 quickTags 仍硬编码 8 项且无「正常」,
  33. * 未拉取 /api/config/public/value;专用端点 /api/health/sleep/tags、/api/admin/sleep/tags 不存在;
  34. * sleep_record 无 tags 列(标签拼进 remark)。→ TC-C26-N5 / TC-C26-E6 以 fixme 占位。
  35. * - D-A27-1 缓存层故障(环境):/api/config/public/value 与 /api/admin/config/all、/update(@Cacheable/@CacheEvict)
  36. * 实测 {code:500,"message":"服务器内部错误"};恢复后 TC-C26-N2 自动实跑转绿(skip 门禁)。
  37. * - G-304-1 越权:权限流 P1/P2/P3/P4 以 test.fail 钉住,修复后 Playwright 报「unexpected pass」强制转正。
  38. * - B-260-1(privacy.html 404):探针 GET /web/privacy.html → 404,与本 SC 无功能耦合,仅如实标注,不造绿。
  39. *
  40. * 写库纪律:本 spec 只创建测试家庭/成员/睡眠记录(与既有 e2e 同口径);不写 sys_config,
  41. * 不做跨家庭写(跨家庭写越权仅以探针证据记录,避免每轮污染他人孩子数据)。
  42. *
  43. * 运行:cd /sc-data/cfc && npx playwright test sleep-config-sc-c26 -c tests/playwright.config.api.js --project=desktop
  44. */
  45. const { test, expect } = require('@playwright/test');
  46. const API = process.env.CFC_API_BASE || 'http://cfc.iwintrue.com';
  47. const ADMIN_PHONE = process.env.ADMIN_PHONE || '13800138000';
  48. const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'admin123';
  49. const SLEEP_TAGS_KEY = 'sleep.config.tags';
  50. const CANONICAL_TAGS = ['正常', '入睡困难', '夜醒', '多梦', '打鼾', '早醒', '赖床', '熬夜', '午睡过长'];
  51. function randPhone() {
  52. return '13' + String(Math.floor(Math.random() * 900000000) + 100000000);
  53. }
  54. function sleep(ms) {
  55. return new Promise(function (resolve) { setTimeout(resolve, ms); });
  56. }
  57. /**
  58. * 远程网关 502 抖动(openresty 后端节点偶发不可用)有限重试;
  59. * 仅对 502/503/504 重试,其余响应原样返回,不掩盖真实业务码。
  60. */
  61. async function postWithRetry(request, path, body, token) {
  62. const headers = { 'Content-Type': 'application/json' };
  63. if (token) headers.Authorization = 'Bearer ' + token;
  64. let res = null;
  65. for (let i = 0; i < 6; i++) {
  66. try {
  67. res = await request.post(API + path, {
  68. data: body || {},
  69. headers: headers,
  70. timeout: 120000,
  71. failOnStatusCode: false,
  72. });
  73. if (res.status() !== 502 && res.status() !== 503 && res.status() !== 504) break;
  74. } catch (e) {
  75. res = null;
  76. }
  77. await sleep(5000);
  78. }
  79. if (!res) return { status: 0, code: 0, message: 'REQUEST_ERROR', data: null };
  80. const text = await res.text().catch(function () { return ''; });
  81. let json = null;
  82. try { json = text ? JSON.parse(text) : null; } catch (e) { json = null; }
  83. if (!json || typeof json !== 'object') {
  84. return { status: res.status(), code: res.status(), message: 'NON_JSON_RESPONSE', data: null };
  85. }
  86. return { status: res.status(), code: json.code, message: json.message, data: json.data };
  87. }
  88. function uniqueSuffix() {
  89. return String(Date.now()).slice(-8) + String(Math.floor(Math.random() * 1000));
  90. }
  91. async function registerParent(request) {
  92. const res = await postWithRetry(request, '/api/auth/direct-register', {
  93. phone: randPhone(), role: 'parent', nickname: 'QA-C26-' + uniqueSuffix(),
  94. });
  95. expect(res.code, 'direct-register 应成功: ' + res.message).toBe(200);
  96. expect(res.data && res.data.token, 'direct-register 应返回 token').toBeTruthy();
  97. return res.data;
  98. }
  99. /** 创建「不能登录用户」(同家庭家长代管;VO memberType=local)并返回成员行 */
  100. async function createManagedChild(request, parent) {
  101. const list = await postWithRetry(request, '/api/family/member/list', {}, parent.token);
  102. expect(list.code, 'member/list: ' + list.message).toBe(200);
  103. const rows = Array.isArray(list.data) ? list.data : [];
  104. const self = rows.find(function (m) { return String(m.userId) === String(parent.userId); });
  105. expect(self, 'member/list 应包含登录家长本人').toBeTruthy();
  106. const added = await postWithRetry(request, '/api/family/member/add', {
  107. relativeMemberId: self.id,
  108. generationLevel: 'child',
  109. nickname: 'C26-' + uniqueSuffix(),
  110. gender: 'female',
  111. birthday: '2016-07-01',
  112. }, parent.token);
  113. expect(added.code, 'member/add: ' + added.message).toBe(200);
  114. const childId = added.data && added.data.id;
  115. expect(childId, 'member/add 应返回孩子成员 id').toBeTruthy();
  116. const list2 = await postWithRetry(request, '/api/family/member/list', {}, parent.token);
  117. const child = (Array.isArray(list2.data) ? list2.data : []).find(function (m) {
  118. return String(m.id) === String(childId);
  119. });
  120. expect(child, 'member/list 应包含新建孩子').toBeTruthy();
  121. expect(child.memberType, '不能登录用户 VO 口径应为 local(同家庭能登录用户代管)').toBe('local');
  122. return child;
  123. }
  124. let adminToken = null;
  125. async function loginAdmin(request) {
  126. if (adminToken) return adminToken;
  127. const res = await postWithRetry(request, '/api/admin-auth/login-by-password', {
  128. phone: ADMIN_PHONE, password: ADMIN_PASSWORD,
  129. });
  130. if (res.code === 200 && res.data && res.data.token) {
  131. adminToken = res.data.token;
  132. return adminToken;
  133. }
  134. return null;
  135. }
  136. /** D-A27-1 门禁:/api/config/public/value 的 @Cacheable 路径是否因缓存层故障 500 */
  137. async function publicValueBroken(request) {
  138. const res = await postWithRetry(request, '/api/config/public/value', { key: SLEEP_TAGS_KEY });
  139. return res.code === 500 && String(res.message || '').indexOf('服务器内部错误') !== -1;
  140. }
  141. function expectDenied(res, label) {
  142. expect([401, 403], label + ' 应被拒绝(401/403),实际 http=' + res.status + ' code=' + res.code).toContain(res.status);
  143. expect(res.data, label + ' 拒绝时不得返回业务数据').toBeNull();
  144. }
  145. test.describe('SC-C-26 睡眠「正常」选项配置驱动(sleep.config.tags)三流', () => {
  146. // ═════════════════════════ 正常流 ═════════════════════════
  147. test.describe('正常流', () => {
  148. test('TC-C26-N1 正常流: 后台配置含「正常」项(配置源 /api/admin/config/list 可读)', async ({ request }) => {
  149. const token = await loginAdmin(request);
  150. test.skip(!token, '管理端凭据不可用(ADMIN_PHONE/ADMIN_PASSWORD 未配置或账号变更)');
  151. const list = await postWithRetry(request, '/api/admin/config/list', {}, token);
  152. expect(list.code, '/api/admin/config/list: ' + list.message).toBe(200);
  153. const row = (Array.isArray(list.data) ? list.data : []).find(function (x) {
  154. return x && x.configKey === SLEEP_TAGS_KEY;
  155. });
  156. expect(row, '后台应已配置 ' + SLEEP_TAGS_KEY).toBeTruthy();
  157. let tags = null;
  158. try { tags = JSON.parse(row.configValue); } catch (e) { tags = null; }
  159. expect(Array.isArray(tags), '配置值应为 JSON 数组,实际: ' + row.configValue).toBe(true);
  160. expect(tags, '后台配置应含「正常」项').toContain('正常');
  161. CANONICAL_TAGS.forEach(function (t) {
  162. expect(tags, '后台配置应含规范项「' + t + '」').toContain(t);
  163. });
  164. });
  165. test('TC-C26-N2 正常流: 前端同步读 /api/config/public/value 与后台配置一致(D-A27-1 门禁)', async ({ request }) => {
  166. const token = await loginAdmin(request);
  167. test.skip(!token, '管理端凭据不可用');
  168. test.skip(
  169. await publicValueBroken(request),
  170. 'D-A27-1 承袭(远程 sysConfig 缓存层故障,public/value 的 @Cacheable 实测 500「服务器内部错误」;环境恢复后本用例自动实跑转绿,2026-12-06 探针)'
  171. );
  172. const list = await postWithRetry(request, '/api/admin/config/list', {}, token);
  173. const row = (Array.isArray(list.data) ? list.data : []).find(function (x) {
  174. return x && x.configKey === SLEEP_TAGS_KEY;
  175. });
  176. const expected = row ? row.configValue : null;
  177. const pv = await postWithRetry(request, '/api/config/public/value', { key: SLEEP_TAGS_KEY });
  178. expect(pv.code, '同步读应成功: ' + pv.message).toBe(200);
  179. expect(pv.data, '小程序端读到的标签配置应与后台一致').toBe(expected);
  180. });
  181. test('TC-C26-N3 正常流: 选中「正常」可提交成功并落库(remark)', async ({ request }) => {
  182. const parent = await registerParent(request);
  183. const child = await createManagedChild(request, parent);
  184. const remark = '正常';
  185. const created = await postWithRetry(request, '/api/health/sleep/create', {
  186. memberId: child.id, sleepTime: '22:30', wakeTime: '07:00',
  187. durationMinutes: 510, qualityScore: 8, remark: remark,
  188. }, parent.token);
  189. expect(created.code, 'create: ' + created.message).toBe(200);
  190. expect(created.data && created.data.remark, '创建响应应回显 remark').toBe(remark);
  191. const list = await postWithRetry(request, '/api/health/sleep/list', { memberId: child.id }, parent.token);
  192. expect(list.code, 'list: ' + list.message).toBe(200);
  193. const hit = (Array.isArray(list.data) ? list.data : []).filter(function (r) {
  194. return r && r.remark === remark;
  195. });
  196. expect(hit.length, '列表应能读回 remark=「正常」的记录').toBeGreaterThanOrEqual(1);
  197. });
  198. test('TC-C26-N4 正常流: 「正常」+「入睡困难」多选按「,」拼接落 remark', async ({ request }) => {
  199. const parent = await registerParent(request);
  200. const child = await createManagedChild(request, parent);
  201. const remark = '正常,入睡困难';
  202. const created = await postWithRetry(request, '/api/health/sleep/create', {
  203. memberId: child.id, sleepTime: '23:10', wakeTime: '06:50',
  204. durationMinutes: 460, qualityScore: 6, remark: remark,
  205. }, parent.token);
  206. expect(created.code, 'create: ' + created.message).toBe(200);
  207. const list = await postWithRetry(request, '/api/health/sleep/list', { memberId: child.id }, parent.token);
  208. const hit = (Array.isArray(list.data) ? list.data : []).filter(function (r) {
  209. return r && r.remark === remark;
  210. });
  211. expect(hit.length, '多选拼接文本应原样落 remark').toBeGreaterThanOrEqual(1);
  212. });
  213. // 承袭缺口:前端未接配置、无「正常」项;API 级环境无前端 SPA,无法做 DOM 渲染断言
  214. test.fixme('TC-C26-N5 承袭缺口 C-26/G-07: 前端按后台配置渲染「正常」选项且可选', async () => {
  215. // 缺口现状(2026-12-06 源码核对 cfc-frontend/pages/growth/sleep-checkin.vue):
  216. // quickTags 硬编码 8 项 ['入睡困难','夜醒','多梦','打鼾','早醒','赖床','熬夜','午睡过长'],无「正常」;
  217. // 页面未调用 /api/config/public/value,后台增删改不影响小程序端列表。
  218. // 转绿条件:小程序端改为拉取 sleep.config.tags(含「正常」)并渲染为可选项后,
  219. // 以 Playwright frontend-mobile 项目对真实页面断言(本用例删除 fixme 改为严格断言)。
  220. });
  221. });
  222. // ═════════════════════════ 异常流 ═════════════════════════
  223. test.describe('异常流', () => {
  224. test('TC-C26-E1 异常流: 公开读缺 key → 可读提示 "key is required"(非裸 500)', async ({ request }) => {
  225. const res = await postWithRetry(request, '/api/config/public/value', {});
  226. expect(res.status, '公开路径匿名可达,业务码承载拒绝(不得裸 HTTP 500)').toBe(200);
  227. expect(res.code).toBe(500);
  228. expect(res.message).toBe('key is required');
  229. });
  230. test('TC-C26-E2 异常流: 纯空白 key 被拒(B-37 trim 判空)', async ({ request }) => {
  231. const res = await postWithRetry(request, '/api/config/public/value', { key: ' ' });
  232. expect(res.status).toBe(200);
  233. expect(res.code, '空白 key 必须与空串同口径拒绝').toBe(500);
  234. expect(res.message).toBe('key is required');
  235. });
  236. test('TC-C26-E3 异常流: 非法 JSON body → 400 请求参数格式错误(GlobalExceptionHandler)', async ({ request }) => {
  237. const r = await request.post(API + '/api/config/public/value', {
  238. data: '{"key":',
  239. headers: { 'Content-Type': 'application/json' },
  240. timeout: 120000,
  241. failOnStatusCode: false,
  242. });
  243. const body = await r.json().catch(function () { return {}; });
  244. expect(r.status(), '业务码承载在 HTTP 200').toBe(200);
  245. expect(body.code, 'HttpMessageNotReadableException 统一映射 400').toBe(400);
  246. expect(String(body.message || '')).toContain('请求参数格式错误');
  247. });
  248. test('TC-C26-E4 异常流: admin 缺 configKey 的 update 被 400 拒绝且无写入(NOT NULL 兜底)', async ({ request }) => {
  249. const token = await loginAdmin(request);
  250. test.skip(!token, '管理端凭据不可用');
  251. const res = await postWithRetry(request, '/api/admin/config/update', {}, token);
  252. expect(res.status, '业务码承载在 HTTP 200').toBe(200);
  253. expect(res.code, 'sys_config.config_key NOT NULL → DataIntegrityViolation → 400').toBe(400);
  254. expect(String(res.message || '')).toContain('数据不完整或格式错误');
  255. });
  256. test('TC-C26-E5 异常流: 缺 sleepTime → HTTP 200 + 业务 500 "请选择入睡时间"(非裸 500)', async ({ request }) => {
  257. const parent = await registerParent(request);
  258. const child = await createManagedChild(request, parent);
  259. const res = await postWithRetry(request, '/api/health/sleep/create', {
  260. memberId: child.id, wakeTime: '07:00',
  261. }, parent.token);
  262. expect(res.status, '校验失败不得返回裸 HTTP 500').toBe(200);
  263. expect(res.code).toBe(500);
  264. expect(res.message).toBe('请选择入睡时间');
  265. expect(res.data).toBeNull();
  266. });
  267. // 承袭缺口:前端无配置解析/回退逻辑,API 级环境亦无前端 SPA 可做白屏断言
  268. test.fixme('TC-C26-E6 承袭缺口 C-26/G-07: 配置为空/非法 JSON 时前端回退默认 9 项且不白屏', async () => {
  269. // 缺口现状(2026-12-06 源码核对):
  270. // sleep-checkin.vue 未拉取配置,故不存在「空数组/非法 JSON → 回退默认 9 项」的解析与兜底分支;
  271. // 后端 /api/config/public/value 亦不校验 value 语义(原样返回 sys_config 字符串,探针实证)。
  272. // 另:探针实测 sleepTime="25:99" 被 java.sql.Time.valueOf 宽容滚动为 02:39 并落库(真实缺陷),
  273. // 为避免每轮写入脏记录,本 spec 不 pin 写路径,仅在此如实标注。
  274. // 转绿条件:前端实现配置解析 + 非法值回退默认 9 项(含「正常」)后,以页面级用例替代本 fixme。
  275. });
  276. });
  277. // ═════════════════════════ 权限流 ═════════════════════════
  278. test.describe('权限流(不能登录用户由同家庭能登录用户代管)', () => {
  279. test('TC-C26-P0 权限流: 同家庭能登录家长可读写不能登录孩子(memberType=local)的睡眠数据', async ({ request }) => {
  280. const parent = await registerParent(request);
  281. const child = await createManagedChild(request, parent);
  282. const created = await postWithRetry(request, '/api/health/sleep/create', {
  283. memberId: child.id, sleepTime: '21:30', wakeTime: '06:30', qualityScore: 7, remark: '代管',
  284. }, parent.token);
  285. expect(created.code, '同家庭代管写应允许: ' + created.message).toBe(200);
  286. const list = await postWithRetry(request, '/api/health/sleep/list', { memberId: child.id }, parent.token);
  287. expect(list.code, '同家庭代管读应允许: ' + list.message).toBe(200);
  288. expect(Array.isArray(list.data)).toBe(true);
  289. expect(list.data.length).toBeGreaterThanOrEqual(1);
  290. });
  291. test('TC-C26-P1 权限流: 匿名 /api/admin/config/list 被 401 拒绝(已强制登录)', async ({ request }) => {
  292. const res = await postWithRetry(request, '/api/admin/config/list', {});
  293. expect(res.status, '匿名应被 JwtInterceptor 拦在路由前').toBe(401);
  294. expect(res.code).toBe(401);
  295. expect(String(res.message || '')).toContain('请先登录');
  296. expect(res.data).toBeNull();
  297. });
  298. test.fail('TC-C26-P2 权限流(承袭缺陷·鉴权缺口): 匿名 /api/health/sleep/list 应 401,实测 200 泄露', async ({ request }) => {
  299. // 探针实测:匿名(不携带 Authorization)POST /api/health/sleep/list {memberId:20123}
  300. // → HTTP 200 {code:200,data:[…睡眠记录…]};根因 /api/health/sleep/** 未纳入
  301. // JwtInterceptor.LOGIN_REQUIRED_PATHS(对照兄弟 /api/health/checkin/ 已在列)。
  302. const res = await postWithRetry(request, '/api/health/sleep/list', { memberId: 1 });
  303. expect(res.status, '睡眠记录属成员私有健康数据,匿名必须 401').toBe(401);
  304. });
  305. test.fail('TC-C26-P3 权限流(承袭缺陷·鉴权缺口): 匿名 /api/health/sleep/create 应 401,实测业务 500 放行', async ({ request }) => {
  306. // 探针实测:匿名 create 携带 memberId 时直接写入成功(id=34);
  307. // 本用例不传 memberId,避免每轮写入,仅钉鉴权门:实测 HTTP 200 {code:500,"message":"memberId不能为空"}。
  308. const res = await postWithRetry(request, '/api/health/sleep/create', { sleepTime: '22:00', wakeTime: '07:00' });
  309. expect(res.status, '匿名写入口必须在拦截器层 401,不得进入业务校验').toBe(401);
  310. });
  311. test.fail('TC-C26-P4 权限流(承袭缺陷 G-304-1): 跨家庭家长读他人孩子睡眠记录应 403,实测 200', async ({ request }) => {
  312. const parentA = await registerParent(request);
  313. const childA = await createManagedChild(request, parentA);
  314. await postWithRetry(request, '/api/health/sleep/create', {
  315. memberId: childA.id, sleepTime: '22:10', wakeTime: '07:10', qualityScore: 6, remark: '跨家庭读探针',
  316. }, parentA.token);
  317. const parentB = await registerParent(request);
  318. const res = await postWithRetry(request, '/api/health/sleep/list', { memberId: childA.id }, parentB.token);
  319. expectDenied(res, '跨家庭读他人孩子睡眠记录');
  320. });
  321. test.fail('TC-C26-P5 权限流(承袭缺陷 G-304-1/D-A27-2): 非 admin 家长调 /api/admin/config/list 应 403,实测 200', async ({ request }) => {
  322. const parent = await registerParent(request);
  323. const res = await postWithRetry(request, '/api/admin/config/list', {}, parent.token);
  324. expectDenied(res, '非 admin 调配置中心');
  325. });
  326. });
  327. });