-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend.test.ts
More file actions
1922 lines (1767 loc) · 95.8 KB
/
Copy pathbackend.test.ts
File metadata and controls
1922 lines (1767 loc) · 95.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { afterEach, describe, expect, it, vi } from "vitest";
import { createApi, createTeamBackend, type Backend, type EvidenceSummary, type RecommendationResult } from "./backend";
import { KioBridgeError, getSheet, registerSheet } from "./client";
import type { OrderSheet } from "@/domain/types";
import { 알레르기설정 } from "@/api/allergy";
import { 사람식별자 } from "@/api/person";
// 백엔드가 아직 없으므로, 명세서대로 응답하는 가짜를 만들어 조립이 맞는지 본다.
// 이 테스트가 통과한다는 건 "백엔드가 명세대로 주면 화면이 돈다" 는 뜻이다.
const 후보표시 = {
"candidate-alpha": { displayName: "매운 순살 닭강정", priceText: "6,000원" },
"candidate-beta": { displayName: "매운 뼈 닭강정", priceText: "5,500원" },
};
const 기본추천 = (over: Partial<RecommendationResult> = {}): RecommendationResult => ({
scoredAxes: [],
unmetConditions: [],
recommendedCandidateId: "candidate-alpha",
alternativeCandidateIds: [],
excludedCandidates: [],
recommendationReasons: ["포장하기를 고르셔서 포장이 되는 메뉴만 남겼어요"],
confidence: 0.95,
requiresReconfirmation: false,
display: 후보표시,
matchedOptions: [{ label: "맵기", value: "매운맛", matched: true }],
...over,
});
function 가짜백엔드(over: Partial<Backend> = {}, rec = 기본추천()): Backend {
return {
createSession: async () => ({ sessionId: "s1", kioskName: "OO분식 1번", expiresAt: Date.now() + 60000 }),
filterCandidates: async () => ({
survivingCandidateIds: ["candidate-alpha", "candidate-beta"],
excluded: [{ candidateId: "candidate-gamma", reasonCode: "ALLERGEN_CONFLICT", explanation: "땅콩 알레르기를 알려주셔서 땅콩 토핑 닭강정은 뺐어요" }],
}),
recommend: async () => rec,
submit: async () => {},
validate: async () => ({ valid: true }),
execute: async () => ({ planId: "pln_1" }),
getEvidence: async (): Promise<EvidenceSummary> => ({ state: "cart_ready", reachedStep: 5, cart: { itemCountText: "1개", totalText: "6,000원", evidenceLabel: "화면 인식으로 확인됨", handoff: "장바구니를 확인해 주세요" } }),
...over,
};
}
const 매핑 = async (b: Backend) => {
const api = createApi(b);
await api.claimPairing("kb");
return api.requestMapping("s1", "p1");
};
describe("후보 필터와 추천을 합쳐 한 응답으로 만든다", () => {
it("맞추지 못한 조건을 버리지 않는다", async () => {
/*
* 서버가 "선호하신 뼈/순살과 다릅니다" 라고 알려 주는데 타입에 선언만 해
* 두고 화면까지 오지 않았다. 못 맞춘 것을 감추면 사용자는 자기가 고른
* 조건이 다 반영된 줄 알고 승인한다.
*/
const r = await 매핑(가짜백엔드({}, 기본추천({
unmetConditions: ["선호하신 뼈/순살과 다릅니다."],
})));
const 못맞춘 = (r.reasons ?? []).filter((x) => x.kind === "unmet");
expect(못맞춘.map((x) => x.text)).toEqual(["선호하신 뼈/순살과 다릅니다."]);
// 제외와 섞이면 안 된다. 저건 '메뉴를 뺐다' 이고 이건 '조건을 못 맞췄다' 다.
expect((r.reasons ?? []).filter((x) => x.kind === "excluded").map((x) => x.text))
.not.toContain("선호하신 뼈/순살과 다릅니다.");
});
it("맞추지 못한 조건에도 거르기가 걸린다", async () => {
/*
* 서버가 준 문장이라 validationMessages 와 같은 종류다. 한쪽만 막으면 안 된다.
*
* 금지 문자열을 여기서 만들지 않는다. 조각내는 것도 생성 경로가 남는다.
* 거르기가 실제로 걸리는지는 금지어 목록에 이미 있는 '결재' 로도 똑같이
* 확인된다 - 오타로 들어온 경우까지 막으려고 목록에 넣어 둔 값이다.
*/
const r = await 매핑(가짜백엔드({}, 기본추천({
unmetConditions: ["결재 수단이 맞지 않습니다.", "선호하신 맵기와 다릅니다."],
})));
expect((r.reasons ?? []).filter((x) => x.kind === "unmet").map((x) => x.text))
.toEqual(["선호하신 맵기와 다릅니다."]);
});
it("제외 사유가 두 곳에서 모두 올라온다", async () => {
const r = await 매핑(가짜백엔드());
const 문구 = (r.reasons ?? []).map((x) => x.text).join("\n");
expect(문구).toContain("포장하기를 고르셔서"); // recommendations
expect(문구).toContain("땅콩 알레르기를 알려주셔서"); // candidate-filters
});
it("추천이 없으면 not_found 다", async () => {
const r = await 매핑(가짜백엔드({}, 기본추천({ recommendedCandidateId: null })));
expect(r.result).toBe("not_found");
});
it("보여 줄 수 있는 후보가 하나도 없으면 clarification 을 만들지 않는다", async () => {
// display 가 비면 이름 없는 후보라 걸러진다. 다 걸러지고도 clarification 을
// 내보내면 화면은 "비슷한 메뉴가 여러 개예요" 라고 말하면서 고를 것을 하나도
// 못 보여 준다. 승인은 후보 선택을 요구하는데 고를 방법이 없으니 갇힌다.
const r = await 매핑(가짜백엔드({}, 기본추천({
alternativeCandidateIds: ["candidate-beta"],
requiresReconfirmation: true,
display: {},
})));
expect(r.result).toBe("not_found");
expect(r.candidates).toBeUndefined();
});
it("확신도가 낮으면 재확인을 요구한다", async () => {
// 심사 필수 기준: 신뢰도 낮을 때 사용자 재확인 수행.
const r = await 매핑(가짜백엔드({}, 기본추천({ confidence: 0.4 })));
expect(r.result).toBe("low_confidence");
});
it("못 맞춘 옵션이 있으면 changed 로 알린다", async () => {
const r = await 매핑(가짜백엔드({}, 기본추천({
matchedOptions: [{ label: "컵", value: "종이컵", matched: false, note: "오늘은 제공되지 않아요" }],
})));
expect(r.result).toBe("changed");
expect(r.item?.options[0].matched).toBe(false);
});
});
describe("후보별 불일치는 서버가 알려 준 것만 쓴다", () => {
const 애매 = (over = {}) => 기본추천({
alternativeCandidateIds: ["candidate-beta"], requiresReconfirmation: true, ...over,
});
it("서버가 알려 주면 표식 순서에 맞춰 실어 준다", async () => {
const r = await 매핑(가짜백엔드({}, 애매({
unmatchedLabelsByCandidate: { "candidate-beta": ["형태"] },
})));
expect(r.candidates?.find((c) => c.candidateId === "c1")?.unmatchedLabels).toBeUndefined();
expect(r.candidates?.find((c) => c.candidateId === "c2")?.unmatchedLabels).toEqual(["형태"]);
// 상품 ID 는 여전히 새어 나가지 않는다.
expect(JSON.stringify(r.candidates)).not.toContain("candidate-");
});
it("서버가 안 알려 주면 비워 둔다 — 짐작하지 않는다", async () => {
// matchedOptions 는 1순위 하나에 대한 답이라 대안 후보에는 쓸 수 없다.
// 그걸 돌려 쓰면 '매운 뼈' 를 고른 사람에게 "형태: 순살, 그대로예요" 라고 말하게 된다.
const r = await 매핑(가짜백엔드({}, 애매({
matchedOptions: [{ label: "형태", value: "순살", matched: false, note: "없어요" }],
})));
for (const c of r.candidates ?? []) {
expect(c.unmatchedLabels).toBeUndefined();
}
// 저장한 조건은 그대로 보여 준다. 서버가 준 matched 도 그대로 쓴다.
// 예전에는 전부 true 로 덮었는데, 그러면 안 맞는 축이 있다는 사실이
// 어느 후보를 고르든 사라진다.
expect(r.sheetOptions?.map((o) => o.label)).toEqual(["형태"]);
expect(r.sheetOptions?.[0].matched).toBe(false);
});
});
describe("상품 ID 를 화면으로 내보내지 않는다", () => {
it("후보 표식은 c1·c2 형태다", async () => {
const r = await 매핑(가짜백엔드({}, 기본추천({
alternativeCandidateIds: ["candidate-beta"], requiresReconfirmation: true,
})));
expect(r.result).toBe("clarification");
expect(r.candidates?.map((c) => c.candidateId)).toEqual(["c1", "c2"]);
expect(JSON.stringify(r.candidates)).not.toContain("candidate-");
});
it("우리가 주지 않은 표식은 거절한다", async () => {
// 예전에는 숫자로 바꾸기만 해서 c99 는 undefined 를 제출하고
// cabc·c0 는 조용히 1순위로 되돌아갔다. 고르지 않은 메뉴가 담긴다.
const submit = vi.fn(async () => {});
const b = 가짜백엔드({ submit }, 기본추천({ alternativeCandidateIds: ["candidate-beta"], requiresReconfirmation: true }));
const api = createApi(b);
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
for (const 가짜 of ["c99", "cabc", "c0"]) {
await expect(
api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "clarification", candidateId: 가짜 }),
).rejects.toThrow();
}
expect(submit).not.toHaveBeenCalled();
});
it("어떤 결과 종류에서도 상품 ID 가 응답 전체에 섞이지 않는다", async () => {
// 후보 목록만 보면 부족하다. reasons·item·sheetOptions·message 어디로든
// 새어 나갈 수 있다. 응답 전체를 문자열로 만들어 잠근다.
//
// 상품 ID 는 서버가 정하는 값이라 접두어 하나만 막으면 다음 환경에서 뚫린다.
// 가짜 백엔드가 쓰는 모든 후보 ID 를 그대로 금지어로 쓴다.
const 후보ID = ["candidate-alpha", "candidate-beta", "candidate-gamma"];
const 경우 = [
기본추천(),
기본추천({ alternativeCandidateIds: ["candidate-beta"], requiresReconfirmation: true }),
기본추천({ confidence: 0.4 }),
기본추천({ matchedOptions: [{ label: "컵", value: "종이컵", matched: false }] }),
기본추천({ recommendedCandidateId: null }),
];
for (const rec of 경우) {
const r = await 매핑(가짜백엔드({}, rec));
const s = JSON.stringify(r);
for (const id of 후보ID) expect(s).not.toContain(id);
}
});
it("사용자가 고른 표식을 서버가 아는 후보로 되돌려 보낸다", async () => {
const submit = vi.fn(async () => {});
const b = 가짜백엔드({ submit }, 기본추천({ alternativeCandidateIds: ["candidate-beta"], requiresReconfirmation: true }));
const api = createApi(b);
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
await api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "clarification", candidateId: "c2" });
expect(submit).toHaveBeenCalledWith("s1", expect.objectContaining({ candidateId: "candidate-beta" }));
});
});
describe("일회용 연결 (팀 #108)", () => {
it("정보 지우기 뒤에는 다 쓴 연결 목록도 남지 않는다", () => {
/*
* pairingId 는 키오스크를 움직일 수 있는 열쇠다. '모두 지워요' 를 누른 뒤에도
* 이 계층이 그 값들을 들고 있으면 화면이 한 말이 사실이 아니게 된다.
*
* 같은 pairingId 를 다시 받아 승인이 되는지로 본다 — 목의 createSession 은
* 늘 "s1" 을 주므로, 안 지워졌으면 두 번째 승인이 CLAIM_EXPIRED 로 막힌다.
*/
const execute = vi.fn(async () => ({ planId: "pln_1" }));
const api = createApi(가짜백엔드({ execute }));
return (async () => {
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
await api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" });
await api.forgetAll();
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
await api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" });
expect(execute).toHaveBeenCalledTimes(2);
})();
});
it("승인이 개발자 오류로 터져도 사람 말로 바꿔 올린다", async () => {
/*
* 화면은 잡은 것을 KioBridgeError 로 보고 e.message 를 그대로 띄운다
* (App.tsx 의 approve). 그물을 빠져나온 것이 fetch 의 TypeError 면
* "Failed to fetch" 가 어르신 화면에 뜬다.
*/
const api = createApi(가짜백엔드({ submit: async () => { throw new TypeError("Failed to fetch"); } }));
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
const e = await api
.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" })
.then(() => null, (err: unknown) => err);
expect(e).toBeInstanceOf(KioBridgeError);
expect((e as KioBridgeError).message).not.toContain("Failed to fetch");
expect((e as KioBridgeError).recoverable).toBe(false);
});
it("한 번 쓴 연결로 다시 승인하면 QR 부터 다시 찍으라고 한다", async () => {
// 이 연결은 서버가 이미 소모했다. 되돌려 두면 사용자는 눌러도 안 되는
// 버튼을 계속 누른다.
const api = createApi(가짜백엔드());
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
await api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" });
const e = await api
.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" })
.then(() => null, (err: KioBridgeError) => err);
expect(e?.code).toBe("CLAIM_EXPIRED");
});
it("취소한 뒤 다른 주문표를 고르면 매핑에서 먼저 막는다 (팀 #146)", async () => {
/*
* 서버는 거절도 승인과 같은 경로로 처리해 pairing 을 폐기한다. 그래서
* 취소하고 나온 뒤 다른 주문표로 들어가면 죽은 값으로 bind 를 시도하고,
* 서버의 PAIRING_NOT_FOUND 가 "연결 정보를 찾을 수 없습니다" 라는
* 개발자 말로 화면에 그대로 떴다.
*
* 승인 경로에는 이 검사가 있었는데 매핑 경로에는 없었다. 화면은 매핑부터
* 부르므로, 정작 사용자가 먼저 닿는 쪽이 안 막혀 있었다.
*/
const api = createApi(가짜백엔드());
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
await api.reject({ pairingId: "s1", sheetId: "p1" });
const e = await api
.requestMapping("s1", "p2")
.then(() => null, (err: KioBridgeError) => err);
expect(e?.code).toBe("CLAIM_EXPIRED");
// 되돌릴 수 있는 오류여야 화면이 'QR 다시 찍기' 로 안내한다.
expect(e?.recoverable).toBe(true);
// 개발자 말이 새어 나가면 안 된다.
expect(e?.message).not.toContain("PAIRING_NOT_FOUND");
expect(e?.message).toContain("QR");
});
it("취소하지 않았으면 다른 주문표로 계속 갈 수 있다", async () => {
// 위 시험이 '언제나 막는다' 로 헛통과하지 않게 지킨다. 연결이 살아 있는
// 동안 주문표를 바꿔 보는 것은 정상 흐름이다.
const api = createApi(가짜백엔드());
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
await expect(api.requestMapping("s1", "p2")).resolves.toBeTruthy();
});
});
describe("주문 입력을 pairing 에 고정하지 못하면 승인까지 가지 않는다 (팀 #108)", () => {
const 이주문표: OrderSheet = { id: "p1", menuName: "닭강정", place: "음식점", selections: {}, memo: "" };
const 차림 = (bindPairing: Backend["bindPairing"]) => {
const execute = vi.fn(async () => ({ planId: "pln_1" }));
const b = 가짜백엔드({ bindPairing, execute });
return { execute, api: createApi(b, "chicken-store", () => 이주문표) };
};
it("고정이 실패하면 매핑이 거기서 멈춘다", async () => {
/*
* 삼키면 안 되는 이유가 이것이다.
*
* 고정 안 된 연결은 승인에서 서버가 PAIRING_INPUT_NOT_BOUND 로 막고
* (PairingRegistry.reserveForExecution), 승인이 한 번 실패하면 그 연결은
* 끝난 것이 된다. 삼키면 사용자는 추천을 다 읽고 승인을 누른 뒤에야
* "QR 을 다시 찍으세요" 를 듣는다 — 되돌릴 수 없는 자리에서 처음 안다.
*
* 여기서 멈추면 연결은 아직 살아 있어서, 다시 시도가 실제로 통한다.
*/
const { api } = 차림(async () => { throw new Error("network"); });
await api.claimPairing("kb");
await expect(api.requestMapping("s1", "p1")).rejects.toThrow();
});
it("고정에 실패한 연결로는 승인이 나가지 않는다", async () => {
const { api, execute } = 차림(async () => { throw new Error("network"); });
await api.claimPairing("kb");
await api.requestMapping("s1", "p1").catch(() => {});
// 매핑 캐시를 지워 두었으므로 승인은 '메뉴를 먼저 찾아야 해요' 에서 막힌다.
await expect(
api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" }),
).rejects.toThrow();
expect(execute).not.toHaveBeenCalled();
});
it("고정에 성공하면 평소대로 승인까지 간다", async () => {
// 위 두 개가 '항상 막힌다' 로 통과해 버리면 아무것도 지키지 못한다.
const { api, execute } = 차림(async () => {});
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
await api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" });
expect(execute).toHaveBeenCalled();
});
it("화면이 주문표를 안 들고 있어도 고정은 시도한다", async () => {
/*
* getSheet 이 없는 것은 **서버가 주문표를 id 로 찾아 주는** 구현이라는 뜻이다
* (createApi 의 getSheet 주석: 그렇게 되면 이 인자는 빼면 된다). 그 구현은
* 화면이 주문표를 안 들고 있어도 pairing 을 고정할 수 있다.
*
* 여기서 건너뛰면 그 백엔드는 매핑을 다 해 놓고 고정만 안 된 채로 승인에
* 들어간다. 무엇이 필요한지는 각 bindPairing 이 스스로 보고, 못 하면 던진다.
*/
const bindPairing = vi.fn(async () => {});
const api = createApi(가짜백엔드({ bindPairing }));
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
// 열쇠는 sheetId 다. 바로 위 filterCandidates·recommend 가 쓰는 값과 같다.
expect(bindPairing).toHaveBeenCalledWith({ pairingId: "s1", profileId: "p1" });
});
it("주문표를 안 들고 있을 때도 고정에 실패하면 매핑이 멈춘다", async () => {
const execute = vi.fn(async () => ({ planId: "pln_1" }));
const api = createApi(가짜백엔드({ execute, bindPairing: async () => { throw new Error("network"); } }));
await api.claimPairing("kb");
await expect(api.requestMapping("s1", "p1")).rejects.toThrow();
await expect(
api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" }),
).rejects.toThrow();
expect(execute).not.toHaveBeenCalled();
});
it("bindPairing 이 없는 옛 백엔드는 그냥 지나간다", async () => {
// 목(mockApi)과 #108 이전 서버에는 이 경로가 없다. 없다고 멈추면 안 된다.
const { api, execute } = 차림(undefined);
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
await api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" });
expect(execute).toHaveBeenCalled();
});
});
describe("승인은 제출 → 검증 → 실행 순서를 지킨다", () => {
it("세 단계가 이 순서로 불린다", async () => {
const 순서: string[] = [];
const b = 가짜백엔드({
submit: async () => { 순서.push("submit"); },
validate: async () => { 순서.push("validate"); return { valid: true }; },
execute: async () => { 순서.push("execute"); return { planId: "pln_1" }; },
});
const api = createApi(b);
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
await api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" });
expect(순서).toEqual(["submit", "validate", "execute"]);
});
it("검증에 실패하면 실행하지 않고 사유를 올린다", async () => {
const execute = vi.fn(async () => ({ planId: "pln_1" }));
const b = 가짜백엔드({ validate: async () => ({ valid: false, errors: ["결제 action 이 포함되어 있어요"] }), execute });
const api = createApi(b);
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
await expect(
api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" }),
).rejects.toThrow("결제 action");
expect(execute).not.toHaveBeenCalled();
});
it("사유가 여러 줄이면 전부 화면까지 올라간다", async () => {
// Error 는 message 한 칸뿐이라 예전에는 첫 줄만 닿고 나머지가 사라졌다.
// 하나를 고쳐도 또 막히는데 왜 막히는지 끝까지 알 수 없었다.
const 사유 = ["필수 정보가 빠졌습니다.", "선택하신 값이 지원되지 않는 옵션입니다."];
const b = 가짜백엔드({ validate: async () => ({ valid: false, errors: 사유 }) });
const api = createApi(b);
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
const e = await api
.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" })
.then(() => null, (err: KioBridgeError) => err);
expect(e?.message).toBe(사유[0]);
expect(e?.details).toEqual(사유);
});
it("매핑 전에는 승인할 수 없다 (P0-4)", async () => {
const execute = vi.fn(async () => ({ planId: "pln_1" }));
const api = createApi(가짜백엔드({ execute }));
await expect(
api.approve({ pairingId: "안한세션", sheetId: "p1", mappingResult: "exact" }),
).rejects.toThrow();
expect(execute).not.toHaveBeenCalled();
});
it("확신이 낮은데 직접 짚지 않으면 실행하지 않는다", async () => {
const execute = vi.fn(async () => ({ planId: "pln_1" }));
const b = 가짜백엔드({ execute }, 기본추천({ confidence: 0.4 }));
const api = createApi(b);
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
await expect(
api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "low_confidence" }),
).rejects.toThrow();
expect(execute).not.toHaveBeenCalled();
});
});
describe("판정 순서", () => {
it("확신이 낮아도 못 맞춘 조건이 있으면 그걸 먼저 알린다", async () => {
// low_confidence 가 changed 를 가리면, 확신 낮고 조건도 못 맞춘 경우에
// 무엇을 못 맞췄는지가 화면에서 사라진다.
const b = 가짜백엔드({}, 기본추천({
confidence: 0.4,
matchedOptions: [{ label: "컵", value: "종이컵", matched: false, note: "오늘은 제공되지 않아요" }],
}));
const api = createApi(b);
await api.claimPairing("kb");
const r = await api.requestMapping("s1", "p1");
expect(r.result).toBe("changed");
expect(r.item?.options[0].matched).toBe(false);
});
});
describe("forgetAll", () => {
it("세션을 비워서 이전 매핑으로 승인할 수 없게 한다", async () => {
// 세션 Map 은 비우는 경로가 없으면 무한히 자라기도 한다.
const api = createApi(가짜백엔드());
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
await api.forgetAll();
await expect(
api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" }),
).rejects.toThrow();
});
it("화면이 등록해 둔 주문표 사본까지 지운다", async () => {
// 목(mockApi)은 이미 지우고 있었고 이 경로만 빠져 있었다. 남으면 '모두
// 지워요' 가 사실이 아니다 — 이름·고른 조건·메모가 그대로 들어 있다.
const api = createApi(가짜백엔드());
registerSheet({ id: "p9", menuName: "닭강정", place: "음식점", selections: {}, memo: "" });
expect(getSheet("p9")).toBeDefined();
await api.forgetAll();
expect(getSheet("p9")).toBeUndefined();
});
it("거절까지 갔던 세션도 지워진다", async () => {
/*
* 예전에는 reject 가 세션을 지웠다. 그러면 forgetAll 이 세션 목록으로
* 지울 대상을 찾을 때 이 페어링이 이미 없어서, 붙인 구현이 들고 있던
* 정규화된 주문표(고른 알레르기·맵기 전부)가 그대로 남았다.
*/
const forgetSession = vi.fn(async () => {});
const api = createApi(가짜백엔드({ forgetSession }));
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
await api.reject!({ pairingId: "s1", sheetId: "p1" });
await api.forgetAll();
// toHaveBeenCalled() 로는 부족하다. forgetAll 은 세션이 하나도 없어도
// forgetSession("") 을 한 번 부르므로, reject 가 다시 세션을 지우도록
// 되돌아가도 그 단언은 통과한다. 거절한 그 페어링으로 불렸는지를 본다.
expect(forgetSession).toHaveBeenCalledWith("s1");
});
it("거절한 세션으로는 다시 승인할 수 없다", async () => {
// 아니라고 한 것을 뒤에서 되살리지 않는다.
const api = createApi(가짜백엔드());
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
await api.reject!({ pairingId: "s1", sheetId: "p1" });
await expect(
api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" }),
).rejects.toThrow();
});
});
describe("changed 는 확인 표시를 받아야 넘어간다", () => {
it("확인 표시가 없으면 실행하지 않는다", async () => {
const execute = vi.fn(async () => ({ planId: "pln_1" }));
const b = 가짜백엔드({ execute }, 기본추천({
matchedOptions: [{ label: "컵", value: "종이컵", matched: false }],
}));
const api = createApi(b);
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
await expect(
api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "changed" }),
).rejects.toThrow();
expect(execute).not.toHaveBeenCalled();
});
it("같은 세션에서 두 번 실행하지 않는다", async () => {
const execute = vi.fn(async () => ({ planId: "pln_1" }));
const api = createApi(가짜백엔드({ execute }));
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
await api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" });
await expect(
api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" }),
).rejects.toThrow();
expect(execute).toHaveBeenCalledTimes(1);
});
it("동시에 들어온 승인 두 건 중 하나만 실행된다", async () => {
// 위 테스트는 순차 호출만 본다. 검사와 확정 사이에 await 를 끼워 넣어도
// 통과한다. 예전에 실제로 그랬고, 사용자는 한 번 승인하고 두 개를 받았다.
const execute = vi.fn(async () => ({ planId: "pln_1" }));
const api = createApi(가짜백엔드({
execute,
// 두 호출이 겹치도록 첫 await 를 늘린다.
submit: async () => { await new Promise((r) => setTimeout(r, 10)); },
}));
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
const 요청 = { pairingId: "s1", sheetId: "p1", mappingResult: "exact" as const };
const 결과 = await Promise.allSettled([api.approve(요청), api.approve(요청)]);
expect(결과.filter((r) => r.status === "fulfilled")).toHaveLength(1);
expect(execute).toHaveBeenCalledTimes(1);
});
it("후보를 고르는 화면이 아닌데 candidateId 가 오면 거절한다", async () => {
// client.ts 는 이미 막는데 이 계층만 열려 있으면, 붙이는 구현을 바꾸는
// 것만으로 사용자가 고른 적 없는 메뉴가 담긴다.
const execute = vi.fn(async () => ({ planId: "pln_1" }));
const api = createApi(가짜백엔드({ execute }));
await api.claimPairing("kb");
await api.requestMapping("s1", "p1"); // exact 로 답한다
await expect(
api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact", candidateId: "c2" }),
).rejects.toThrow();
expect(execute).not.toHaveBeenCalled();
});
});
describe("evidence 를 화면이 아는 상태로 옮긴다", () => {
it("cart_ready 는 모든 단계를 done 으로 만든다", async () => {
const api = createApi(가짜백엔드());
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
const { planId } = await api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" });
const s = await api.getPlanStatus(planId);
expect(s.state).toBe("cart_ready");
expect(s.steps.every((x) => x === "done")).toBe(true);
expect(s.cart?.totalText).toBe("6,000원");
});
it("aborted 는 멈춘 단계를 failed 로 표시한다", async () => {
const b = 가짜백엔드({
getEvidence: async () => ({ state: "aborted", reachedStep: 2, abort: { code: "UNKNOWN_SCREEN", title: "안전을 위해 중단되었습니다", message: "예상하지 못한 화면", userAction: "직원을 불러 주세요" } }),
});
const api = createApi(b);
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
const { planId } = await api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" });
const s = await api.getPlanStatus(planId);
expect(s.state).toBe("aborted");
expect(s.steps[2]).toBe("failed");
expect(s.abort?.recoverable).toBe(false);
});
it("동작 수가 단계 수보다 많아도 전부 완료로 보이지 않는다", async () => {
/*
* reachedStep 은 '실행한 동작 수' 이고 STEPS 는 다섯 칸이라 단위가 다르다.
* 백엔드가 만드는 동작은 9~10개라 중단이 나면 거의 항상 5 이상이 된다.
*
* 자르지 않으면 다섯 칸이 전부 i < reachedStep 에 걸려 모두 done 이 되고,
* 화면 위쪽은 "안전을 위해 멈췄어요" 인데 아래는 다 끝난 것처럼 보인다.
*/
const b = 가짜백엔드({
getEvidence: async () => ({
state: "aborted", reachedStep: 8,
abort: { code: "SAFETY_STOP", title: "안전을 위해 멈췄어요", message: "예상하지 못한 화면", userAction: "직원을 불러 주세요" },
}),
});
const api = createApi(b);
await api.claimPairing("kb");
await api.requestMapping("s1", "p1");
const { planId } = await api.approve({ pairingId: "s1", sheetId: "p1", mappingResult: "exact" });
const s = await api.getPlanStatus(planId);
expect(s.steps.every((x) => x === "done")).toBe(false);
// 실패 칸이 반드시 하나 찍힌다. 멈췄다는 사실이 단계에도 남아야 한다.
expect(s.steps.filter((x) => x === "failed")).toHaveLength(1);
expect(s.steps[s.steps.length - 1]).toBe("failed");
});
});
// ─── 팀 백엔드 어댑터 ─────────────────────────────────────────────────────────
//
// 위 테스트들은 "명세대로 주면 도는가" 를 본다. 아래는 팀 백엔드가 실제로
// 돌려주는 모양(ExecutionPlanController · ExecuteResult · Evidence)을 그대로 넣고
// 화면이 아는 값으로 옮겨지는지 본다. 명세와 구현이 달라서 둘 다 필요하다.
const 원래fetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = 원래fetch;
/*
* 알레르기설정 은 모듈 저장소라 시험 사이에 그대로 남는다. 시험 하나가 중간에
* 실패하면 켜 둔 값이 다음 시험으로 새어 나가고, 엉뚱한 시험이 알 수 없는
* 이유로 깨진다 — 그때는 실패한 시험이 아니라 뒤따르는 시험을 들여다보게 된다.
*
* 시험 안에서 try/finally 로 감싸는 것보다 여기서 한 번에 치우는 편이 낫다.
* 앞으로 생길 시험까지 덮는다.
*/
알레르기설정.비우기();
// 사람 식별자도 같은 이유로 되돌린다. 앞 시험이 로그인해 두면 다음 시험의
// 요청에 그 계정이 실린다.
사람식별자.비우기();
});
const 응답 = (body: unknown, status = 200) =>
({ ok: status < 400, status, text: async () => JSON.stringify(body), json: async () => body }) as Response;
/** 실제 백엔드가 돌려주는 submit-and-run 응답. */
const 실행성공 = {
valid: true,
validation: { valid: true, errors: [] },
evidence: {
runId: "run_77",
result: "PASS",
stopType: "NORMAL_BOUNDARY_STOP",
executedActions: [{}, {}, {}, {}, {}],
reviewSnapshot: {
"주문 방식": "포장하기",
cartItems: [{ name: "매운 순살 닭강정", price: 6000, quantity: 2 }],
total: 12000,
},
},
};
/** 화면이 들고 있는 주문표. 승인 때 내용을 그대로 함께 보낸다. */
const 목주문표: OrderSheet = {
id: "p1", menuName: "닭강정", place: "음식점", memo: "",
selections: { "이용 방식": ["포장하기"], "맵기": ["매운맛"], "형태": ["순살"], "수량": ["2개"] },
};
/** POST /api/v1/recommendations 응답. 승인 요청에 그대로 되돌려 준다. */
const 목추천 = {
recommendedCandidateId: "candidate-alpha",
alternativeCandidateIds: [],
excludedCandidates: [],
recommendationReasons: ["매운맛 선호와 일치해요."],
confidence: 0.9,
requiresReconfirmation: false,
};
/** 서버가 정규화해서 돌려주는 값. 이걸 그대로 다음 호출에 쓴다. */
const 정규화응답 = {
주문표: {
status: "VALID",
profile: {
profileId: "p1", dataClassification: "SYNTHETIC_PROFILE",
// providerId 는 서버 설정에서 온다. 프론트가 짐작하지 않는다.
source: { collectionChannel: "WEB_FORM", providerId: "WHATTHEBUG", collectedAt: "2026-08-01T05:30:00Z" },
accessibility: {}, interaction: {}, consent: {},
},
contractValidation: { valid: true, errors: [] },
},
맥락: {
status: "VALID",
sessionContext: {
intent: { task: "ORDER_FOOD" },
preferences: { serviceType: "TAKE_OUT", spicyLevel: "HOT", boneType: "BONELESS", quantity: 2 },
hardConstraints: { allergenIds: [] },
},
reconfirmationFields: [],
contractValidation: { valid: true, errors: [] },
},
// 담당1의 마지막 관문. 주문표와 맥락을 합쳐 놓고 다시 본다.
통합: { status: "VALID", recommendationReady: true, contractValidation: { valid: true, errors: [] } },
};
/** 경로를 보고 답한다. 순서에 기대면 정규화가 끼는 순간 전부 어긋난다. */
const 경로별응답 = (over: Record<string, unknown> = {}) => (url: string, body: Record<string, unknown>) => {
for (const [조각, 값] of Object.entries(over)) if (url.includes(조각)) return 값;
if (url.includes("profile-normalizations")) return 정규화응답.주문표;
if (url.includes("session-context-normalizations")) return 정규화응답.맥락;
if (url.includes("canonical-inputs/validate")) return 정규화응답.통합;
// 서버는 고정에 성공하면 bound: true 를 주고, 아니면 던진다.
if (url.includes("pairing/bind")) return { bound: true };
if (url.includes("candidate-filters")) return { eligibleCandidates: [], excludedCandidates: [] };
if (url.includes("recommendations")) return 목추천;
if (body.userDecision) return 실행성공;
return {};
};
describe("팀 백엔드가 실제로 주는 모양을 화면 값으로 옮긴다", () => {
const 붙이기 = (over: Record<string, unknown> = {}) => {
const 답 = 경로별응답(over);
globalThis.fetch = vi.fn(async (u: unknown, init?: RequestInit) =>
응답(답(String(u), JSON.parse(String(init?.body ?? "{}"))))) as unknown as typeof fetch;
return createTeamBackend("/api/bff");
};
/** 승인 전에 매핑을 한 번 거친다. 실제 흐름과 같은 순서다. */
const 승인 = async (
b: ReturnType<typeof createTeamBackend>,
실행응답: unknown,
/** 주문표를 바꿔 넣고 싶을 때. 실행 단계의 '아는 값' 이 여기서 나온다. */
주문표: OrderSheet = 목주문표,
) => {
const 답 = 경로별응답({ "orchestrator/approve": 실행응답 });
globalThis.fetch = vi.fn(async (u: unknown, init?: RequestInit) =>
응답(답(String(u), JSON.parse(String(init?.body ?? "{}"))))) as unknown as typeof fetch;
await b.recommend({ environmentId: "chicken-store", profileId: "p1", survivingCandidateIds: [], profile: 주문표 });
await b.submit("s1", { pairingId: "s1", sheetId: "p1", mappingResult: "exact", profile: 주문표 });
};
it("재확인이 필요하면 돌아갈 길이 있는 오류로 알린다", async () => {
/*
* 이 분기가 죽어 있었다.
*
* 백엔드는 reconfirmationFields 가 비지 않을 때만 RECONFIRMATION_REQUIRED 를
* 내고, 그 필드는 contractValidation.errors 에서 골라 만든다. 킷은
* HARD_CONSTRAINT_UNKNOWN 을 warning 이 아니라 error 로 넣는다.
*
* 즉 RECONFIRMATION_REQUIRED 이면 valid 는 반드시 false 다. INVALID 검사가
* 위에 있으면 항상 그쪽이 먼저 던지고, 알레르기를 모르는 분에게
* 돌아갈 길 없는(recoverable: false) 오류와 킷 원문이 그대로 나간다.
*/
const b = 붙이기({
"session-context-normalizations": {
status: "RECONFIRMATION_REQUIRED",
sessionContext: 정규화응답.맥락.sessionContext,
reconfirmationFields: [{ field: "allergenIds", message: "알레르기를 다시 확인해 주세요" }],
contractValidation: {
valid: false,
errors: [{ code: "HARD_CONSTRAINT_UNKNOWN", message: "allergenIds 가 UNKNOWN 입니다. 임의로 추론하지 말고..." }],
},
},
});
const e = await b.recommend({
environmentId: "chicken-store", profileId: "p1", survivingCandidateIds: [], profile: 목주문표,
}).then(() => null, (err: KioBridgeError) => err);
expect(e?.code).toBe("RECONFIRM_REQUIRED");
// 돌아갈 길을 준다. 이게 이 분기를 만든 이유다.
expect(e?.recoverable).toBe(true);
// 킷 원문이 아니라 재확인 쪽 문장을 쓴다.
expect(e?.message).toBe("알레르기를 다시 확인해 주세요");
expect(e?.message).not.toContain("UNKNOWN");
});
it("서버가 준 규칙 판정을 그대로 쓴다", async () => {
/*
* 예전에는 이 셋을 버리고 attributes.supportedOptions 로 같은 판단을 다시 했다.
* 같은 판단을 두 곳에서 하면 언젠가 갈라진다.
*/
const b = 붙이기({
"candidate-filters": {
eligibleCandidates: [{ candidateId: "candidate-alpha", name: "매운 순살 닭강정", price: 6000, available: true }],
excludedCandidates: [],
warningsByCandidateId: {
"candidate-alpha": [{ ruleId: "CHICKEN_BONE_TYPE_PREFERENCE", result: "FAIL", severity: "WARN", errorCode: "BONE_TYPE_MISMATCH" }],
},
passesByCandidateId: {
"candidate-alpha": [{ ruleId: "CHICKEN_SPICY_LEVEL_PREFERENCE", result: "PASS", errorCode: "SPICY_LEVEL_MISMATCH" }],
},
},
recommendations: { ...목추천, recommendedCandidateId: "candidate-alpha", alternativeCandidateIds: [] },
});
await b.filterCandidates({ environmentId: "chicken-store", profileId: "p1", profile: 목주문표 });
const rec = await b.recommend({ environmentId: "chicken-store", profileId: "p1", survivingCandidateIds: [], profile: 목주문표 });
const 표 = Object.fromEntries(rec.matchedOptions.map((o) => [o.label, o.matched]));
expect(표["형태"]).toBe(false); // WARN 이 왔다
expect(표["맵기"]).toBe(true); // PASS 가 왔다
/*
* 이용 방식은 어느 쪽에도 안 왔다. WARN 이 없다는 사실만으로는 '일치한다' 를
* 뜻하지 않는다 - SKIPPED 면 '비교한 적이 없다' 다. 아무 말도 하지 않는다.
*/
expect(표["이용 방식"]).toBeUndefined();
});
it("서버가 비교한 값을 우리말로 바꿔 적는다", async () => {
/*
* 예전에는 어느 축이든 "오늘은 이 조합이 없어요" 한 문장이었다. 무엇으로
* 바뀌는지를 안 말해 줘서, 사용자가 이걸 담아도 되는지 판단할 근거가 없었다.
* 서버는 candidateValue 를 실어 보내고 있었는데 우리가 안 읽었다.
*/
const b = 붙이기({
"candidate-filters": {
eligibleCandidates: [{ candidateId: "candidate-alpha", name: "닭강정", price: 6000, available: true }],
excludedCandidates: [],
warningsByCandidateId: {
"candidate-alpha": [{
ruleId: "CHICKEN_SPICY_LEVEL_PREFERENCE", result: "FAIL", severity: "WARN",
errorCode: "SPICY_LEVEL_MISMATCH", sourceValue: "HOT", candidateValue: ["MILD"],
}],
},
passesByCandidateId: {},
},
recommendations: { ...목추천, recommendedCandidateId: "candidate-alpha", alternativeCandidateIds: [] },
});
await b.filterCandidates({ environmentId: "chicken-store", profileId: "p1", profile: 목주문표 });
const rec = await b.recommend({ environmentId: "chicken-store", profileId: "p1", survivingCandidateIds: [], profile: 목주문표 });
const 맵기 = rec.matchedOptions.find((o) => o.label === "맵기");
expect(맵기?.matched).toBe(false);
// enum 이 아니라 우리말로. "MILD" 가 화면에 뜨면 안 된다.
expect(맵기?.note).toBe("이 메뉴는 순한맛이에요");
expect(맵기?.note).not.toContain("MILD");
});
it("모르는 enum 이면 원문을 띄우지 않고 예전 문장으로 돌아간다", async () => {
const b = 붙이기({
"candidate-filters": {
eligibleCandidates: [{ candidateId: "candidate-alpha", name: "닭강정", price: 6000, available: true }],
excludedCandidates: [],
warningsByCandidateId: {
"candidate-alpha": [{
ruleId: "CHICKEN_SPICY_LEVEL_PREFERENCE", result: "FAIL", severity: "WARN",
errorCode: "SPICY_LEVEL_MISMATCH", sourceValue: "HOT", candidateValue: ["SERVER_ADDED_THIS"],
}],
},
passesByCandidateId: {},
},
recommendations: { ...목추천, recommendedCandidateId: "candidate-alpha", alternativeCandidateIds: [] },
});
await b.filterCandidates({ environmentId: "chicken-store", profileId: "p1", profile: 목주문표 });
const rec = await b.recommend({ environmentId: "chicken-store", profileId: "p1", survivingCandidateIds: [], profile: 목주문표 });
const 맵기 = rec.matchedOptions.find((o) => o.label === "맵기");
expect(맵기?.note).toBe("오늘은 이 조합이 없어요");
expect(맵기?.note).not.toContain("SERVER_ADDED_THIS");
});
it("severity 가 BLOCK 이면 후보에서 뺀다", async () => {
/*
* warningsByCandidateId 에는 WARN 만 담기게 돼 있어서 지금은 한 번도 안 걸린다.
* 그래도 남긴다 - BLOCK 은 알레르기.품절 같은 절대 조건에 붙는 severity 라,
* 그런 후보를 "조금 다른 메뉴" 로 내밀면 안 된다.
*/
const b = 붙이기({
"candidate-filters": {
eligibleCandidates: [
{ candidateId: "candidate-alpha", name: "매운 순살 닭강정", price: 6000, available: true },
{ candidateId: "candidate-beta", name: "순한 순살 닭강정", price: 7000, available: true },
],
excludedCandidates: [],
warningsByCandidateId: {
// ruleId 와 errorCode 가 같은 축을 가리켜야 한다. 예전에는 알레르기 규칙에
// 맵기 코드를 붙여 놓고 "맵기 때문에 뺐어요" 를 기대값으로 못 박았다 —
// 알레르기 코드를 규칙축 표에 넣는 날 이 시험이 틀린 기대를 지킨다.
"candidate-beta": [{
ruleId: "CHICKEN_SPICY_LEVEL_PREFERENCE", result: "FAIL", severity: "BLOCK",
errorCode: "SPICY_LEVEL_MISMATCH",
}],
},
passesByCandidateId: {},
},
recommendations: { ...목추천, recommendedCandidateId: "candidate-alpha", alternativeCandidateIds: ["candidate-beta"] },
});
const f = await b.filterCandidates({ environmentId: "chicken-store", profileId: "p1", profile: 목주문표 });
expect(f.survivingCandidateIds).toEqual(["candidate-alpha"]);
// 조용히 사라지면 "왜 없지?" 가 된다. 뺐다고 말하고, 어느 축인지도 짚는다.
const 뺀 = f.excluded.find((e) => e.candidateId === "candidate-beta");
expect(뺀?.reasonCode).toBe("BLOCKED");
expect(뺀?.explanation).toContain("맵기");
// 추천 응답이 대안으로 올려보내도 다시 걸러진다.
const rec = await b.recommend({ environmentId: "chicken-store", profileId: "p1", survivingCandidateIds: [], profile: 목주문표 });
expect(rec.alternativeCandidateIds).toEqual([]);
});
it("정규화 도중에 알레르기가 바뀌어도 키와 보낸 값이 갈라지지 않는다", async () => {
/*
* 예전에는 캐시키를 만들 때 한 번, 요청을 보낼 때 또 한 번 값을 읽었다.
* 그 사이에 await 이 있어서, 그동안 알레르기를 바꾸면 **키와 실제 보낸 값이
* 서로 다른 조건을 가리켰다.** 알레르기가 빠진 맥락이 '알레르기가 있는' 키에
* 저장되고, 다음에 같은 키로 찾으면 걸러졌어야 할 후보가 안 걸러진다.
*
* 첫 요청(profile-normalizations)이 나가는 순간 알레르기를 비워서 그 틈을
* 흉내 낸다. 두 번째 요청에는 처음 값이 실려야 한다.
*/
알레르기설정.되살리기(["PEANUT"]);
const 보낸것: Record<string, unknown>[] = [];
globalThis.fetch = vi.fn(async (u: unknown, init?: RequestInit) => {
const 주소 = String(u);
const 본문 = JSON.parse(String(init?.body ?? "{}"));
보낸것.push({ 주소, 본문 });
// 첫 요청이 나가자마자 설정이 바뀐 상황
if (주소.includes("profile-normalizations")) 알레르기설정.비우기();
return 응답(경로별응답({})(주소, 본문));
}) as unknown as typeof fetch;
const b = createTeamBackend("");
await b.filterCandidates({ environmentId: "chicken-store", profileId: "p1", profile: 목주문표 });
const 맥락 = 보낸것.find((x) => String(x.주소).includes("session-context-normalizations"));
expect((맥락?.본문 as { contextInput: { allergenIds: string[] } }).contextInput.allergenIds)
.toEqual(["PEANUT"]);
// 치우는 것은 afterEach 가 한다. 여기서 부르면 실패로 빠져나갈 때 안 불린다.
});
it("규칙축에 없는 errorCode 면 축을 짚지 않고 뭉뚱그린다", async () => {
// 알레르기(ALLERGEN_CONFLICT)는 규칙축 표에 없다. 없는 것을 억지로 짚느니
// "조건에 맞지 않아서" 라고만 말한다 — 틀린 축을 짚으면 그게 더 나쁘다.
const b = 붙이기({
"candidate-filters": {
eligibleCandidates: [{ candidateId: "candidate-beta", name: "땅콩 토핑 닭강정", price: 7000, available: true }],
excludedCandidates: [],
warningsByCandidateId: {
"candidate-beta": [{
ruleId: "CHICKEN_ALLERGEN_HARD_CONSTRAINT", result: "FAIL", severity: "BLOCK",
errorCode: "ALLERGEN_CONFLICT",
}],
},
passesByCandidateId: {},
},
});
const f = await b.filterCandidates({ environmentId: "chicken-store", profileId: "p1", profile: 목주문표 });
expect(f.survivingCandidateIds).toEqual([]);
const 뺀것 = f.excluded.find((e) => e.candidateId === "candidate-beta");
// 문장은 고정문, 이름은 menuName 으로 따로 온다. 문장에 이름을 섞으면
// 매번 다른 문장이 되어 영어 화면에서 통째로 못 옮긴다(#101 리뷰).
expect(뺀것?.explanation).toBe("조건에 맞지 않아서 뺐어요");
expect(뺀것?.menuName).toBe("땅콩 토핑 닭강정");
});
it("점수가 양수인 축만 이름으로 뽑고 숫자는 버린다", async () => {
/*
* 0.0259 는 이 앱을 쓰는 분들에게 읽을 수 없는 값이다. 다만 이유 문장이
* 빠뜨리는 것이 있어서(가격 한도를 정해도 서버 이유에는 가격 얘기가 안 나온다)
* 축 이름만 남긴다. 깎인 축과 모르는 칸은 뺀다.
*/
const b = 붙이기({
recommendations: {
...목추천,
scoreBreakdown: { serviceTypeMatch: 1.0, spicyLevelMatch: -0.5, priceScore: 0.0259, serverAddedThis: 3 },
},
});
const rec = await b.recommend({ environmentId: "chicken-store", profileId: "p1", survivingCandidateIds: [], profile: 목주문표 });
expect(rec.scoredAxes).toEqual(["이용 방식", "가격"]);
});
it("점수가 안 오면 빈 배열이다 — 화면이 그 줄을 안 그린다", async () => {
const b = 붙이기();
const rec = await b.recommend({ environmentId: "chicken-store", profileId: "p1", survivingCandidateIds: [], profile: 목주문표 });
expect(rec.scoredAxes).toEqual([]);
});
it("규칙 판정이 아예 안 오면 예전처럼 우리가 맞춰 본다", async () => {
// 옛 백엔드에서도 확인 카드가 비지 않아야 한다.
const b = 붙이기({
"candidate-filters": {
eligibleCandidates: [{
candidateId: "candidate-alpha", name: "매운 순살 닭강정", price: 6000, available: true,
attributes: { spicyLevel: "HOT", boneType: "BONELESS" },
supportedOptions: { SERVICE_TYPE: ["TAKE_OUT"], CUP: ["PAPER"] },
}],