| 1 | use sqlx::types::Json; |
| 2 | |
| 3 | use crate::constant::{ |
| 4 | MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN, MIN_QUESTION_CHOICES, |
| 5 | }; |
| 6 | use crate::domain::bank_question::BankQuestionId; |
| 7 | use crate::domain::exam::ExamId; |
| 8 | use crate::domain::monotonic_id::next_uuid; |
| 9 | use crate::domain::subject::SubjectId; |
| 10 | use crate::error::ValidationError; |
| 11 | use crate::validate::{validate_question_kind, validate_question_points, validate_required}; |
| 12 | |
| 13 | #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 14 | #[sqlx(transparent)] |
| 15 | pub struct ExamQuestionId(uuid::Uuid); |
| 16 | |
| 17 | impl ExamQuestionId { |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | pub fn generate() -> Self { |
| 24 | Self(next_uuid()) |
| 25 | } |
| 26 | |
| 27 | |
| 28 | |
| 29 | pub fn uuid(&self) -> uuid::Uuid { |
| 30 | self.0 |
| 31 | } |
| 32 | |
| 33 | |
| 34 | |
| 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)] |
| 46 | pub struct QuestionText(String); |
| 47 | |
| 48 | impl 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 | |
| 60 | |
| 61 | #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 62 | #[sqlx(transparent)] |
| 63 | pub struct QuestionKind(String); |
| 64 | |
| 65 | impl 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 | |
| 77 | |
| 78 | #[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] |
| 79 | #[sqlx(transparent)] |
| 80 | pub struct QuestionPoints(i64); |
| 81 | |
| 82 | impl 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 | |
| 94 | #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type, serde::Serialize, serde::Deserialize)] |
| 95 | #[sqlx(transparent)] |
| 96 | pub struct ChoiceText(String); |
| 97 | |
| 98 | impl 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 | |
| 110 | |
| 111 | |
| 112 | |
| 113 | |
| 114 | |
| 115 | |
| 116 | |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type, serde::Serialize, serde::Deserialize)] |
| 122 | #[sqlx(transparent)] |
| 123 | pub struct ChoiceId(String); |
| 124 | |
| 125 | impl ChoiceId { |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 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 | |
| 141 | |
| 142 | #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] |
| 143 | pub struct Choice { |
| 144 | id: ChoiceId, |
| 145 | text: ChoiceText, |
| 146 | } |
| 147 | |
| 148 | impl 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 | |
| 159 | |
| 160 | #[derive(Debug, Clone)] |
| 161 | pub struct ChoiceInput { |
| 162 | pub id: Option<String>, |
| 163 | pub text: String, |
| 164 | } |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | #[derive(Debug, Clone)] |
| 173 | pub struct QuestionSpec { |
| 174 | pub(crate) kind: QuestionKind, |
| 175 | pub(crate) choices: Option<Vec<Choice>>, |
| 176 | pub(crate) correct: Option<ChoiceId>, |
| 177 | } |
| 178 | |
| 179 | impl QuestionSpec { |
| 180 | |
| 181 | |
| 182 | |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | |
| 196 | |
| 197 | |
| 198 | |
| 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 | |
| 226 | |
| 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 | |
| 265 | |
| 266 | |
| 267 | |
| 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 | |
| 285 | |
| 286 | pub fn into_parts(self) -> (QuestionKind, Option<Vec<Choice>>, Option<ChoiceId>) { |
| 287 | (self.kind, self.choices, self.correct) |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | |
| 292 | |
| 293 | |
| 294 | |
| 295 | |
| 296 | |
| 297 | |
| 298 | #[derive(Debug, Clone, sqlx::FromRow)] |
| 299 | pub 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 | |
| 309 | |
| 310 | pub(crate) from_bank: Option<BankQuestionId>, |
| 311 | |
| 312 | |
| 313 | |
| 314 | |
| 315 | |
| 316 | |
| 317 | pub(crate) banked_as: Option<BankQuestionId>, |
| 318 | } |
| 319 | |
| 320 | impl 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 | |
| 362 | |
| 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 | |
| 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)] |
| 390 | mod tests { |
| 391 | use super::*; |
| 392 | |
| 393 | fn kind(value: &str) -> QuestionKind { |
| 394 | QuestionKind::try_new(value).unwrap() |
| 395 | } |
| 396 | |
| 397 | |
| 398 | |
| 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 | |
| 420 | |
| 421 | |
| 422 | |
| 423 | |
| 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 | |
| 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 | |
| 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 | |
| 484 | |
| 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 | |
| 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 | |
| 507 | assert_eq!(correct.as_ref(), Some(choices[1].get_id())); |
| 508 | } |
| 509 | |
| 510 | |
| 511 | |
| 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 | |
| 522 | |
| 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 | |
| 581 | |
| 582 | |
| 583 | |
| 584 | |
| 585 | |
| 586 | mod props { |
| 587 | use super::*; |
| 588 | use proptest::prelude::*; |
| 589 | |
| 590 | |
| 591 | |
| 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 | |
| 607 | |
| 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 | |
| 671 | |
| 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 | |
| 681 | |
| 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 | |
| 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 | |
| 699 | |
| 700 | Some(existing) => prop_assert_eq!(&choice.id, &existing.id), |
| 701 | |
| 702 | |
| 703 | |
| 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 | |
| 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 | |
| 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 | } |