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

exam_question.rs742 lines, 27.2 KiBHistoryRawDownload
1use sqlx::types::Json;
2
3use crate::constant::{
4 MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN, MIN_QUESTION_CHOICES,
5};
6use crate::domain::bank_question::BankQuestionId;
7use crate::domain::exam::ExamId;
8use crate::domain::monotonic_id::next_uuid;
9use crate::domain::subject::SubjectId;
10use crate::error::ValidationError;
11use crate::validate::{validate_question_kind, validate_question_points, validate_required};
12
13#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
14#[sqlx(transparent)]
15pub struct ExamQuestionId(uuid::Uuid);
16
17impl ExamQuestionId {
18 /// Minted from the process-wide monotonic generator, not a plain random
19 /// UUID: the id *is* the question's presentation order
20 /// ([`crate::db::exam_question::list_for_exam`]
21 /// sorts `id ASC`), and a random low half scrambles a burst of saves that
22 /// lands inside one millisecond.
23 pub fn generate() -> Self {
24 Self(next_uuid())
25 }
26
27 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
28 /// cannot take the newtype. Static `query!` binds take `self` directly.
29 pub fn uuid(&self) -> uuid::Uuid {
30 self.0
31 }
32
33 /// Parses a wire key. A key that is not a UUID parses as the nil UUID,
34 /// which matches no row.
35 pub fn from_key(key: &str) -> Self {
36 Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil()))
37 }
38
39 pub fn key(&self) -> String {
40 self.0.to_string()
41 }
42}
43
44#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
45#[sqlx(transparent)]
46pub struct QuestionText(String);
47
48impl QuestionText {
49 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
50 validate_required("text", value, MAX_QUESTION_TEXT_LEN)?;
51 Ok(Self(value.to_string()))
52 }
53
54 pub fn as_str(&self) -> &str {
55 &self.0
56 }
57}
58
59/// A validated question kind: `choice` (pick one option, auto-scorable) or
60/// `text` (free text, judged by the grader).
61#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
62#[sqlx(transparent)]
63pub struct QuestionKind(String);
64
65impl QuestionKind {
66 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
67 validate_question_kind(value)?;
68 Ok(Self(value.to_string()))
69 }
70
71 pub fn as_str(&self) -> &str {
72 &self.0
73 }
74}
75
76/// A validated question weight in the auto-score, held to
77/// `[MIN_QUESTION_POINTS, MAX_QUESTION_POINTS]`.
78#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
79#[sqlx(transparent)]
80pub struct QuestionPoints(i64);
81
82impl QuestionPoints {
83 pub fn try_new(value: i64) -> Result<Self, ValidationError> {
84 validate_question_points(value)?;
85 Ok(Self(value))
86 }
87
88 pub fn as_i64(&self) -> i64 {
89 self.0
90 }
91}
92
93/// One option's text: non-blank, at most `MAX_CHOICE_TEXT_LEN` characters.
94#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type, serde::Serialize, serde::Deserialize)]
95#[sqlx(transparent)]
96pub struct ChoiceText(String);
97
98impl ChoiceText {
99 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
100 validate_required("choice", value, MAX_CHOICE_TEXT_LEN)?;
101 Ok(Self(value.to_string()))
102 }
103
104 pub fn as_str(&self) -> &str {
105 &self.0
106 }
107}
108
109/// An option's stable identity — a server-minted UUID, never reused, never
110/// taken from client input (it becomes part of an image row's slot key and of
111/// a URL path, so a client-shaped value would be an injection surface).
112///
113/// This id is the whole point of the choice remodel. `correct`, the per-option
114/// pictures, and a student's `selected` all name an option *by id*, so
115/// reordering the list or deleting an option moves none of them. They used to
116/// be parallel arrays keyed by position, where any edit to the list silently
117/// re-pointed the others.
118///
119/// Stored as a bare string: it travels inside the choices JSON and names a
120/// slot in the image tables' `TEXT` columns.
121#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type, serde::Serialize, serde::Deserialize)]
122#[sqlx(transparent)]
123pub struct ChoiceId(String);
124
125impl ChoiceId {
126 /// The process-wide monotonic generator, like every other id in the crate.
127 /// Nothing here reads this one as a clock — options are ordered by their
128 /// position in the stored `Vec`, never by id — but a second id convention
129 /// is a second thing to get wrong, and a v4 is one no reader has to know
130 /// about.
131 fn generate() -> Self {
132 Self(next_uuid().to_string())
133 }
134
135 pub fn as_str(&self) -> &str {
136 &self.0
137 }
138}
139
140/// One option of a choice question: its identity plus its text. Stored inside
141/// the `choices` JSONB column, in list order.
142#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
143pub struct Choice {
144 id: ChoiceId,
145 text: ChoiceText,
146}
147
148impl Choice {
149 pub fn get_id(&self) -> &ChoiceId {
150 &self.id
151 }
152
153 pub fn get_text(&self) -> &ChoiceText {
154 &self.text
155 }
156}
157
158/// One option as a client submits it. `id` is the option's *key within this
159/// payload* — see [`QuestionSpec::try_new`] for how it is resolved.
160#[derive(Debug, Clone)]
161pub struct ChoiceInput {
162 pub id: Option<String>,
163 pub text: String,
164}
165
166/// The kind-dependent fields of a question, validated as a unit — they only
167/// make sense together. `try_new` is the sole constructor, so a `QuestionSpec`
168/// in hand always satisfies:
169///
170/// - `text` → no `choices`, no `correct` (the grader judges the answer),
171/// - `choice` → 2–10 `choices` plus a `correct` naming one of them.
172#[derive(Debug, Clone)]
173pub struct QuestionSpec {
174 pub(crate) kind: QuestionKind,
175 pub(crate) choices: Option<Vec<Choice>>,
176 pub(crate) correct: Option<ChoiceId>,
177}
178
179impl QuestionSpec {
180 /// Validate the kind-dependent fields as a unit and resolve each submitted
181 /// option to a stable [`ChoiceId`].
182 ///
183 /// **The identity rule, one sentence:** every submitted choice has a key —
184 /// its `id` if one was sent — and a key that matches one of `existing` *is*
185 /// that stored option (same id, so its picture survives); any other key
186 /// names a brand-new option, whose submitted string is used only to resolve
187 /// `correct` inside this payload and is never stored.
188 ///
189 /// `existing` is the question's stored choices (`&[]` on create, so every
190 /// option there is new and every id is minted here). `correct` names one of
191 /// the submitted keys.
192 ///
193 /// Why an unrecognised id mints instead of failing: `correct` has to be
194 /// settable on create, where nothing is stored yet, so a client must be
195 /// able to label an option the server has never seen. The failure mode is
196 /// benign and visible — a stale id degrades to "this is a new option", which
197 /// loses that option's picture but can never steal another option's, since
198 /// it matches no stored id.
199 pub fn try_new(
200 kind: QuestionKind,
201 choices: Option<Vec<ChoiceInput>>,
202 correct: Option<String>,
203 existing: &[Choice],
204 ) -> Result<Self, ValidationError> {
205 let invalid = |field, reason| ValidationError::Invalid { field, reason };
206 let (choices, correct) = match (kind.as_str(), choices) {
207 ("text", Some(_)) => {
208 return Err(invalid("choices", "only choice questions take choices"));
209 }
210 ("text", None) => {
211 if correct.is_some() {
212 return Err(invalid(
213 "correct",
214 "only choice questions take a correct choice",
215 ));
216 }
217 (None, None)
218 }
219 (_, None) => return Err(invalid("choices", "required for a choice question")),
220 (_, Some(inputs)) => {
221 if !(MIN_QUESTION_CHOICES..=MAX_QUESTION_CHOICES).contains(&inputs.len()) {
222 return Err(invalid("choices", "must list 2 to 10 choices"));
223 }
224 let mut resolved: Vec<Choice> = Vec::with_capacity(inputs.len());
225 // Submitted key -> the id it resolved to, so `correct` can name
226 // a fresh option by the label the client gave it.
227 let mut keys: Vec<(String, ChoiceId)> = Vec::new();
228 for input in inputs {
229 let id = match input.id {
230 Some(key) => {
231 if keys.iter().any(|(seen, _)| *seen == key) {
232 return Err(invalid("choices", "duplicate choice id"));
233 }
234 let id = existing
235 .iter()
236 .find(|choice| choice.id.as_str() == key)
237 .map_or_else(ChoiceId::generate, |choice| choice.id.clone());
238 keys.push((key, id.clone()));
239 id
240 }
241 None => ChoiceId::generate(),
242 };
243 resolved.push(Choice {
244 id,
245 text: ChoiceText::try_new(&input.text)?,
246 });
247 }
248 let Some(correct) = correct else {
249 return Err(invalid("correct", "required for a choice question"));
250 };
251 let Some((_, correct)) = keys.into_iter().find(|(key, _)| *key == correct) else {
252 return Err(invalid("correct", "must name one of the choices"));
253 };
254 (Some(resolved), Some(correct))
255 }
256 };
257 Ok(Self {
258 kind,
259 choices,
260 correct,
261 })
262 }
263
264 /// The stored kind-dependent fields as the validated bundle, bypassing
265 /// [`Self::try_new`] — the fields were written through one, so the
266 /// invariants already hold. For merge-on-update and for copying a question
267 /// between the exam and the bank.
268 pub(crate) fn from_stored(
269 kind: QuestionKind,
270 choices: Option<Vec<Choice>>,
271 correct: Option<ChoiceId>,
272 ) -> Self {
273 Self {
274 kind,
275 choices,
276 correct,
277 }
278 }
279
280 pub fn get_kind(&self) -> &QuestionKind {
281 &self.kind
282 }
283
284 /// The validated fields, consumed — for a writer in another module (the
285 /// question bank) that stores the same three columns.
286 pub fn into_parts(self) -> (QuestionKind, Option<Vec<Choice>>, Option<ChoiceId>) {
287 (self.kind, self.choices, self.correct)
288 }
289}
290
291/// One question of an exam. Order within the exam is the id's creation order;
292/// the kind-dependent columns always satisfy the
293/// [`QuestionSpec`] invariants because every write goes through one. Every
294/// question links to a subject of the exam's course, and — since the
295/// course-template system — to one the exam's *instance* actually teaches:
296/// the service validates both halves of that rule
297/// ([`crate::service::subject::in_instance`]) before any write.
298#[derive(Debug, Clone, sqlx::FromRow)]
299pub struct ExamQuestion {
300 pub(crate) id: ExamQuestionId,
301 pub(crate) exam: ExamId,
302 pub(crate) subject: SubjectId,
303 pub(crate) text: QuestionText,
304 pub(crate) kind: QuestionKind,
305 pub(crate) points: QuestionPoints,
306 pub(crate) choices: Option<Json<Vec<Choice>>>,
307 pub(crate) correct: Option<ChoiceId>,
308 /// The bank template this question was created *from*, if it was inserted
309 /// out of the bank. Written once, at insert.
310 pub(crate) from_bank: Option<BankQuestionId>,
311 /// The bank template most recently created *by saving this question* into
312 /// the bank, if any. Written by
313 /// [`crate::db::exam_question::link_banked_as`], repointed by every
314 /// repeat save. Never set by an insert-from-bank: the two directions are
315 /// separate columns precisely so "came from the bank" can't be misread as
316 /// "already saved to the bank".
317 pub(crate) banked_as: Option<BankQuestionId>,
318}
319
320impl ExamQuestion {
321 pub fn get_id(&self) -> &ExamQuestionId {
322 &self.id
323 }
324
325 pub fn get_exam(&self) -> &ExamId {
326 &self.exam
327 }
328
329 pub fn get_subject(&self) -> &SubjectId {
330 &self.subject
331 }
332
333 pub fn get_text(&self) -> &QuestionText {
334 &self.text
335 }
336
337 pub fn get_kind(&self) -> &QuestionKind {
338 &self.kind
339 }
340
341 pub fn get_points(&self) -> QuestionPoints {
342 self.points
343 }
344
345 pub fn get_choices(&self) -> Option<&[Choice]> {
346 self.choices.as_ref().map(|json| json.0.as_slice())
347 }
348
349 pub fn get_correct(&self) -> Option<&ChoiceId> {
350 self.correct.as_ref()
351 }
352
353 pub fn get_from_bank(&self) -> Option<&BankQuestionId> {
354 self.from_bank.as_ref()
355 }
356
357 pub fn get_banked_as(&self) -> Option<&BankQuestionId> {
358 self.banked_as.as_ref()
359 }
360
361 /// The stored kind-dependent fields as the validated bundle (for
362 /// merge-on-update, and for copying into the bank).
363 pub fn spec(&self) -> QuestionSpec {
364 QuestionSpec::from_stored(
365 self.kind.clone(),
366 self.choices.as_ref().map(|json| json.0.clone()),
367 self.correct.clone(),
368 )
369 }
370
371 /// A question constructed without a database, for pure-function tests.
372 #[cfg(test)]
373 pub fn test_new(exam: &ExamId, text: &str, points: i64, spec: QuestionSpec) -> ExamQuestion {
374 ExamQuestion {
375 id: ExamQuestionId::generate(),
376 exam: exam.clone(),
377 subject: SubjectId::generate(),
378 text: QuestionText::try_new(text).unwrap(),
379 points: QuestionPoints::try_new(points).unwrap(),
380 kind: spec.kind,
381 choices: spec.choices.map(Json),
382 correct: spec.correct,
383 from_bank: None,
384 banked_as: None,
385 }
386 }
387}
388
389#[cfg(test)]
390mod tests {
391 use super::*;
392
393 fn kind(value: &str) -> QuestionKind {
394 QuestionKind::try_new(value).unwrap()
395 }
396
397 /// Two options keyed `a` / `b` — the client-side labels a form sends for
398 /// rows the server has never seen.
399 fn two_choices() -> Option<Vec<ChoiceInput>> {
400 Some(vec![
401 ChoiceInput {
402 id: Some("a".into()),
403 text: "yes".into(),
404 },
405 ChoiceInput {
406 id: Some("b".into()),
407 text: "no".into(),
408 },
409 ])
410 }
411
412 fn spec(
413 choices: Option<Vec<ChoiceInput>>,
414 correct: Option<&str>,
415 ) -> Result<QuestionSpec, ValidationError> {
416 QuestionSpec::try_new(kind("choice"), choices, correct.map(str::to_string), &[])
417 }
418
419 /// A teacher saving several questions back to back gets them back in that
420 /// order: `list_for_exam` sorts `id ASC`, so the ids minted inside one
421 /// millisecond have to sort in mint order. Revert `generate` to a plain
422 /// random UUID and this fails — the random bits are redrawn per id, so a
423 /// same-tick burst comes out shuffled.
424 #[tokio::test]
425 async fn ids_sort_in_creation_order() {
426 let ids: Vec<String> = (0..500).map(|_| ExamQuestionId::generate().key()).collect();
427 let mut sorted = ids.clone();
428 sorted.sort();
429 assert_eq!(ids, sorted);
430 }
431
432 #[tokio::test]
433 async fn text_is_required() {
434 assert!(QuestionText::try_new("What is 2 + 2?").is_ok());
435 assert!(QuestionText::try_new("").is_err());
436 assert!(QuestionText::try_new(" ").is_err());
437 assert!(QuestionText::try_new(&"x".repeat(2_001)).is_err());
438 }
439
440 #[tokio::test]
441 async fn kind_must_be_known() {
442 for value in ["choice", "text"] {
443 assert_eq!(QuestionKind::try_new(value).unwrap().as_str(), value);
444 }
445 assert!(QuestionKind::try_new("essay").is_err());
446 }
447
448 #[tokio::test]
449 async fn points_range_is_enforced() {
450 assert_eq!(QuestionPoints::try_new(1).unwrap().as_i64(), 1);
451 assert_eq!(QuestionPoints::try_new(100).unwrap().as_i64(), 100);
452 assert!(QuestionPoints::try_new(0).is_err());
453 assert!(QuestionPoints::try_new(101).is_err());
454 }
455
456 #[tokio::test]
457 async fn choice_text_is_required() {
458 assert!(ChoiceText::try_new("yes").is_ok());
459 assert!(ChoiceText::try_new("").is_err());
460 assert!(ChoiceText::try_new(" ").is_err());
461 assert!(ChoiceText::try_new(&"x".repeat(501)).is_err());
462 }
463
464 #[tokio::test]
465 async fn spec_invariants_hold() {
466 // Text questions carry neither choices nor a correct choice.
467 assert!(QuestionSpec::try_new(kind("text"), None, None, &[]).is_ok());
468 assert!(QuestionSpec::try_new(kind("text"), two_choices(), None, &[]).is_err());
469 assert!(QuestionSpec::try_new(kind("text"), None, Some("a".into()), &[]).is_err());
470
471 // Choice questions need both.
472 assert!(spec(two_choices(), Some("a")).is_ok());
473 assert!(spec(two_choices(), Some("b")).is_ok());
474 assert!(spec(None, None).is_err());
475 assert!(spec(None, Some("a")).is_err());
476 assert!(spec(two_choices(), None).is_err());
477 }
478
479 #[tokio::test]
480 async fn spec_correct_must_name_a_submitted_choice() {
481 assert!(spec(two_choices(), Some("c")).is_err());
482 assert!(spec(two_choices(), Some("")).is_err());
483 // An unlabelled option cannot be marked correct — there is nothing to
484 // name it by until the server's minted id comes back in the response.
485 let unlabelled = Some(vec![
486 ChoiceInput {
487 id: None,
488 text: "yes".into(),
489 },
490 ChoiceInput {
491 id: None,
492 text: "no".into(),
493 },
494 ]);
495 assert!(spec(unlabelled, Some("a")).is_err());
496 }
497
498 #[tokio::test]
499 async fn spec_mints_a_distinct_id_per_choice() {
500 let built = spec(two_choices(), Some("b")).unwrap();
501 let (_, choices, correct) = built.into_parts();
502 let choices = choices.unwrap();
503 // Client labels never reach storage; a minted id is a hyphenated UUID.
504 assert!(choices.iter().all(|c| c.get_id().as_str().len() == 36));
505 assert_ne!(choices[0].get_id(), choices[1].get_id());
506 // `correct` resolved to the *second* option's minted id, by label.
507 assert_eq!(correct.as_ref(), Some(choices[1].get_id()));
508 }
509
510 /// The heart of the remodel: an id that matches a stored option keeps that
511 /// option's identity, so reordering and deleting move nothing.
512 #[tokio::test]
513 async fn existing_ids_are_preserved_across_an_edit() {
514 let stored = spec(two_choices(), Some("a"))
515 .unwrap()
516 .into_parts()
517 .1
518 .unwrap();
519 let (first, second) = (stored[0].get_id().clone(), stored[1].get_id().clone());
520
521 // Resubmit reordered, renaming the first option's text, and marking the
522 // option that used to be second as correct.
523 let edited = QuestionSpec::try_new(
524 kind("choice"),
525 Some(vec![
526 ChoiceInput {
527 id: Some(second.as_str().into()),
528 text: "no".into(),
529 },
530 ChoiceInput {
531 id: Some(first.as_str().into()),
532 text: "YES".into(),
533 },
534 ]),
535 Some(second.as_str().into()),
536 &stored,
537 )
538 .unwrap();
539 let (_, choices, correct) = edited.into_parts();
540 let choices = choices.unwrap();
541 assert_eq!(choices[0].get_id(), &second);
542 assert_eq!(choices[1].get_id(), &first);
543 assert_eq!(choices[1].get_text().as_str(), "YES");
544 assert_eq!(correct.as_ref(), Some(&second));
545 }
546
547 #[tokio::test]
548 async fn spec_rejects_a_duplicate_choice_id() {
549 let dupes = Some(vec![
550 ChoiceInput {
551 id: Some("a".into()),
552 text: "yes".into(),
553 },
554 ChoiceInput {
555 id: Some("a".into()),
556 text: "no".into(),
557 },
558 ]);
559 assert!(spec(dupes, Some("a")).is_err());
560 }
561
562 #[tokio::test]
563 async fn spec_choice_count_is_bounded() {
564 let n = |count: usize| {
565 Some(
566 (0..count)
567 .map(|i| ChoiceInput {
568 id: Some(i.to_string()),
569 text: "option".into(),
570 })
571 .collect::<Vec<_>>(),
572 )
573 };
574 assert!(spec(n(1), Some("0")).is_err());
575 assert!(spec(n(2), Some("0")).is_ok());
576 assert!(spec(n(10), Some("0")).is_ok());
577 assert!(spec(n(11), Some("0")).is_err());
578 }
579
580 /// Generated coverage of the §2-REVISED identity rules. The example tests
581 /// above each pin one hand-picked payload; these generate arbitrary stored
582 /// sets and arbitrary submissions over them (matching keys, stale keys,
583 /// `null` ids, duplicates, blank and oversized texts) and assert the rules
584 /// as one predicate, because every bug this remodel exists to kill lived in
585 /// a *relation* between a submitted option and a stored one.
586 mod props {
587 use super::*;
588 use proptest::prelude::*;
589
590 /// A stored question's options, built the only way they can be: through
591 /// `try_new` on create, so the ids are real minted UUIDs.
592 fn stored_set(n: usize) -> Vec<Choice> {
593 let inputs = (0..n)
594 .map(|i| ChoiceInput {
595 id: Some(format!("s{i}")),
596 text: format!("stored {i}"),
597 })
598 .collect();
599 QuestionSpec::try_new(kind("choice"), Some(inputs), Some("s0".into()), &[])
600 .unwrap()
601 .into_parts()
602 .1
603 .unwrap()
604 }
605
606 /// How a submitted option names itself: as a stored option, as some
607 /// other string (a client-minted label, a stale id, junk), or not at all.
608 #[derive(Debug, Clone)]
609 enum Key {
610 Stored(usize),
611 Other(String),
612 Null,
613 }
614
615 fn key() -> impl Strategy<Value = Key> {
616 use proptest::prelude::*;
617 prop_oneof![
618 4 => (0usize..10).prop_map(Key::Stored),
619 3 => prop_oneof![
620 Just(String::new()),
621 Just("new:1".to_string()),
622 "[a-z0-9]{1,5}",
623 Just("0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f".to_string()),
624 ].prop_map(Key::Other),
625 1 => Just(Key::Null),
626 ]
627 }
628
629 fn text() -> impl Strategy<Value = String> {
630 use proptest::prelude::*;
631 prop_oneof![
632 6 => "[a-z ]{1,6}",
633 1 => Just(String::new()),
634 1 => Just(" ".to_string()),
635 1 => Just("x".repeat(501)),
636 ]
637 }
638
639 proptest! {
640 #![proptest_config(ProptestConfig::with_cases(400))]
641
642 #[test]
643 fn a_matching_key_is_that_choice_and_nothing_else_can_be(
644 stored_n in 2usize..=10,
645 submitted in prop::collection::vec((key(), text()), 0..=12),
646 correct in prop::option::of(key()),
647 ) {
648 let stored = stored_set(stored_n);
649 let name = |k: &Key| match k {
650 Key::Stored(i) => Some(stored[i % stored_n].id.as_str().to_string()),
651 Key::Other(s) => Some(s.clone()),
652 Key::Null => None,
653 };
654 let keys: Vec<Option<String>> = submitted.iter().map(|(k, _)| name(k)).collect();
655 let texts: Vec<String> = submitted.iter().map(|(_, t)| t.clone()).collect();
656 let correct = correct.as_ref().map(|k| name(k).unwrap_or_default());
657
658 let inputs: Vec<ChoiceInput> = keys
659 .iter()
660 .zip(&texts)
661 .map(|(id, text)| ChoiceInput { id: id.clone(), text: text.clone() })
662 .collect();
663 let built = QuestionSpec::try_new(
664 kind("choice"),
665 Some(inputs),
666 correct.clone(),
667 &stored,
668 );
669
670 // Every way a payload can be rejected, stated independently of
671 // the implementation's order of checks.
672 let bad_len = !(MIN_QUESTION_CHOICES..=MAX_QUESTION_CHOICES).contains(&submitted.len());
673 let mut seen: Vec<&String> = Vec::new();
674 let mut dup = false;
675 for k in keys.iter().flatten() {
676 if seen.contains(&k) { dup = true; break; }
677 seen.push(k);
678 }
679 let bad_text = texts.iter().any(|t| t.trim().is_empty() || t.chars().count() > MAX_CHOICE_TEXT_LEN);
680 // `correct` must name a *submitted key*; an option sent with
681 // `id: null` has no key, so it is unnameable.
682 let named = correct.as_ref().is_some_and(|c| keys.iter().flatten().any(|k| k == c));
683
684 if bad_len || dup || bad_text || !named {
685 prop_assert!(built.is_err());
686 return Ok(());
687 }
688
689 let (_, choices, resolved) = built.unwrap().into_parts();
690 let choices = choices.unwrap();
691 prop_assert_eq!(choices.len(), submitted.len());
692
693 let stored_ids: Vec<&str> = stored.iter().map(|c| c.id.as_str()).collect();
694 for (i, choice) in choices.iter().enumerate() {
695 // Order and text are passed through untouched.
696 prop_assert_eq!(choice.text.as_str(), texts[i].as_str());
697 match keys[i].as_deref().and_then(|k| stored.iter().find(|c| c.id.as_str() == k)) {
698 // A key matching a stored choice IS that choice: same
699 // id, so its picture stays with it.
700 Some(existing) => prop_assert_eq!(&choice.id, &existing.id),
701 // Any other key (stale, junk, absent) is a NEW option:
702 // freshly minted, so it can never take over a stored
703 // option's identity or its picture.
704 None => {
705 prop_assert_eq!(choice.id.as_str().len(), 36);
706 prop_assert!(!stored_ids.contains(&choice.id.as_str()));
707 }
708 }
709 }
710 // No id is invented twice.
711 let mut out: Vec<&str> = choices.iter().map(|c| c.id.as_str()).collect();
712 out.sort_unstable();
713 let unique = out.len();
714 out.dedup();
715 prop_assert_eq!(out.len(), unique);
716
717 // `correct` resolves to the option that carried that key.
718 let correct = correct.unwrap();
719 let at = keys.iter().position(|k| k.as_ref() == Some(&correct)).unwrap();
720 prop_assert_eq!(resolved.as_ref(), Some(&choices[at].id));
721 }
722 }
723 }
724
725 #[tokio::test]
726 async fn spec_rejects_blank_or_oversized_choices() {
727 let with = |text: String| {
728 Some(vec![
729 ChoiceInput {
730 id: Some("a".into()),
731 text: "yes".into(),
732 },
733 ChoiceInput {
734 id: Some("b".into()),
735 text,
736 },
737 ])
738 };
739 assert!(spec(with(" ".into()), Some("a")).is_err());
740 assert!(spec(with("x".repeat(501)), Some("a")).is_err());
741 }
742}