forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

spec_bounds.rs1629 lines, 49.8 KiBHistoryRawDownload
1//! The OpenAPI document must not lie about its own bounds.
2//!
3//! utoipa 5.5's `#[schema(max_length = …)]` accepts a **literal only** — a
4//! `const` there fails to compile with "no `literal` value found after this
5//! point". So every annotation in `src/web/*.rs` is unavoidably a hand-copied
6//! duplicate of a number in `src/constant.rs`, and a copy nothing checks is a
7//! copy that silently goes stale. A frontend generating validators from
8//! `/api-docs/openapi.json` would then enforce yesterday's rule and get 400s it
9//! cannot explain.
10//!
11//! This test closes that loop from the far end: it builds the real router,
12//! fetches the emitted spec, and asserts each published bound still equals the
13//! constant the server actually validates against. The expectations below are
14//! the constants — never literals — because a test written against literals
15//! would be a third copy and would pass while both were wrong.
16
17use axum::body::Body;
18use axum::http::Request;
19use hezarfen_backend::constant::*;
20use hezarfen_backend::state::AppState;
21use hezarfen_backend::{build_router, database};
22use serde_json::Value;
23use tower::ServiceExt;
24
25/// The emitted OpenAPI document, as the server serves it.
26async fn spec() -> Value {
27 let tenants = database::init_test_tenants().await;
28 let app = build_router(AppState {
29 db: tenants.control().clone(),
30 tenants,
31 files_path: tempfile::tempdir().expect("files dir").keep(),
32 cookie_secure: false,
33 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
34 chatbot_limit: Default::default(),
35 rag_limit: Default::default(),
36 exam_presence: Default::default(),
37 board_hub: Default::default(),
38 ai: None,
39 metrics: hezarfen_backend::telemetry::Metrics::noop(),
40 });
41 let res = app
42 .oneshot(
43 Request::builder()
44 .uri("/api-docs/openapi.json")
45 .body(Body::empty())
46 .expect("request"),
47 )
48 .await
49 .expect("spec response");
50 let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
51 .await
52 .expect("spec body");
53 serde_json::from_slice(&bytes).expect("spec is json")
54}
55
56/// Every published request-schema bound, paired with the constant it must
57/// equal. Columns: schema, field, JSON Schema keyword, expected value.
58///
59/// Add a row whenever you add a `#[schema(max_length = …)]`-style attribute to
60/// a request DTO — the annotation is the promise, this row is the proof.
61fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> {
62 vec![
63 // --- builder (the vendor surface) ---
64 (
65 "CreateSchool",
66 "name",
67 "maxLength",
68 MAX_SCHOOL_NAME_LEN as i64,
69 ),
70 (
71 "UpdateSchool",
72 "name",
73 "maxLength",
74 MAX_SCHOOL_NAME_LEN as i64,
75 ),
76 (
77 "CreateSchool",
78 "admin_username",
79 "minLength",
80 MIN_USERNAME_LEN as i64,
81 ),
82 (
83 "CreateSchool",
84 "admin_username",
85 "maxLength",
86 MAX_USERNAME_LEN as i64,
87 ),
88 (
89 "CreateSchool",
90 "admin_password",
91 "minLength",
92 MIN_PASSWORD_LEN as i64,
93 ),
94 (
95 "CreateSchool",
96 "admin_password",
97 "maxLength",
98 MAX_PASSWORD_LEN as i64,
99 ),
100 (
101 "BuilderCredentials",
102 "username",
103 "minLength",
104 MIN_USERNAME_LEN as i64,
105 ),
106 (
107 "BuilderCredentials",
108 "username",
109 "maxLength",
110 MAX_USERNAME_LEN as i64,
111 ),
112 (
113 "BuilderCredentials",
114 "password",
115 "minLength",
116 MIN_PASSWORD_LEN as i64,
117 ),
118 (
119 "BuilderCredentials",
120 "password",
121 "maxLength",
122 MAX_PASSWORD_LEN as i64,
123 ),
124 (
125 "AdminPassword",
126 "username",
127 "minLength",
128 MIN_USERNAME_LEN as i64,
129 ),
130 (
131 "AdminPassword",
132 "username",
133 "maxLength",
134 MAX_USERNAME_LEN as i64,
135 ),
136 (
137 "EnterSchool",
138 "username",
139 "minLength",
140 MIN_USERNAME_LEN as i64,
141 ),
142 (
143 "EnterSchool",
144 "username",
145 "maxLength",
146 MAX_USERNAME_LEN as i64,
147 ),
148 (
149 "AdminPassword",
150 "password",
151 "minLength",
152 MIN_PASSWORD_LEN as i64,
153 ),
154 (
155 "AdminPassword",
156 "password",
157 "maxLength",
158 MAX_PASSWORD_LEN as i64,
159 ),
160 // --- auth / users / notes / messages ---
161 (
162 "RegisterCredentials",
163 "username",
164 "minLength",
165 MIN_USERNAME_LEN as i64,
166 ),
167 (
168 "RegisterCredentials",
169 "username",
170 "maxLength",
171 MAX_USERNAME_LEN as i64,
172 ),
173 (
174 "RegisterCredentials",
175 "password",
176 "minLength",
177 MIN_PASSWORD_LEN as i64,
178 ),
179 (
180 "RegisterCredentials",
181 "password",
182 "maxLength",
183 MAX_PASSWORD_LEN as i64,
184 ),
185 (
186 "LoginCredentials",
187 "username",
188 "minLength",
189 MIN_USERNAME_LEN as i64,
190 ),
191 (
192 "LoginCredentials",
193 "username",
194 "maxLength",
195 MAX_USERNAME_LEN as i64,
196 ),
197 (
198 "LoginCredentials",
199 "password",
200 "minLength",
201 MIN_PASSWORD_LEN as i64,
202 ),
203 (
204 "LoginCredentials",
205 "password",
206 "maxLength",
207 MAX_PASSWORD_LEN as i64,
208 ),
209 (
210 "CreateUser",
211 "username",
212 "minLength",
213 MIN_USERNAME_LEN as i64,
214 ),
215 (
216 "CreateUser",
217 "username",
218 "maxLength",
219 MAX_USERNAME_LEN as i64,
220 ),
221 (
222 "CreateUser",
223 "password",
224 "minLength",
225 MIN_PASSWORD_LEN as i64,
226 ),
227 (
228 "CreateUser",
229 "password",
230 "maxLength",
231 MAX_PASSWORD_LEN as i64,
232 ),
233 (
234 "CreateUser",
235 "student_number",
236 "maxLength",
237 MAX_STUDENT_NUMBER_LEN as i64,
238 ),
239 ("UpdateProfile", "name", "maxLength", MAX_NAME_LEN as i64),
240 ("UpdateProfile", "surname", "maxLength", MAX_NAME_LEN as i64),
241 ("UpdateProfile", "email", "maxLength", MAX_EMAIL_LEN as i64),
242 (
243 "UpdateProfile",
244 "display_name",
245 "maxLength",
246 MAX_DISPLAY_NAME_LEN as i64,
247 ),
248 ("UpdateProfile", "bio", "maxLength", MAX_BIO_LEN as i64),
249 // Free text with the same length cap the bio has.
250 ("UpdateProfile", "address", "maxLength", MAX_ADDRESS_LEN as i64),
251 // The emergency contact is a person's name, held to the same bound.
252 (
253 "UpdateProfile",
254 "emergency_contact_name",
255 "maxLength",
256 MAX_NAME_LEN as i64,
257 ),
258 // A branş is one entry of the school's `branches` list, so it is
259 // bounded by the same per-entry length the list itself is.
260 (
261 "UpdateProfile",
262 "branch",
263 "maxLength",
264 MAX_SETTINGS_ITEM_LEN as i64,
265 ),
266 (
267 "UpdateProfile",
268 "student_number",
269 "maxLength",
270 MAX_STUDENT_NUMBER_LEN as i64,
271 ),
272 (
273 "CreateNote",
274 "title",
275 "maxLength",
276 MAX_NOTE_TITLE_LEN as i64,
277 ),
278 (
279 "CreateNote",
280 "content",
281 "maxLength",
282 MAX_NOTE_CONTENT_LEN as i64,
283 ),
284 (
285 "UpdateNote",
286 "title",
287 "maxLength",
288 MAX_NOTE_TITLE_LEN as i64,
289 ),
290 (
291 "UpdateNote",
292 "content",
293 "maxLength",
294 MAX_NOTE_CONTENT_LEN as i64,
295 ),
296 (
297 "CreateCourseNote",
298 "title",
299 "maxLength",
300 MAX_NOTE_TITLE_LEN as i64,
301 ),
302 (
303 "CreateCourseNote",
304 "content",
305 "maxLength",
306 MAX_NOTE_CONTENT_LEN as i64,
307 ),
308 (
309 "UpdateCourseNote",
310 "title",
311 "maxLength",
312 MAX_NOTE_TITLE_LEN as i64,
313 ),
314 (
315 "UpdateCourseNote",
316 "content",
317 "maxLength",
318 MAX_NOTE_CONTENT_LEN as i64,
319 ),
320 (
321 "SendMessage",
322 "subject",
323 "maxLength",
324 MAX_MESSAGE_SUBJECT_LEN as i64,
325 ),
326 (
327 "SendMessage",
328 "body",
329 "maxLength",
330 MAX_MESSAGE_BODY_LEN as i64,
331 ),
332 (
333 "SendMessage",
334 "label",
335 "maxLength",
336 MAX_MESSAGE_LABEL_LEN as i64,
337 ),
338 // --- events / appointments / courses / subjects / sessions ---
339 (
340 "CreateEvent",
341 "title",
342 "maxLength",
343 MAX_EVENT_TITLE_LEN as i64,
344 ),
345 (
346 "CreateEvent",
347 "description",
348 "maxLength",
349 MAX_EVENT_DESCRIPTION_LEN as i64,
350 ),
351 (
352 "UpdateEvent",
353 "title",
354 "maxLength",
355 MAX_EVENT_TITLE_LEN as i64,
356 ),
357 (
358 "UpdateEvent",
359 "description",
360 "maxLength",
361 MAX_EVENT_DESCRIPTION_LEN as i64,
362 ),
363 (
364 "MarkAttendance",
365 "status",
366 "maxLength",
367 MAX_SETTINGS_ITEM_LEN as i64,
368 ),
369 (
370 "PublishSlots",
371 "note",
372 "maxLength",
373 MAX_APPOINTMENT_NOTE_LEN as i64,
374 ),
375 (
376 "BookAppointment",
377 "reason",
378 "maxLength",
379 MAX_APPOINTMENT_REASON_LEN as i64,
380 ),
381 (
382 "CancelRequest",
383 "reason",
384 "maxLength",
385 MAX_APPOINTMENT_REASON_LEN as i64,
386 ),
387 (
388 "RejectRequest",
389 "reason",
390 "maxLength",
391 MAX_APPOINTMENT_REASON_LEN as i64,
392 ),
393 (
394 "CreateCourse",
395 "title",
396 "maxLength",
397 MAX_COURSE_TITLE_LEN as i64,
398 ),
399 (
400 "CreateCourse",
401 "description",
402 "maxLength",
403 MAX_COURSE_DESCRIPTION_LEN as i64,
404 ),
405 (
406 "UpdateCourse",
407 "title",
408 "maxLength",
409 MAX_COURSE_TITLE_LEN as i64,
410 ),
411 (
412 "UpdateCourse",
413 "description",
414 "maxLength",
415 MAX_COURSE_DESCRIPTION_LEN as i64,
416 ),
417 (
418 "CreateClass",
419 "name",
420 "maxLength",
421 MAX_CLASS_NAME_LEN as i64,
422 ),
423 (
424 "CreateClass",
425 "grade_level",
426 "minimum",
427 MIN_GRADE_LEVEL as i64,
428 ),
429 (
430 "CreateClass",
431 "grade_level",
432 "maximum",
433 MAX_GRADE_LEVEL as i64,
434 ),
435 (
436 "CreateBlueprint",
437 "grade_level",
438 "minimum",
439 MIN_GRADE_LEVEL as i64,
440 ),
441 (
442 "CreateBlueprint",
443 "grade_level",
444 "maximum",
445 MAX_GRADE_LEVEL as i64,
446 ),
447 (
448 "UpdateClass",
449 "name",
450 "maxLength",
451 MAX_CLASS_NAME_LEN as i64,
452 ),
453 (
454 "UpdateClass",
455 "grade_level",
456 "minimum",
457 MIN_GRADE_LEVEL as i64,
458 ),
459 (
460 "UpdateClass",
461 "grade_level",
462 "maximum",
463 MAX_GRADE_LEVEL as i64,
464 ),
465 (
466 "CreateExamInCourse",
467 "title",
468 "maxLength",
469 MAX_EXAM_TITLE_LEN as i64,
470 ),
471 (
472 "CreateExamInCourse",
473 "description",
474 "maxLength",
475 MAX_EXAM_DESCRIPTION_LEN as i64,
476 ),
477 (
478 "CreateExamInCourse",
479 "kind",
480 "maxLength",
481 MAX_SETTINGS_ITEM_LEN as i64,
482 ),
483 (
484 "CreateExamInCourse",
485 "duration_ms",
486 "minimum",
487 MIN_EXAM_DURATION_MS,
488 ),
489 (
490 "CreateExamInCourse",
491 "duration_ms",
492 "maximum",
493 MAX_EXAM_DURATION_MS,
494 ),
495 (
496 "CreateExamInCourse",
497 "max_attempts",
498 "minimum",
499 UNLIMITED_EXAM_ATTEMPTS,
500 ),
501 (
502 "CreateExamInCourse",
503 "max_attempts",
504 "maximum",
505 MAX_EXAM_ATTEMPTS,
506 ),
507 (
508 "CreateSubject",
509 "name",
510 "maxLength",
511 MAX_SUBJECT_NAME_LEN as i64,
512 ),
513 (
514 "CreateSubject",
515 "description",
516 "maxLength",
517 MAX_SUBJECT_DESCRIPTION_LEN as i64,
518 ),
519 (
520 "CreateHomework",
521 "title",
522 "maxLength",
523 MAX_HOMEWORK_TITLE_LEN as i64,
524 ),
525 (
526 "CreateHomework",
527 "description",
528 "maxLength",
529 MAX_HOMEWORK_DESCRIPTION_LEN as i64,
530 ),
531 (
532 "CreateHomework",
533 "assigned",
534 "maxItems",
535 MAX_HOMEWORK_ASSIGNED as i64,
536 ),
537 (
538 "CreateSessionInCourse",
539 "topic",
540 "maxLength",
541 MAX_SESSION_TOPIC_LEN as i64,
542 ),
543 (
544 "UpdateSession",
545 "topic",
546 "maxLength",
547 MAX_SESSION_TOPIC_LEN as i64,
548 ),
549 (
550 "MarkRollCall",
551 "status",
552 "maxLength",
553 MAX_SETTINGS_ITEM_LEN as i64,
554 ),
555 (
556 "UpdateSubject",
557 "name",
558 "maxLength",
559 MAX_SUBJECT_NAME_LEN as i64,
560 ),
561 (
562 "UpdateSubject",
563 "description",
564 "maxLength",
565 MAX_SUBJECT_DESCRIPTION_LEN as i64,
566 ),
567 // --- exams / questions / question bank ---
568 (
569 "UpdateExam",
570 "title",
571 "maxLength",
572 MAX_EXAM_TITLE_LEN as i64,
573 ),
574 (
575 "UpdateExam",
576 "description",
577 "maxLength",
578 MAX_EXAM_DESCRIPTION_LEN as i64,
579 ),
580 ("UpdateExam", "duration_ms", "minimum", MIN_EXAM_DURATION_MS),
581 ("UpdateExam", "duration_ms", "maximum", MAX_EXAM_DURATION_MS),
582 (
583 "UpdateExam",
584 "max_attempts",
585 "minimum",
586 UNLIMITED_EXAM_ATTEMPTS,
587 ),
588 ("UpdateExam", "max_attempts", "maximum", MAX_EXAM_ATTEMPTS),
589 ("GradeResult", "mark", "minimum", MIN_MARK),
590 ("GradeResult", "mark", "maximum", MAX_MARK),
591 (
592 "CreateQuestion",
593 "text",
594 "maxLength",
595 MAX_QUESTION_TEXT_LEN as i64,
596 ),
597 ("CreateQuestion", "points", "minimum", MIN_QUESTION_POINTS),
598 ("CreateQuestion", "points", "maximum", MAX_QUESTION_POINTS),
599 (
600 "CreateQuestion",
601 "choices",
602 "minItems",
603 MIN_QUESTION_CHOICES as i64,
604 ),
605 (
606 "CreateQuestion",
607 "choices",
608 "maxItems",
609 MAX_QUESTION_CHOICES as i64,
610 ),
611 (
612 "UpdateQuestion",
613 "text",
614 "maxLength",
615 MAX_QUESTION_TEXT_LEN as i64,
616 ),
617 ("UpdateQuestion", "points", "minimum", MIN_QUESTION_POINTS),
618 ("UpdateQuestion", "points", "maximum", MAX_QUESTION_POINTS),
619 (
620 "UpdateQuestion",
621 "choices",
622 "minItems",
623 MIN_QUESTION_CHOICES as i64,
624 ),
625 (
626 "UpdateQuestion",
627 "choices",
628 "maxItems",
629 MAX_QUESTION_CHOICES as i64,
630 ),
631 (
632 "SaveAnswer",
633 "text",
634 "maxLength",
635 MAX_ANSWER_TEXT_LEN as i64,
636 ),
637 (
638 "AskQuestion",
639 "title",
640 "maxLength",
641 MAX_POOL_QUESTION_TITLE_LEN as i64,
642 ),
643 (
644 "AskQuestion",
645 "body",
646 "maxLength",
647 MAX_POOL_QUESTION_BODY_LEN as i64,
648 ),
649 (
650 "OfferSolution",
651 "body",
652 "maxLength",
653 MAX_SOLUTION_BODY_LEN as i64,
654 ),
655 (
656 "CreateBankQuestion",
657 "text",
658 "maxLength",
659 MAX_QUESTION_TEXT_LEN as i64,
660 ),
661 (
662 "CreateBankQuestion",
663 "points",
664 "minimum",
665 MIN_QUESTION_POINTS,
666 ),
667 (
668 "CreateBankQuestion",
669 "points",
670 "maximum",
671 MAX_QUESTION_POINTS,
672 ),
673 (
674 "CreateBankQuestion",
675 "choices",
676 "minItems",
677 MIN_QUESTION_CHOICES as i64,
678 ),
679 (
680 "CreateBankQuestion",
681 "choices",
682 "maxItems",
683 MAX_QUESTION_CHOICES as i64,
684 ),
685 (
686 "UpdateBankQuestion",
687 "text",
688 "maxLength",
689 MAX_QUESTION_TEXT_LEN as i64,
690 ),
691 (
692 "UpdateBankQuestion",
693 "points",
694 "minimum",
695 MIN_QUESTION_POINTS,
696 ),
697 (
698 "UpdateBankQuestion",
699 "points",
700 "maximum",
701 MAX_QUESTION_POINTS,
702 ),
703 (
704 "UpdateBankQuestion",
705 "choices",
706 "minItems",
707 MIN_QUESTION_CHOICES as i64,
708 ),
709 (
710 "UpdateBankQuestion",
711 "choices",
712 "maxItems",
713 MAX_QUESTION_CHOICES as i64,
714 ),
715 (
716 "ChoiceBody",
717 "text",
718 "maxLength",
719 MAX_CHOICE_TEXT_LEN as i64,
720 ),
721 // --- homework / settings / terms / chatbot ---
722 (
723 "UpdateHomework",
724 "title",
725 "maxLength",
726 MAX_HOMEWORK_TITLE_LEN as i64,
727 ),
728 (
729 "UpdateHomework",
730 "description",
731 "maxLength",
732 MAX_HOMEWORK_DESCRIPTION_LEN as i64,
733 ),
734 (
735 "UpdateHomework",
736 "assigned",
737 "maxItems",
738 MAX_HOMEWORK_ASSIGNED as i64,
739 ),
740 (
741 "SubmitHomework",
742 "text",
743 "maxLength",
744 MAX_HOMEWORK_TEXT_LEN as i64,
745 ),
746 ("GradeHomework", "mark", "minimum", MIN_MARK),
747 ("GradeHomework", "mark", "maximum", MAX_MARK),
748 (
749 "ExamKindDto",
750 "name",
751 "maxLength",
752 MAX_SETTINGS_ITEM_LEN as i64,
753 ),
754 ("ExamKindDto", "weight", "minimum", MIN_EXAM_KIND_WEIGHT),
755 ("ExamKindDto", "weight", "maximum", MAX_EXAM_KIND_WEIGHT),
756 (
757 "PatchExamWeight",
758 "weight",
759 "minimum",
760 MIN_EXAM_KIND_WEIGHT,
761 ),
762 (
763 "PatchExamWeight",
764 "weight",
765 "maximum",
766 MAX_EXAM_KIND_WEIGHT,
767 ),
768 ("GradeBandDto", "min", "minimum", MIN_MARK),
769 ("GradeBandDto", "min", "maximum", MAX_MARK),
770 (
771 "GradeBandDto",
772 "label",
773 "maxLength",
774 MAX_GRADE_LABEL_LEN as i64,
775 ),
776 (
777 "UpdateSettings",
778 "exam_kinds",
779 "maxItems",
780 MAX_SETTINGS_LIST_LEN as i64,
781 ),
782 (
783 "UpdateSettings",
784 "attendance_statuses",
785 "maxItems",
786 MAX_SETTINGS_LIST_LEN as i64,
787 ),
788 (
789 "UpdateSettings",
790 "grade_bands",
791 "maxItems",
792 MAX_GRADE_BANDS as i64,
793 ),
794 (
795 "UpdateSettings",
796 "max_file_bytes",
797 "minimum",
798 MIN_MAX_FILE_BYTES,
799 ),
800 (
801 "UpdateSettings",
802 "max_file_bytes",
803 "maximum",
804 MAX_MAX_FILE_BYTES,
805 ),
806 (
807 "UpdateSettings",
808 "chatbot_history_turns",
809 "minimum",
810 MIN_CHATBOT_HISTORY_TURNS,
811 ),
812 (
813 "UpdateSettings",
814 "chatbot_history_turns",
815 "maximum",
816 MAX_CHATBOT_HISTORY_TURNS,
817 ),
818 (
819 "UpdateSettings",
820 "max_chatbot_threads",
821 "minimum",
822 MIN_MAX_CHATBOT_THREADS,
823 ),
824 (
825 "UpdateSettings",
826 "max_chatbot_threads",
827 "maximum",
828 MAX_MAX_CHATBOT_THREADS,
829 ),
830 (
831 "UpdateSettings",
832 "max_chatbot_message_len",
833 "minimum",
834 MIN_MAX_CHATBOT_MESSAGE_LEN,
835 ),
836 (
837 "UpdateSettings",
838 "max_chatbot_message_len",
839 "maximum",
840 MAX_MAX_CHATBOT_MESSAGE_LEN,
841 ),
842 // --- the devamsızlık axes: the branş vocabulary, what an absence may
843 // be excused as, and the per-dönem day limits. The two lists are
844 // school policy like `exam_kinds`, so they carry the same bounds; the
845 // limits are days, bounded so a typo cannot disable the rule.
846 (
847 "UpdateSettings",
848 "branches",
849 "maxItems",
850 MAX_SETTINGS_LIST_LEN as i64,
851 ),
852 (
853 "UpdateSettings",
854 "excuse_kinds",
855 "maxItems",
856 MAX_SETTINGS_LIST_LEN as i64,
857 ),
858 ("UpdateSettings", "max_excused_absent_days", "minimum", 0),
859 (
860 "UpdateSettings",
861 "max_excused_absent_days",
862 "maximum",
863 MAX_ABSENCE_DAYS,
864 ),
865 ("UpdateSettings", "max_unexcused_absent_days", "minimum", 0),
866 (
867 "UpdateSettings",
868 "max_unexcused_absent_days",
869 "maximum",
870 MAX_ABSENCE_DAYS,
871 ),
872 // The read side publishes the same two lists, and the bound has to
873 // hold on both or a client validating a `GET` against them is wrong.
874 (
875 "SettingsResponse",
876 "branches",
877 "maxItems",
878 MAX_SETTINGS_LIST_LEN as i64,
879 ),
880 (
881 "SettingsResponse",
882 "excuse_kinds",
883 "maxItems",
884 MAX_SETTINGS_LIST_LEN as i64,
885 ),
886 // --- food program (the school-editable lists live in /settings) ---
887 (
888 "MealSlotDto",
889 "name",
890 "maxLength",
891 MAX_SETTINGS_ITEM_LEN as i64,
892 ),
893 ("MealSlotDto", "serving_minute", "minimum", 0),
894 (
895 "MealSlotDto",
896 "serving_minute",
897 "maximum",
898 MAX_MEAL_SERVING_MINUTE,
899 ),
900 (
901 "UpdateSettings",
902 "meal_slots",
903 "maxItems",
904 MAX_SETTINGS_LIST_LEN as i64,
905 ),
906 (
907 "UpdateSettings",
908 "dietary_tags",
909 "maxItems",
910 MAX_SETTINGS_LIST_LEN as i64,
911 ),
912 ("UpdateSettings", "meal_cancel_cutoff_minutes", "minimum", 0),
913 (
914 "UpdateSettings",
915 "meal_cancel_cutoff_minutes",
916 "maximum",
917 MAX_MEAL_CANCEL_CUTOFF_MINUTES,
918 ),
919 // --- menus and dishes ---
920 // `date` is a fixed-width `YYYY-MM-DD`, so both length bounds are 10 —
921 // the shape itself, not a constant anyone could tune.
922 ("CreateMenu", "date", "minLength", 10),
923 ("CreateMenu", "date", "maxLength", 10),
924 ("CreateMenu", "capacity", "minimum", 0),
925 ("CreateMenu", "capacity", "maximum", MAX_MENU_CAPACITY),
926 ("UpdateMenu", "capacity", "minimum", 0),
927 ("UpdateMenu", "capacity", "maximum", MAX_MENU_CAPACITY),
928 ("CreateDish", "price_minor", "minimum", 0),
929 ("UpdateDish", "price_minor", "minimum", 0),
930 ("CreateDish", "name", "maxLength", MAX_DISH_NAME_LEN as i64),
931 ("UpdateDish", "name", "maxLength", MAX_DISH_NAME_LEN as i64),
932 (
933 "CreateDish",
934 "description",
935 "maxLength",
936 MAX_DISH_DESCRIPTION_LEN as i64,
937 ),
938 (
939 "UpdateDish",
940 "description",
941 "maxLength",
942 MAX_DISH_DESCRIPTION_LEN as i64,
943 ),
944 ("CreateDish", "price_minor", "maximum", MAX_DISH_PRICE_MINOR),
945 ("UpdateDish", "price_minor", "maximum", MAX_DISH_PRICE_MINOR),
946 ("CreateDish", "tags", "maxItems", MAX_DISH_TAGS as i64),
947 ("UpdateDish", "tags", "maxItems", MAX_DISH_TAGS as i64),
948 (
949 "UpdateDietaryProfile",
950 "tags",
951 "maxItems",
952 MAX_DIETARY_TAGS as i64,
953 ),
954 (
955 "UpdateDietaryProfile",
956 "note",
957 "maxLength",
958 MAX_DIETARY_NOTE_LEN as i64,
959 ),
960 ("RecordCredit", "amount_minor", "minimum", 1),
961 (
962 "RecordCredit",
963 "amount_minor",
964 "maximum",
965 MAX_LEDGER_AMOUNT_MINOR,
966 ),
967 (
968 "RecordCredit",
969 "method",
970 "maxLength",
971 MAX_LEDGER_METHOD_LEN as i64,
972 ),
973 (
974 "RecordCredit",
975 "note",
976 "maxLength",
977 MAX_LEDGER_NOTE_LEN as i64,
978 ),
979 ("RecordCredit", "request_key", "minLength", 1),
980 (
981 "RecordCredit",
982 "request_key",
983 "maxLength",
984 MAX_PAYMENT_REQUEST_KEY_LEN as i64,
985 ),
986 // --- school payments: fee plans and the payment ledger ---
987 ("InstallmentBody", "amount_minor", "minimum", 1),
988 (
989 "InstallmentBody",
990 "amount_minor",
991 "maximum",
992 MAX_LEDGER_AMOUNT_MINOR,
993 ),
994 ("InstallmentBody", "due_at", "minimum", 0),
995 (
996 "CreateFeePlan",
997 "name",
998 "maxLength",
999 MAX_FEE_PLAN_NAME_LEN as i64,
1000 ),
1001 ("CreateFeePlan", "installments", "minItems", 1),
1002 (
1003 "CreateFeePlan",
1004 "installments",
1005 "maxItems",
1006 MAX_FEE_PLAN_INSTALLMENTS as i64,
1007 ),
1008 (
1009 "UpdateFeePlan",
1010 "name",
1011 "maxLength",
1012 MAX_FEE_PLAN_NAME_LEN as i64,
1013 ),
1014 ("UpdateFeePlan", "installments", "minItems", 1),
1015 (
1016 "UpdateFeePlan",
1017 "installments",
1018 "maxItems",
1019 MAX_FEE_PLAN_INSTALLMENTS as i64,
1020 ),
1021 (
1022 "AssignFeePlan",
1023 "student_ids",
1024 "maxItems",
1025 MAX_FEE_PLAN_ASSIGN_STUDENTS as i64,
1026 ),
1027 ("RecordPayment", "amount_minor", "minimum", 1),
1028 (
1029 "RecordPayment",
1030 "amount_minor",
1031 "maximum",
1032 MAX_LEDGER_AMOUNT_MINOR,
1033 ),
1034 (
1035 "RecordPayment",
1036 "method",
1037 "maxLength",
1038 MAX_LEDGER_METHOD_LEN as i64,
1039 ),
1040 (
1041 "RecordPayment",
1042 "note",
1043 "maxLength",
1044 MAX_LEDGER_NOTE_LEN as i64,
1045 ),
1046 ("RecordPayment", "request_key", "minLength", 1),
1047 (
1048 "RecordPayment",
1049 "request_key",
1050 "maxLength",
1051 MAX_PAYMENT_REQUEST_KEY_LEN as i64,
1052 ),
1053 ("RecordRefund", "amount_minor", "minimum", 1),
1054 (
1055 "RecordRefund",
1056 "amount_minor",
1057 "maximum",
1058 MAX_LEDGER_AMOUNT_MINOR,
1059 ),
1060 (
1061 "RecordRefund",
1062 "method",
1063 "maxLength",
1064 MAX_LEDGER_METHOD_LEN as i64,
1065 ),
1066 (
1067 "RecordRefund",
1068 "note",
1069 "maxLength",
1070 MAX_LEDGER_NOTE_LEN as i64,
1071 ),
1072 ("RecordRefund", "request_key", "minLength", 1),
1073 (
1074 "RecordRefund",
1075 "request_key",
1076 "maxLength",
1077 MAX_PAYMENT_REQUEST_KEY_LEN as i64,
1078 ),
1079 (
1080 "RecordReversal",
1081 "note",
1082 "maxLength",
1083 MAX_LEDGER_NOTE_LEN as i64,
1084 ),
1085 ("CreateTerm", "name", "maxLength", MAX_TERM_NAME_LEN as i64),
1086 ("UpdateTerm", "name", "maxLength", MAX_TERM_NAME_LEN as i64),
1087 (
1088 "SendChatbotMessage",
1089 "content",
1090 "maxLength",
1091 MAX_CHATBOT_MESSAGE_LEN as i64,
1092 ),
1093 // --- chatbot thread titles (constant promoted out of
1094 // domain/chatbot_thread.rs, where it escaped both surfaces) ---
1095 (
1096 "CreateChatbotThread",
1097 "title",
1098 "maxLength",
1099 MAX_CHATBOT_THREAD_TITLE_LEN as i64,
1100 ),
1101 (
1102 "RenameChatbotThread",
1103 "title",
1104 "maxLength",
1105 MAX_CHATBOT_THREAD_TITLE_LEN as i64,
1106 ),
1107 // --- the RAG nest reuses the chatbot's shapes and its school knobs:
1108 // the same title cap and the same per-message character cap ---
1109 (
1110 "CreateRagThread",
1111 "title",
1112 "maxLength",
1113 MAX_CHATBOT_THREAD_TITLE_LEN as i64,
1114 ),
1115 (
1116 "RenameRagThread",
1117 "title",
1118 "maxLength",
1119 MAX_CHATBOT_THREAD_TITLE_LEN as i64,
1120 ),
1121 (
1122 "SendRagMessage",
1123 "content",
1124 "maxLength",
1125 MAX_CHATBOT_MESSAGE_LEN as i64,
1126 ),
1127 // --- whiteboards ---
1128 (
1129 "CreateBoard",
1130 "title",
1131 "maxLength",
1132 MAX_BOARD_TITLE_LEN as i64,
1133 ),
1134 (
1135 "CreateBoard",
1136 "participants",
1137 "maxItems",
1138 MAX_BOARD_PARTICIPANTS as i64,
1139 ),
1140 (
1141 "UpdateBoard",
1142 "title",
1143 "maxLength",
1144 MAX_BOARD_TITLE_LEN as i64,
1145 ),
1146 (
1147 "UpdateBoard",
1148 "participants",
1149 "maxItems",
1150 MAX_BOARD_PARTICIPANTS as i64,
1151 ),
1152 // --- academic years and the class×course instance (the K12 anchor) ---
1153 // A year is named like a term ("2026-2027"), so it shares the term
1154 // name's bound; its two grade fields are şube rungs on the grade
1155 // ladder, bounded like `CreateClass.grade_level`.
1156 (
1157 "CreateYear",
1158 "name",
1159 "maxLength",
1160 MAX_ACADEMIC_YEAR_NAME_LEN as i64,
1161 ),
1162 (
1163 "UpdateYear",
1164 "name",
1165 "maxLength",
1166 MAX_ACADEMIC_YEAR_NAME_LEN as i64,
1167 ),
1168 (
1169 "PromotionBody",
1170 "from_grade",
1171 "minimum",
1172 MIN_GRADE_LEVEL as i64,
1173 ),
1174 (
1175 "PromotionBody",
1176 "from_grade",
1177 "maximum",
1178 MAX_GRADE_LEVEL as i64,
1179 ),
1180 (
1181 "PromotionBody",
1182 "to_grade",
1183 "minimum",
1184 MIN_GRADE_LEVEL as i64,
1185 ),
1186 (
1187 "PromotionBody",
1188 "to_grade",
1189 "maximum",
1190 MAX_GRADE_LEVEL as i64,
1191 ),
1192 // The instance's weekly hours: the karne weight, bounded so one
1193 // instance cannot be made to dominate the year average by a typo.
1194 ("UpdateInstance", "ders_saati", "minimum", MIN_DERS_SAATI),
1195 ("UpdateInstance", "ders_saati", "maximum", MAX_DERS_SAATI),
1196 // The holiday calendar's one free-text field, and the optional topic
1197 // a weekly-plan slot may stamp onto every lesson it generates.
1198 (
1199 "CreateHoliday",
1200 "name",
1201 "maxLength",
1202 MAX_HOLIDAY_NAME_LEN as i64,
1203 ),
1204 (
1205 "UpdateHoliday",
1206 "name",
1207 "maxLength",
1208 MAX_HOLIDAY_NAME_LEN as i64,
1209 ),
1210 ("CreateSlot", "topic", "maxLength", MAX_SESSION_TOPIC_LEN as i64),
1211 // The offering spine (course × grade_level templates) and the
1212 // per-class instance overrides: same bounds as the catalog course
1213 // they inherit from.
1214 ("CreateOffering", "grade_level", "minimum", MIN_GRADE_LEVEL as i64),
1215 ("CreateOffering", "grade_level", "maximum", MAX_GRADE_LEVEL as i64),
1216 ("CreateOffering", "title", "maxLength", MAX_COURSE_TITLE_LEN as i64),
1217 (
1218 "CreateOffering",
1219 "description",
1220 "maxLength",
1221 MAX_COURSE_DESCRIPTION_LEN as i64,
1222 ),
1223 ("CreateOffering", "default_ders_saati", "minimum", MIN_DERS_SAATI),
1224 ("CreateOffering", "default_ders_saati", "maximum", MAX_DERS_SAATI),
1225 ("UpdateOffering", "title", "maxLength", MAX_COURSE_TITLE_LEN as i64),
1226 (
1227 "UpdateOffering",
1228 "description",
1229 "maxLength",
1230 MAX_COURSE_DESCRIPTION_LEN as i64,
1231 ),
1232 ("UpdateOffering", "default_ders_saati", "minimum", MIN_DERS_SAATI),
1233 ("UpdateOffering", "default_ders_saati", "maximum", MAX_DERS_SAATI),
1234 ("UpdateInstance", "title", "maxLength", MAX_COURSE_TITLE_LEN as i64),
1235 (
1236 "UpdateInstance",
1237 "description",
1238 "maxLength",
1239 MAX_COURSE_DESCRIPTION_LEN as i64,
1240 ),
1241 ]
1242}
1243
1244#[tokio::test]
1245async fn published_bounds_match_the_constants() {
1246 let spec = spec().await;
1247 let schemas = &spec["components"]["schemas"];
1248
1249 let mut wrong = Vec::new();
1250 for (schema, field, keyword, want) in expectations() {
1251 let got = schemas[schema]["properties"][field][keyword].as_i64();
1252 if got != Some(want) {
1253 wrong.push(format!(
1254 " {schema}.{field}: spec says {keyword}={got:?}, constant says {want}"
1255 ));
1256 }
1257 }
1258
1259 assert!(
1260 wrong.is_empty(),
1261 "the OpenAPI spec disagrees with src/constant.rs — a client generating \
1262 validators from it would enforce the wrong rule:\n{}\n\nutoipa takes \
1263 literals only, so fix the `#[schema(...)]` attribute to match the constant.",
1264 wrong.join("\n")
1265 );
1266}
1267
1268/// Every JSON-bodied operation must publish its `422`.
1269///
1270/// axum's `Json` extractor answers `422 Unprocessable Entity` whenever the body
1271/// parses as JSON but does not fit the DTO — a number where a string belongs, a
1272/// missing required field, or (on the three `deny_unknown_fields` DTOs) a key
1273/// the request does not accept. That is a status the server really returns on
1274/// *every* route taking a JSON body, so a generated client that has no case for
1275/// it will mishandle the most common client mistake there is. (`400` is a
1276/// different failure: a body that is not JSON at all, or one whose values are
1277/// well-typed but violate a domain rule — those already carry an `{error}`
1278/// payload and their own declarations.)
1279///
1280/// Hand-applying that declaration across ~24 files drifts the moment someone
1281/// adds a route, so the emitted document is what gets asserted, not the source:
1282/// a new JSON-bodied operation fails this test until it declares its `422`.
1283/// Multipart operations are out of scope on purpose — their rejection is
1284/// `400`, and they are checked by the same walk below.
1285#[tokio::test]
1286async fn every_json_body_operation_declares_422() {
1287 let spec = spec().await;
1288
1289 let mut missing = Vec::new();
1290 let mut wrongly_declared = Vec::new();
1291 for (path, item) in spec["paths"].as_object().expect("paths").iter() {
1292 for (method, operation) in item.as_object().expect("path item").iter() {
1293 let Some(content) = operation["requestBody"]["content"].as_object() else {
1294 continue;
1295 };
1296 let declares_422 = operation["responses"]["422"].is_object();
1297 if content.contains_key("application/json") {
1298 if !declares_422 {
1299 missing.push(format!(" {} {path}", method.to_uppercase()));
1300 }
1301 } else if declares_422 {
1302 wrongly_declared.push(format!(
1303 " {} {path} ({})",
1304 method.to_uppercase(),
1305 content.keys().cloned().collect::<Vec<_>>().join(", ")
1306 ));
1307 }
1308 }
1309 }
1310
1311 assert!(
1312 missing.is_empty(),
1313 "{} operation(s) take a JSON body but do not declare the `422` axum answers \
1314 when that body does not fit the DTO — a generated client has no case for a \
1315 status the server really returns:\n{}\n\nAdd \
1316 `(status = 422, description = \"…\")` to each `responses(...)` block.",
1317 missing.len(),
1318 missing.join("\n")
1319 );
1320 assert!(
1321 wrongly_declared.is_empty(),
1322 "{} non-JSON operation(s) declare a `422` they never return — a malformed \
1323 multipart body is rejected with `400`:\n{}",
1324 wrongly_declared.len(),
1325 wrongly_declared.join("\n")
1326 );
1327}
1328
1329#[tokio::test]
1330async fn every_page_limit_param_matches_its_constant() {
1331 // `#[param(maximum = 500)]` is written out beside MAX_PAGE_LIMIT, and
1332 // constant.rs merely *asks* a human to keep the two in step. This makes
1333 // that request enforceable.
1334 //
1335 // EVERY `limit` parameter, not the first one found: `src/web/page.rs` is
1336 // the shared one, but `src/web/users.rs` declares its own search paging
1337 // with the literal repeated. Checking one would have left the other free
1338 // to drift — which is exactly the bug this test was written to prevent.
1339 let spec = spec().await;
1340
1341 let limits: Vec<_> = spec["paths"]
1342 .as_object()
1343 .expect("paths")
1344 .values()
1345 .filter_map(|path| path.as_object())
1346 .flat_map(|path| path.values())
1347 .filter_map(|op| op["parameters"].as_array())
1348 .flatten()
1349 .filter(|param| param["name"] == "limit")
1350 .collect();
1351
1352 assert!(
1353 !limits.is_empty(),
1354 "no endpoint publishes a `limit` query parameter — the paging contract vanished"
1355 );
1356
1357 let drifted: Vec<String> = limits
1358 .iter()
1359 .filter(|param| param["schema"]["maximum"].as_i64() != Some(MAX_PAGE_LIMIT))
1360 .map(|param| format!(" {:?}", param["schema"]["maximum"]))
1361 .collect();
1362
1363 assert!(
1364 drifted.is_empty(),
1365 "{} of {} published `limit` parameters disagree with MAX_PAGE_LIMIT ({}):\n{}\n\n\
1366 Update the `#[param(maximum = ...)]` that drifted (src/web/page.rs is the shared \
1367 one; src/web/users.rs declares its own).",
1368 drifted.len(),
1369 limits.len(),
1370 MAX_PAGE_LIMIT,
1371 drifted.join("\n")
1372 );
1373}
1374
1375/// Every `#[schema(...)]` bound in the web layer must have a row in
1376/// [`expectations`] — otherwise the table is itself a mirror that silently
1377/// lags, and a new annotation gets published with nothing checking it.
1378///
1379/// This is not hypothetical: the `CreateHomework.assigned` row was added by a
1380/// text substitution that silently matched nothing after rustfmt rewrapped the
1381/// anchor line. The suite stayed green with the row missing. This test is what
1382/// catches that class.
1383#[test]
1384fn expectations_cover_every_annotation() {
1385 let root = env!("CARGO_MANIFEST_DIR");
1386 let keywords = [
1387 "max_length",
1388 "min_length",
1389 "minimum",
1390 "maximum",
1391 "min_items",
1392 "max_items",
1393 ];
1394
1395 let mut annotated = 0;
1396 // Walk sub-directories too: a resource split into `web/<x>/` (exams) keeps
1397 // its annotations, and a flat read_dir would silently stop counting them.
1398 let mut dirs = vec![format!("{root}/src/web")];
1399 while let Some(dir) = dirs.pop() {
1400 for entry in std::fs::read_dir(&dir).expect("read src/web") {
1401 let path = entry.expect("dir entry").path();
1402 if path.is_dir() {
1403 dirs.push(path.to_string_lossy().into_owned());
1404 continue;
1405 }
1406 if path.extension().is_none_or(|ext| ext != "rs") {
1407 continue;
1408 }
1409 let source = std::fs::read_to_string(&path).expect("read source");
1410 // Scan whole attributes, not lines: rustfmt wraps a long
1411 // `#[schema(example = "…", max_length = 5_000)]` across several lines,
1412 // and a line-based count silently misses the wrapped keyword.
1413 //
1414 // `#[param(...)]` bounds are query parameters, covered by
1415 // `every_page_limit_param_matches_its_constant` instead.
1416 for (at, _) in source.match_indices("#[schema(") {
1417 let rest = &source[at..];
1418 let end = rest.find(")]").map_or(rest.len(), |end| end + 2);
1419 let attribute = &rest[..end];
1420 annotated += keywords
1421 .iter()
1422 .filter(|kw| attribute.contains(&format!("{kw} = ")))
1423 .count();
1424 }
1425 }
1426 }
1427
1428 assert_eq!(
1429 annotated,
1430 expectations().len(),
1431 "src/web/ carries {annotated} `#[schema(...)]` bounds but the expectations table \
1432 has {} rows — every annotation needs a row, or it is published with nothing \
1433 asserting it still matches its constant.",
1434 expectations().len()
1435 );
1436}
1437
1438/// README.md quotes how many bounds this suite checks — a hand-kept copy of
1439/// [`expectations`]`.len()`, and one that had already gone stale twice before
1440/// anything watched it. This is that watcher.
1441#[test]
1442fn the_readme_states_the_real_bound_count() {
1443 // Anchored on the sentence itself, not a line number or a loose digit
1444 // scan: the README is 73KB and full of other numbers.
1445 const ANCHOR: &str = "`tests/spec_bounds.rs` builds the OpenAPI document, reads all ";
1446 let readme = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md"))
1447 .expect("read README.md");
1448 let at = readme.find(ANCHOR).unwrap_or_else(|| {
1449 panic!(
1450 "README.md no longer contains the sentence this test reads:\n \"{ANCHOR}…\"\n\n\
1451 It states how many published bounds this suite checks ({} today). Restore that \
1452 wording, or move the count and re-anchor this test on its new phrasing.",
1453 expectations().len()
1454 )
1455 });
1456 let stated: String = readme[at + ANCHOR.len()..]
1457 .chars()
1458 .take_while(char::is_ascii_digit)
1459 .collect();
1460
1461 assert_eq!(
1462 stated.parse::<usize>().ok(),
1463 Some(expectations().len()),
1464 "README.md says this suite checks {stated:?} published bounds, but the expectations \
1465 table has {} rows.\n\nEdit README.md so that sentence reads \"reads all {} published \
1466 bounds\" — the table is the truth, the README is the copy.",
1467 expectations().len(),
1468 expectations().len()
1469 );
1470}
1471
1472/// The three image-meta bodies — exam question images, bank template images,
1473/// and pool question/solution photos — are hand-kept copies of one shape,
1474/// `{content_type, size}`. The write half behind them is shared
1475/// (`src/web/image.rs`), but the DTOs stay three types because their *names*
1476/// are the published contract, so nothing but this comparison of the emitted
1477/// JSON stops one of them from quietly growing a field the others lack.
1478#[tokio::test]
1479async fn the_image_meta_bodies_stay_the_same_shape() {
1480 let spec = spec().await;
1481 let schemas = &spec["components"]["schemas"];
1482
1483 // Field names with their JSON type, prose (description/example) stripped —
1484 // the wording is allowed to differ per system, the shape is not.
1485 let shape = |name: &str| -> Vec<String> {
1486 let properties = schemas[name]["properties"]
1487 .as_object()
1488 .unwrap_or_else(|| panic!("{name} is not an object schema — was it renamed?"));
1489 let mut fields: Vec<String> = properties
1490 .iter()
1491 .map(|(field, spec)| format!("{field}: {}/{}", spec["type"], spec["format"]))
1492 .collect();
1493 fields.sort();
1494 let mut required: Vec<String> = schemas[name]["required"]
1495 .as_array()
1496 .map(|items| items.iter().map(|item| item.to_string()).collect())
1497 .unwrap_or_default();
1498 required.sort();
1499 fields.push(format!("required: {required:?}"));
1500 fields
1501 };
1502
1503 let want = shape("ImageMetaResponse");
1504 for other in ["BankImageMeta", "PoolImageMeta", "ProfileAvatar"] {
1505 assert_eq!(
1506 want,
1507 shape(other),
1508 "{other} has drifted from ImageMetaResponse — the image-meta bodies are \
1509 copies of one shape and must be changed together"
1510 );
1511 }
1512}
1513
1514/// The class refusal codes are a **published** vocabulary: a blueprint pump
1515/// reports them as a skip `reason`, and the two manual attach routes answer
1516/// them as the `code` on their `409`. A client branches on them *per route*,
1517/// and the two ceiling codes are not the same on the two attach axes — a full
1518/// roster and a full course list are different refusals — so this asserts each
1519/// route's `409` names **exactly** its own set, and that the whole vocabulary
1520/// is accounted for on the `SkipResponse.reason` field that documents it.
1521///
1522/// Anywhere-in-the-document containment was the earlier shape and could not
1523/// fail: `course_full` survived as a `#[schema(example)]` and `duplicate` in
1524/// prose, so a code dropped from a `409` description, moved to the wrong route
1525/// or added undocumented all passed.
1526///
1527/// `course_full` itself is gone with the seat claim: an instance no longer
1528/// holds a capacity, so a full course is not a refusal any more.
1529#[tokio::test]
1530async fn the_class_refusal_codes_stay_published() {
1531 let spec = spec().await;
1532
1533 // Every backticked snake_case word in a description, minus the terms that
1534 // are not codes — so a code added to (or moved into) a description shows up
1535 // here without the test being told about it.
1536 let quoted = |text: &str| -> Vec<String> {
1537 text.split('`')
1538 .skip(1)
1539 .step_by(2)
1540 .filter(|word| {
1541 word.chars().all(|c| c.is_ascii_lowercase() || c == '_')
1542 && !matches!(*word, "code" | "max_class_members" | "max_class_courses")
1543 })
1544 .map(str::to_string)
1545 .collect()
1546 };
1547 let sorted = |mut codes: Vec<String>| -> Vec<String> {
1548 codes.sort();
1549 codes.dedup();
1550 codes
1551 };
1552 let want = |codes: &[&str]| sorted(codes.iter().map(|c| c.to_string()).collect());
1553
1554 // The pump's own half, on the field that carries it. `Attached::refusal_code`
1555 // answers these on the course axis, which is the only axis a pump runs.
1556 let pump = [
1557 "class_deleted",
1558 "course_deleted",
1559 "class_at_course_ceiling",
1560 "class_roster_too_large",
1561 "blueprint_deleted",
1562 ];
1563 // Per route, in the axis's own words: `class_at_*_ceiling` is the axis being
1564 // attached, the `*_too_large` pair the other one. The instance route is
1565 // where a course is attached to a section now; the second path segment of
1566 // its `DELETE` is the instance id, not a course id.
1567 let instances = [
1568 "duplicate",
1569 "class_at_course_ceiling",
1570 "class_roster_too_large",
1571 "academic_year_archived",
1572 ];
1573 let members = [
1574 "duplicate",
1575 "class_at_roster_ceiling",
1576 "class_course_list_too_large",
1577 "linked_course_missing",
1578 "academic_year_archived",
1579 ];
1580 // `academic_year_archived` refuses the whole request up front (the class's
1581 // academic year is archived), so no pump ever *skips* an item for it — it
1582 // belongs on the two routes' 409s, never in `SkipResponse.reason`.
1583 let whole_request = ["academic_year_archived"];
1584
1585 for (path, expected) in [
1586 ("/classes/{id}/instances", instances.as_slice()),
1587 ("/classes/{id}/members", members.as_slice()),
1588 ] {
1589 let description = spec["paths"][path]["post"]["responses"]["409"]["description"]
1590 .as_str()
1591 .unwrap_or_else(|| panic!("{path} must declare a 409 with a description"));
1592 assert_eq!(
1593 sorted(quoted(description)),
1594 want(expected),
1595 "the `409` on POST {path} must name exactly the refusal codes that route \
1596 answers — a client branches on them, and one it never sees documented (or \
1597 one it is promised and never gets) is a branch written against nothing"
1598 );
1599 }
1600
1601 // …and the closed set itself, on the one field that explains all of it: the
1602 // union of both routes plus the pump, so a code documented on one surface
1603 // but missing from the field that collects them all still fails here.
1604 //
1605 // What this cannot catch: a code this file has never heard of. The three
1606 // lists above are hand-kept, so a new `Attached` variant reaches the API
1607 // documented nowhere and every assertion here still passes. The compiler
1608 // holds that end instead — `refusal_code`'s match is exhaustive, so the
1609 // variant cannot be added without a code — and
1610 // `class_blueprint::tests::each_axis_names_the_ceiling_it_actually_hit`
1611 // pins what that code is per axis. Adding one means editing both.
1612 let reason =
1613 spec["components"]["schemas"]["SkipResponse"]["properties"]["reason"]["description"]
1614 .as_str()
1615 .expect("SkipResponse.reason must document the code vocabulary");
1616 let everything: Vec<&str> = pump
1617 .iter()
1618 .chain(instances.iter())
1619 .chain(members.iter())
1620 .copied()
1621 .filter(|code| !whole_request.contains(code))
1622 .collect();
1623 assert_eq!(
1624 sorted(quoted(reason)),
1625 want(&everything),
1626 "`SkipResponse.reason` is where the whole closed vocabulary is written down — \
1627 every code either route or a pump can answer must appear there, and nothing else"
1628 );
1629}