forge
Explore
Log in

Don't you dare go Hollow

Cargo fmt the tree before the audit fixes

Browse files at this commit

b4a5a006e1ea99f86a8acad3c4f8e39f3b09aceaAhmet Kaan GümüşParent: cf04258
  • style
    • cargo fmt the tree before the audit fixes
Show full message
🎨 style: cargo fmt the tree before the audit fixes

Pure reformatting, no behaviour change: rustfmt wrapping plus its
alphabetical `use`-list reordering across the files that had drifted.
Kept separate so the correctness commits that follow carry only logic.

25 changed files +1102 -290

src/domain/appointment_slot.rsmodified+21 -13
@@ -565,17 +565,23 @@ mod tests {
565 Err(AppError::ConflictOwned(_))565 Err(AppError::ConflictOwned(_))
566 ));566 ));
567 // Touching at the boundary (ends where the next starts) → allowed.567 // Touching at the boundary (ends where the next starts) → allowed.
568- assert!(AppointmentSlot::create(&teacher, at(2_000), at(3_000), None, &db)568+ assert!(
569- .await569+ AppointmentSlot::create(&teacher, at(2_000), at(3_000), None, &db)
570- .is_ok());570+ .await
571- assert!(AppointmentSlot::create(&teacher, at(0), at(1_000), None, &db)571+ .is_ok()
572- .await572+ );
573- .is_ok());573+ assert!(
574+ AppointmentSlot::create(&teacher, at(0), at(1_000), None, &db)
575+ .await
576+ .is_ok()
577+ );
574 // A different teacher sharing the same window is fine.578 // A different teacher sharing the same window is fine.
575 let other = UserId::from_key("t2");579 let other = UserId::from_key("t2");
576- assert!(AppointmentSlot::create(&other, at(1_000), at(2_000), None, &db)580+ assert!(
577- .await581+ AppointmentSlot::create(&other, at(1_000), at(2_000), None, &db)
578- .is_ok());582+ .await
583+ .is_ok()
584+ );
579 }585 }
580 586
581 #[tokio::test]587 #[tokio::test]
@@ -636,9 +642,11 @@ mod tests {
636 .await,642 .await,
637 Err(AppError::ConflictOwned(_))643 Err(AppError::ConflictOwned(_))
638 ));644 ));
639- assert!(AppointmentSlot::list_for_teacher(&teacher, &db)645+ assert!(
640- .await646+ AppointmentSlot::list_for_teacher(&teacher, &db)
641- .unwrap()647+ .await
642- .is_empty());648+ .unwrap()
649+ .is_empty()
650+ );
643 }651 }
644 }652 }
src/domain/bank_question.rsmodified+67 -22
@@ -191,7 +191,11 @@ impl BankQuestion {
191 /// hold — and a round-trip through `try_new` would mint *new* choice ids,191 /// hold — and a round-trip through `try_new` would mint *new* choice ids,
192 /// detaching the copy's `correct` and option pictures from its choices.192 /// detaching the copy's `correct` and option pictures from its choices.
193 pub fn spec(&self) -> QuestionSpec {193 pub fn spec(&self) -> QuestionSpec {
194- QuestionSpec::from_stored(self.kind.clone(), self.choices.clone(), self.correct.clone())194+ QuestionSpec::from_stored(
195+ self.kind.clone(),
196+ self.choices.clone(),
197+ self.correct.clone(),
198+ )
195 }199 }
196 200
197 pub async fn create(201 pub async fn create(
@@ -248,7 +252,10 @@ impl BankQuestion {
248 created.ok_or_else(|| AppError::Internal("failed to create bank question".into()))252 created.ok_or_else(|| AppError::Internal("failed to create bank question".into()))
249 }253 }
250 254
251- pub async fn read(id: &BankQuestionId, db: &Database) -> Result<Option<BankQuestion>, AppError> {255+ pub async fn read(
256+ id: &BankQuestionId,
257+ db: &Database,
258+ ) -> Result<Option<BankQuestion>, AppError> {
252 Ok(db.select(id.record()).await?)259 Ok(db.select(id.record()).await?)
253 }260 }
254 261
@@ -481,8 +488,14 @@ mod tests {
481 QuestionSpec::try_new(488 QuestionSpec::try_new(
482 QuestionKind::try_new("choice").unwrap(),489 QuestionKind::try_new("choice").unwrap(),
483 Some(vec![490 Some(vec![
484- ChoiceInput { id: Some("a".into()), text: "yes".into() },491+ ChoiceInput {
485- ChoiceInput { id: Some("b".into()), text: "no".into() },492+ id: Some("a".into()),
493+ text: "yes".into(),
494+ },
495+ ChoiceInput {
496+ id: Some("b".into()),
497+ text: "no".into(),
498+ },
486 ]),499 ]),
487 Some("b".into()),500 Some("b".into()),
488 &[],501 &[],
@@ -672,7 +685,10 @@ mod tests {
672 685
673 // One statement, so a page costs one round trip — a `;` here would mean686 // One statement, so a page costs one round trip — a `;` here would mean
674 // the per-row N+1 crept back in.687 // the per-row N+1 crept back in.
675- assert!(!USAGE_COUNTS_SQL.contains(';'), "usage_counts must be one statement");688+ assert!(
689+ !USAGE_COUNTS_SQL.contains(';'),
690+ "usage_counts must be one statement"
691+ );
676 692
677 let db = crate::database::init_mem().await.unwrap();693 let db = crate::database::init_mem().await.unwrap();
678 let owner = UserId::generate();694 let owner = UserId::generate();
@@ -725,15 +741,26 @@ mod tests {
725 let counts = BankQuestion::usage_counts(&ids, &db).await.unwrap();741 let counts = BankQuestion::usage_counts(&ids, &db).await.unwrap();
726 assert_eq!(counts.get(used_twice.get_id().key()).copied(), Some(2));742 assert_eq!(counts.get(used_twice.get_id().key()).copied(), Some(2));
727 assert_eq!(counts.get(used_once.get_id().key()).copied(), Some(1));743 assert_eq!(counts.get(used_once.get_id().key()).copied(), Some(1));
728- assert_eq!(counts.get(unused.get_id().key()), None, "unused stays absent");744+ assert_eq!(
745+ counts.get(unused.get_id().key()),
746+ None,
747+ "unused stays absent"
748+ );
729 assert_eq!(counts.len(), 2);749 assert_eq!(counts.len(), 2);
730 750
731 // A template outside the page is never counted into it.751 // A template outside the page is never counted into it.
732- let narrow = BankQuestion::usage_counts(&[used_once.get_id()], &db).await.unwrap();752+ let narrow = BankQuestion::usage_counts(&[used_once.get_id()], &db)
753+ .await
754+ .unwrap();
733 assert_eq!(narrow.len(), 1);755 assert_eq!(narrow.len(), 1);
734 assert_eq!(narrow.get(used_once.get_id().key()).copied(), Some(1));756 assert_eq!(narrow.get(used_once.get_id().key()).copied(), Some(1));
735 // An empty page asks nothing at all.757 // An empty page asks nothing at all.
736- assert!(BankQuestion::usage_counts(&[], &db).await.unwrap().is_empty());758+ assert!(
759+ BankQuestion::usage_counts(&[], &db)
760+ .await
761+ .unwrap()
762+ .is_empty()
763+ );
737 }764 }
738 765
739 #[test]766 #[test]
@@ -796,15 +823,24 @@ mod tests {
796 .unwrap();823 .unwrap();
797 assert_eq!(tail[0].get_text().as_str(), "question 0");824 assert_eq!(tail[0].get_text().as_str(), "question 0");
798 // Text filter runs in SQL, case-insensitively, and narrows `total`.825 // Text filter runs in SQL, case-insensitively, and narrows `total`.
799- let (hits, total) = BankQuestion::list(None, None, None, None, Some("QUESTION 3"), None, 0, &db)826+ let (hits, total) =
800- .await827+ BankQuestion::list(None, None, None, None, Some("QUESTION 3"), None, 0, &db)
801- .unwrap();
802- assert_eq!((hits.len(), total), (1, 1));
803- // Owner filter with nobody's templates.
804- let (none, total) =
805- BankQuestion::list(None, Some(&UserId::generate()), None, None, None, None, 0, &db)
806 .await828 .await
807 .unwrap();829 .unwrap();
830+ assert_eq!((hits.len(), total), (1, 1));
831+ // Owner filter with nobody's templates.
832+ let (none, total) = BankQuestion::list(
833+ None,
834+ Some(&UserId::generate()),
835+ None,
836+ None,
837+ None,
838+ None,
839+ 0,
840+ &db,
841+ )
842+ .await
843+ .unwrap();
808 assert!(none.is_empty());844 assert!(none.is_empty());
809 assert_eq!(total, 0);845 assert_eq!(total, 0);
810 }846 }
@@ -823,15 +859,24 @@ mod tests {
823 )859 )
824 .await860 .await
825 .unwrap();861 .unwrap();
826- for needle in ["istanbul", "İSTANBUL", "İstanbul", "ıstanbul", "ilçe", "ILCE"] {862+ for needle in [
827- let (hits, total) = BankQuestion::list(None, None, None, None, Some(needle), None, 0, &db)863+ "istanbul",
828- .await864+ "İSTANBUL",
829- .unwrap();865+ "İstanbul",
866+ "ıstanbul",
867+ "ilçe",
868+ "ILCE",
869+ ] {
870+ let (hits, total) =
871+ BankQuestion::list(None, None, None, None, Some(needle), None, 0, &db)
872+ .await
873+ .unwrap();
830 assert_eq!((hits.len(), total), (1, 1), "needle {needle} missed");874 assert_eq!((hits.len(), total), (1, 1), "needle {needle} missed");
831 }875 }
832- let (miss, total) = BankQuestion::list(None, None, None, None, Some("ankara"), None, 0, &db)876+ let (miss, total) =
833- .await877+ BankQuestion::list(None, None, None, None, Some("ankara"), None, 0, &db)
834- .unwrap();878+ .await
879+ .unwrap();
835 assert!(miss.is_empty());880 assert!(miss.is_empty());
836 assert_eq!(total, 0);881 assert_eq!(total, 0);
837 }882 }
src/domain/bank_question_image.rsmodified+4 -1
@@ -201,7 +201,10 @@ mod tests {
201 Some(201 Some(
202 ["a", "b", "c"]202 ["a", "b", "c"]
203 .iter()203 .iter()
204- .map(|l| ChoiceInput { id: Some((*l).into()), text: (*l).into() })204+ .map(|l| ChoiceInput {
205+ id: Some((*l).into()),
206+ text: (*l).into(),
207+ })
205 .collect(),208 .collect(),
206 ),209 ),
207 Some("a".into()),210 Some("a".into()),
src/domain/chatbot_message.rsmodified+3 -4
@@ -213,7 +213,8 @@ impl ChatbotMessage {
213 }213 }
214 214
215 async fn insert(message: ChatbotMessage, db: &Database) -> Result<ChatbotMessage, AppError> {215 async fn insert(message: ChatbotMessage, db: &Database) -> Result<ChatbotMessage, AppError> {
216- let created: Option<ChatbotMessage> = db.create(message.id.record()).content(message).await?;216+ let created: Option<ChatbotMessage> =
217+ db.create(message.id.record()).content(message).await?;
217 created.ok_or_else(|| AppError::Internal("failed to create chat message".into()))218 created.ok_or_else(|| AppError::Internal("failed to create chat message".into()))
218 }219 }
219 220
@@ -469,9 +470,7 @@ mod tests {
469 .unwrap();470 .unwrap();
470 }471 }
471 472
472- let whole = ChatbotMessage::list_for_thread(&thread, &db)473+ let whole = ChatbotMessage::list_for_thread(&thread, &db).await.unwrap();
473- .await
474- .unwrap();
475 let tail = ChatbotMessage::list_tail(&thread, TURNS * 2, &db)474 let tail = ChatbotMessage::list_tail(&thread, TURNS * 2, &db)
476 .await475 .await
477 .unwrap();476 .unwrap();
src/domain/chatbot_thread.rsmodified+3 -5
@@ -108,10 +108,7 @@ impl ChatbotThread {
108 created_at: now,108 created_at: now,
109 updated_at: now,109 updated_at: now,
110 };110 };
111- let created: Option<ChatbotThread> = db111+ let created: Option<ChatbotThread> = db.create(thread.id.record()).content(thread).await?;
112- .create(thread.id.record())
113- .content(thread)
114- .await?;
115 created.ok_or_else(|| AppError::Internal("failed to create thread".into()))112 created.ok_or_else(|| AppError::Internal("failed to create thread".into()))
116 }113 }
117 114
@@ -227,7 +224,8 @@ impl ChatbotThread {
227 .await?224 .await?
228 .check()?;225 .check()?;
229 // BEGIN is slot 0; the thread's own DELETE is slot 2.226 // BEGIN is slot 0; the thread's own DELETE is slot 2.
230- let deleted: Option<ChatbotThread> = result.take::<Vec<ChatbotThread>>(2)?.into_iter().next();227+ let deleted: Option<ChatbotThread> =
228+ result.take::<Vec<ChatbotThread>>(2)?.into_iter().next();
231 deleted.ok_or(AppError::NotFound)229 deleted.ok_or(AppError::NotFound)
232 }230 }
233 }231 }
src/domain/course.rsmodified+11 -7
@@ -264,11 +264,7 @@ impl Course {
264 /// so a whole-row save from either side would revert the other. The264 /// so a whole-row save from either side would revert the other. The
265 /// `array::distinct` keeps the assignment idempotent even when two requests265 /// `array::distinct` keeps the assignment idempotent even when two requests
266 /// name the same teacher at once (the early return only sees a stale row).266 /// name the same teacher at once (the early return only sees a stale row).
267- pub async fn assign_teacher(267+ pub async fn assign_teacher(self, teacher: &UserId, db: &Database) -> Result<Course, AppError> {
268- self,
269- teacher: &UserId,
270- db: &Database,
271- ) -> Result<Course, AppError> {
272 if self.is_assigned(teacher) {268 if self.is_assigned(teacher) {
273 return Ok(self);269 return Ok(self);
274 }270 }
@@ -281,7 +277,11 @@ impl Course {
281 .bind(("usr", teacher.record()))277 .bind(("usr", teacher.record()))
282 .await?278 .await?
283 .check()?;279 .check()?;
284- result.take::<Vec<Course>>(0)?.into_iter().next().ok_or(AppError::NotFound)280+ result
281+ .take::<Vec<Course>>(0)?
282+ .into_iter()
283+ .next()
284+ .ok_or(AppError::NotFound)
285 }285 }
286 286
287 /// Drop `teacher` from this course. `None` when they weren't assigned, so287 /// Drop `teacher` from this course. `None` when they weren't assigned, so
@@ -303,7 +303,11 @@ impl Course {
303 .await?303 .await?
304 .check()?;304 .check()?;
305 Ok(Some(305 Ok(Some(
306- result.take::<Vec<Course>>(0)?.into_iter().next().ok_or(AppError::NotFound)?,306+ result
307+ .take::<Vec<Course>>(0)?
308+ .into_iter()
309+ .next()
310+ .ok_or(AppError::NotFound)?,
307 ))311 ))
308 }312 }
309 313
src/domain/course_session.rsmodified+5 -1
@@ -157,7 +157,11 @@ impl CourseSession {
157 .bind(("ends_at", ends_at))157 .bind(("ends_at", ends_at))
158 .await?158 .await?
159 .check()?;159 .check()?;
160- result.take::<Vec<CourseSession>>(0)?.into_iter().next().ok_or(AppError::NotFound)160+ result
161+ .take::<Vec<CourseSession>>(0)?
162+ .into_iter()
163+ .next()
164+ .ok_or(AppError::NotFound)
161 }165 }
162 166
163 /// Delete the session and cascade-remove its roll-call rows.167 /// Delete the session and cascade-remove its roll-call rows.
src/domain/exam.rsmodified+0 -1
@@ -620,4 +620,3 @@ mod tests {
620 assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err());620 assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err());
621 }621 }
622 }622 }
623-
src/domain/exam_answer.rsmodified+4 -1
@@ -312,7 +312,10 @@ mod tests {
312 Some(312 Some(
313 labels313 labels
314 .iter()314 .iter()
315- .map(|l| ChoiceInput { id: Some((*l).into()), text: (*l).into() })315+ .map(|l| ChoiceInput {
316+ id: Some((*l).into()),
317+ text: (*l).into(),
318+ })
316 .collect(),319 .collect(),
317 ),320 ),
318 Some(labels[correct].into()),321 Some(labels[correct].into()),
src/domain/exam_attempt.rsmodified+32 -9
@@ -338,7 +338,10 @@ mod tests {
338 /// The id of the question's second option — what these tests used to write338 /// The id of the question's second option — what these tests used to write
339 /// as the index `1`.339 /// as the index `1`.
340 fn second_choice(question: &ExamQuestion) -> String {340 fn second_choice(question: &ExamQuestion) -> String {
341- question.get_choices().unwrap()[1].get_id().as_str().to_string()341+ question.get_choices().unwrap()[1]
342+ .get_id()
343+ .as_str()
344+ .to_string()
342 }345 }
343 use crate::domain::settings::Settings;346 use crate::domain::settings::Settings;
344 347
@@ -367,8 +370,14 @@ mod tests {
367 let spec = QuestionSpec::try_new(370 let spec = QuestionSpec::try_new(
368 QuestionKind::try_new("choice").unwrap(),371 QuestionKind::try_new("choice").unwrap(),
369 Some(vec![372 Some(vec![
370- ChoiceInput { id: Some("a".into()), text: "5".into() },373+ ChoiceInput {
371- ChoiceInput { id: Some("b".into()), text: "6".into() },374+ id: Some("a".into()),
375+ text: "5".into(),
376+ },
377+ ChoiceInput {
378+ id: Some("b".into()),
379+ text: "6".into(),
380+ },
372 ]),381 ]),
373 Some("b".into()),382 Some("b".into()),
374 &[],383 &[],
@@ -400,9 +409,16 @@ mod tests {
400 let (first, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();409 let (first, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
401 assert!(created);410 assert!(created);
402 assert_eq!(first.get_seq(), 1);411 assert_eq!(first.get_seq(), 1);
403- ExamAnswer::save(&question, &user, 1, Some(second_choice(&question)), None, &db)412+ ExamAnswer::save(
404- .await413+ &question,
405- .unwrap();414+ &user,
415+ 1,
416+ Some(second_choice(&question)),
417+ None,
418+ &db,
419+ )
420+ .await
421+ .unwrap();
406 first.finish(&db).await.unwrap();422 first.finish(&db).await.unwrap();
407 423
408 // The retake lands as sitting #2 without touching sitting #1's answers.424 // The retake lands as sitting #2 without touching sitting #1's answers.
@@ -434,9 +450,16 @@ mod tests {
434 let (winner, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();450 let (winner, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
435 assert!(created);451 assert!(created);
436 assert_eq!(winner.get_seq(), 2);452 assert_eq!(winner.get_seq(), 2);
437- ExamAnswer::save(&question, &user, 2, Some(second_choice(&question)), None, &db)453+ ExamAnswer::save(
438- .await454+ &question,
439- .unwrap();455+ &user,
456+ 2,
457+ Some(second_choice(&question)),
458+ None,
459+ &db,
460+ )
461+ .await
462+ .unwrap();
440 463
441 // A stale double-start races on the same seq and loses to the464 // A stale double-start races on the same seq and loses to the
442 // composite id: the duplicate create is rejected, and with no wipe in465 // composite id: the duplicate create is rejected, and with no wipe in
src/domain/exam_question.rsmodified+54 -13
@@ -340,7 +340,11 @@ impl ExamQuestion {
340 /// The stored kind-dependent fields as the validated bundle (for340 /// The stored kind-dependent fields as the validated bundle (for
341 /// merge-on-update, and for copying into the bank).341 /// merge-on-update, and for copying into the bank).
342 pub fn spec(&self) -> QuestionSpec {342 pub fn spec(&self) -> QuestionSpec {
343- QuestionSpec::from_stored(self.kind.clone(), self.choices.clone(), self.correct.clone())343+ QuestionSpec::from_stored(
344+ self.kind.clone(),
345+ self.choices.clone(),
346+ self.correct.clone(),
347+ )
344 }348 }
345 349
346 pub async fn create(350 pub async fn create(
@@ -535,7 +539,10 @@ mod tests {
535 ])539 ])
536 }540 }
537 541
538- fn spec(choices: Option<Vec<ChoiceInput>>, correct: Option<&str>) -> Result<QuestionSpec, ValidationError> {542+ fn spec(
543+ choices: Option<Vec<ChoiceInput>>,
544+ correct: Option<&str>,
545+ ) -> Result<QuestionSpec, ValidationError> {
539 QuestionSpec::try_new(kind("choice"), choices, correct.map(str::to_string), &[])546 QuestionSpec::try_new(kind("choice"), choices, correct.map(str::to_string), &[])
540 }547 }
541 548
@@ -593,8 +600,14 @@ mod tests {
593 // An unlabelled option cannot be marked correct — there is nothing to600 // An unlabelled option cannot be marked correct — there is nothing to
594 // name it by until the server's minted id comes back in the response.601 // name it by until the server's minted id comes back in the response.
595 let unlabelled = Some(vec![602 let unlabelled = Some(vec![
596- ChoiceInput { id: None, text: "yes".into() },603+ ChoiceInput {
597- ChoiceInput { id: None, text: "no".into() },604+ id: None,
605+ text: "yes".into(),
606+ },
607+ ChoiceInput {
608+ id: None,
609+ text: "no".into(),
610+ },
598 ]);611 ]);
599 assert!(spec(unlabelled, Some("a")).is_err());612 assert!(spec(unlabelled, Some("a")).is_err());
600 }613 }
@@ -615,7 +628,11 @@ mod tests {
615 /// option's identity, so reordering and deleting move nothing.628 /// option's identity, so reordering and deleting move nothing.
616 #[tokio::test]629 #[tokio::test]
617 async fn existing_ids_are_preserved_across_an_edit() {630 async fn existing_ids_are_preserved_across_an_edit() {
618- let stored = spec(two_choices(), Some("a")).unwrap().into_parts().1.unwrap();631+ let stored = spec(two_choices(), Some("a"))
632+ .unwrap()
633+ .into_parts()
634+ .1
635+ .unwrap();
619 let (first, second) = (stored[0].get_id().clone(), stored[1].get_id().clone());636 let (first, second) = (stored[0].get_id().clone(), stored[1].get_id().clone());
620 637
621 // Resubmit reordered, renaming the first option's text, and marking the638 // Resubmit reordered, renaming the first option's text, and marking the
@@ -623,8 +640,14 @@ mod tests {
623 let edited = QuestionSpec::try_new(640 let edited = QuestionSpec::try_new(
624 kind("choice"),641 kind("choice"),
625 Some(vec![642 Some(vec![
626- ChoiceInput { id: Some(second.as_str().into()), text: "no".into() },643+ ChoiceInput {
627- ChoiceInput { id: Some(first.as_str().into()), text: "YES".into() },644+ id: Some(second.as_str().into()),
645+ text: "no".into(),
646+ },
647+ ChoiceInput {
648+ id: Some(first.as_str().into()),
649+ text: "YES".into(),
650+ },
628 ]),651 ]),
629 Some(second.as_str().into()),652 Some(second.as_str().into()),
630 &stored,653 &stored,
@@ -641,8 +664,14 @@ mod tests {
641 #[tokio::test]664 #[tokio::test]
642 async fn spec_rejects_a_duplicate_choice_id() {665 async fn spec_rejects_a_duplicate_choice_id() {
643 let dupes = Some(vec![666 let dupes = Some(vec![
644- ChoiceInput { id: Some("a".into()), text: "yes".into() },667+ ChoiceInput {
645- ChoiceInput { id: Some("a".into()), text: "no".into() },668+ id: Some("a".into()),
669+ text: "yes".into(),
670+ },
671+ ChoiceInput {
672+ id: Some("a".into()),
673+ text: "no".into(),
674+ },
646 ]);675 ]);
647 assert!(spec(dupes, Some("a")).is_err());676 assert!(spec(dupes, Some("a")).is_err());
648 }677 }
@@ -652,7 +681,10 @@ mod tests {
652 let n = |count: usize| {681 let n = |count: usize| {
653 Some(682 Some(
654 (0..count)683 (0..count)
655- .map(|i| ChoiceInput { id: Some(i.to_string()), text: "option".into() })684+ .map(|i| ChoiceInput {
685+ id: Some(i.to_string()),
686+ text: "option".into(),
687+ })
656 .collect::<Vec<_>>(),688 .collect::<Vec<_>>(),
657 )689 )
658 };690 };
@@ -676,7 +708,10 @@ mod tests {
676 /// `try_new` on create, so the ids are real minted ULIDs.708 /// `try_new` on create, so the ids are real minted ULIDs.
677 fn stored_set(n: usize) -> Vec<Choice> {709 fn stored_set(n: usize) -> Vec<Choice> {
678 let inputs = (0..n)710 let inputs = (0..n)
679- .map(|i| ChoiceInput { id: Some(format!("s{i}")), text: format!("stored {i}") })711+ .map(|i| ChoiceInput {
712+ id: Some(format!("s{i}")),
713+ text: format!("stored {i}"),
714+ })
680 .collect();715 .collect();
681 QuestionSpec::try_new(kind("choice"), Some(inputs), Some("s0".into()), &[])716 QuestionSpec::try_new(kind("choice"), Some(inputs), Some("s0".into()), &[])
682 .unwrap()717 .unwrap()
@@ -806,8 +841,14 @@ mod tests {
806 async fn spec_rejects_blank_or_oversized_choices() {841 async fn spec_rejects_blank_or_oversized_choices() {
807 let with = |text: String| {842 let with = |text: String| {
808 Some(vec![843 Some(vec![
809- ChoiceInput { id: Some("a".into()), text: "yes".into() },844+ ChoiceInput {
810- ChoiceInput { id: Some("b".into()), text },845+ id: Some("a".into()),
846+ text: "yes".into(),
847+ },
848+ ChoiceInput {
849+ id: Some("b".into()),
850+ text,
851+ },
811 ])852 ])
812 };853 };
813 assert!(spec(with(" ".into()), Some("a")).is_err());854 assert!(spec(with(" ".into()), Some("a")).is_err());
src/domain/exam_result.rsmodified+10 -5
@@ -300,15 +300,20 @@ mod tests {
300 .await300 .await
301 .unwrap();301 .unwrap();
302 assert_eq!(302 assert_eq!(
303- history.iter().map(|r| r.get_mark().as_i64()).collect::<Vec<_>>(),303+ history
304+ .iter()
305+ .map(|r| r.get_mark().as_i64())
306+ .collect::<Vec<_>>(),
304 vec![40, 90]307 vec![40, 90]
305 );308 );
306 309
307 // Deleting the pair removes every sitting.310 // Deleting the pair removes every sitting.
308 ExamResult::remove(&exam, &user, &db).await.unwrap();311 ExamResult::remove(&exam, &user, &db).await.unwrap();
309- assert!(ExamResult::list_all_for_exam_user(&exam, &user, &db)312+ assert!(
310- .await313+ ExamResult::list_all_for_exam_user(&exam, &user, &db)
311- .unwrap()314+ .await
312- .is_empty());315+ .unwrap()
316+ .is_empty()
317+ );
313 }318 }
314 }319 }
src/domain/question_image.rsmodified+22 -4
@@ -217,7 +217,10 @@ mod tests {
217 Some(217 Some(
218 ["a", "b", "c"]218 ["a", "b", "c"]
219 .iter()219 .iter()
220- .map(|l| ChoiceInput { id: Some((*l).into()), text: (*l).into() })220+ .map(|l| ChoiceInput {
221+ id: Some((*l).into()),
222+ text: (*l).into(),
223+ })
221 .collect(),224 .collect(),
222 ),225 ),
223 Some("a".into()),226 Some("a".into()),
@@ -312,9 +315,24 @@ mod tests {
312 .unwrap();315 .unwrap();
313 // The question illustration plus the two surviving option pictures.316 // The question illustration plus the two surviving option pictures.
314 assert_eq!(left.len(), 3);317 assert_eq!(left.len(), 3);
315- assert!(QuestionImage::read_slot(&question, Some(&ids[0]), &db).await.unwrap().is_some());318+ assert!(
316- assert!(QuestionImage::read_slot(&question, Some(&ids[2]), &db).await.unwrap().is_some());319+ QuestionImage::read_slot(&question, Some(&ids[0]), &db)
317- assert!(QuestionImage::read_slot(&question, None, &db).await.unwrap().is_some());320+ .await
321+ .unwrap()
322+ .is_some()
323+ );
324+ assert!(
325+ QuestionImage::read_slot(&question, Some(&ids[2]), &db)
326+ .await
327+ .unwrap()
328+ .is_some()
329+ );
330+ assert!(
331+ QuestionImage::read_slot(&question, None, &db)
332+ .await
333+ .unwrap()
334+ .is_some()
335+ );
318 }336 }
319 337
320 #[tokio::test]338 #[tokio::test]
src/domain/settings.rsmodified+8 -5
@@ -15,11 +15,11 @@ use surrealdb::types::{RecordId, SurrealValue};
15 15
16 use crate::constant::{16 use crate::constant::{
17 DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_EXAM_KINDS,17 DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_EXAM_KINDS,
18- DEFAULT_MAX_CHATBOT_THREADS, DEFAULT_MAX_CHATBOT_MESSAGE_LEN, DEFAULT_MAX_FILE_BYTES,18+ DEFAULT_MAX_CHATBOT_MESSAGE_LEN, DEFAULT_MAX_CHATBOT_THREADS, DEFAULT_MAX_FILE_BYTES,
19- MAX_CHATBOT_HISTORY_TURNS, MAX_EXAM_KIND_WEIGHT, MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN, MAX_MARK,19+ MAX_CHATBOT_HISTORY_TURNS, MAX_EXAM_KIND_WEIGHT, MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN,
20- MAX_MAX_CHATBOT_THREADS, MAX_MAX_CHATBOT_MESSAGE_LEN, MAX_MAX_FILE_BYTES,20+ MAX_MARK, MAX_MAX_CHATBOT_MESSAGE_LEN, MAX_MAX_CHATBOT_THREADS, MAX_MAX_FILE_BYTES,
21 MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT,21 MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT,
22- MIN_MARK, MIN_MAX_CHATBOT_THREADS, MIN_MAX_CHATBOT_MESSAGE_LEN, MIN_MAX_FILE_BYTES,22+ MIN_MARK, MIN_MAX_CHATBOT_MESSAGE_LEN, MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES,
23 };23 };
24 use crate::database::{Database, SETTINGS_TABLE};24 use crate::database::{Database, SETTINGS_TABLE};
25 use crate::domain::text_fold;25 use crate::domain::text_fold;
@@ -704,7 +704,10 @@ mod tests {
704 Settings::defaults().save(&db).await.unwrap();704 Settings::defaults().save(&db).await.unwrap();
705 let loaded = Settings::load(&db).await.unwrap();705 let loaded = Settings::load(&db).await.unwrap();
706 assert_eq!(loaded.get_max_file_bytes(), DEFAULT_MAX_FILE_BYTES);706 assert_eq!(loaded.get_max_file_bytes(), DEFAULT_MAX_FILE_BYTES);
707- assert_eq!(loaded.get_chatbot_history_turns(), DEFAULT_CHATBOT_HISTORY_TURNS);707+ assert_eq!(
708+ loaded.get_chatbot_history_turns(),
709+ DEFAULT_CHATBOT_HISTORY_TURNS
710+ );
708 assert_eq!(711 assert_eq!(
709 loaded.get_max_chatbot_threads(),712 loaded.get_max_chatbot_threads(),
710 DEFAULT_MAX_CHATBOT_THREADS713 DEFAULT_MAX_CHATBOT_THREADS
src/domain/subject.rsmodified+5 -1
@@ -152,7 +152,11 @@ impl Subject {
152 .bind(("description", description))152 .bind(("description", description))
153 .await?153 .await?
154 .check()?;154 .check()?;
155- result.take::<Vec<Subject>>(0)?.into_iter().next().ok_or(AppError::NotFound)155+ result
156+ .take::<Vec<Subject>>(0)?
157+ .into_iter()
158+ .next()
159+ .ok_or(AppError::NotFound)
156 }160 }
157 161
158 /// Delete the subject and clear it off every bank template that carried it162 /// Delete the subject and clear it off every bank template that carried it
src/web/bank_questions.rsmodified+5 -2
@@ -39,8 +39,8 @@ use crate::error::{AppError, ErrorResponse, ValidationError};
39 use crate::state::AppState;39 use crate::state::AppState;
40 40
41 use super::dto::person_map;41 use super::dto::person_map;
42-use super::subjects::subject_must_exist;
43 use super::exams::ChoiceResponse;42 use super::exams::ChoiceResponse;
43+use super::subjects::subject_must_exist;
44 use super::{44 use super::{
45 ChoiceBody, Page, PageParams, RequireTeacher, UploadFileForm, blob_path, image_content_type,45 ChoiceBody, Page, PageParams, RequireTeacher, UploadFileForm, blob_path, image_content_type,
46 read_upload, remove_blob, serve_inline_blob, set_or_clear,46 read_upload, remove_blob, serve_inline_blob, set_or_clear,
@@ -530,7 +530,10 @@ async fn list_questions(
530 let buckets = bank_images_by_question(&ids, &st.db).await?;530 let buckets = bank_images_by_question(&ids, &st.db).await?;
531 // One grouped query for the whole page — never a count per row.531 // One grouped query for the whole page — never a count per row.
532 let used = BankQuestion::usage_counts(&ids, &st.db).await?;532 let used = BankQuestion::usage_counts(&ids, &st.db).await?;
533- let subject_ids: Vec<&SubjectId> = questions.iter().filter_map(BankQuestion::get_subject).collect();533+ let subject_ids: Vec<&SubjectId> = questions
534+ .iter()
535+ .filter_map(BankQuestion::get_subject)
536+ .collect();
534 let subject_names: HashMap<String, String> = Subject::list_by_ids(&subject_ids, &st.db)537 let subject_names: HashMap<String, String> = Subject::list_by_ids(&subject_ids, &st.db)
535 .await?538 .await?
536 .iter()539 .iter()
src/web/chatbot.rsmodified+5 -15
@@ -85,9 +85,7 @@ impl ChatbotThreadResponse {
85 fn new(thread: &ChatbotThread) -> Self {85 fn new(thread: &ChatbotThread) -> Self {
86 Self {86 Self {
87 id: thread.get_id().key().to_string(),87 id: thread.get_id().key().to_string(),
88- title: thread88+ title: thread.get_title().map(|title| title.as_str().to_string()),
89- .get_title()
90- .map(|title| title.as_str().to_string()),
91 created_at: thread.get_created_at().as_millis(),89 created_at: thread.get_created_at().as_millis(),
92 updated_at: thread.get_updated_at().as_millis(),90 updated_at: thread.get_updated_at().as_millis(),
93 }91 }
@@ -232,11 +230,7 @@ async fn delete_thread(
232 230
233 /// Read a thread the caller owns, or `404`. A foreign id is indistinguishable231 /// Read a thread the caller owns, or `404`. A foreign id is indistinguishable
234 /// from a missing one.232 /// from a missing one.
235-async fn own_thread(233+async fn own_thread(id: &str, user: &UserId, db: &Database) -> Result<ChatbotThread, AppError> {
236- id: &str,
237- user: &UserId,
238- db: &Database,
239-) -> Result<ChatbotThread, AppError> {
240 ChatbotThread::read_for(&ChatbotThreadId::from_key(id), user, db)234 ChatbotThread::read_for(&ChatbotThreadId::from_key(id), user, db)
241 .await?235 .await?
242 .ok_or(AppError::NotFound)236 .ok_or(AppError::NotFound)
@@ -406,13 +400,9 @@ async fn send_message(
406 return Ok(unavailable("no AI service is connected right now"));400 return Ok(unavailable("no AI service is connected right now"));
407 }401 }
408 402
409- let prompt = ChatbotMessage::append_user(403+ let prompt =
410- thread.get_id(),404+ ChatbotMessage::append_user(thread.get_id(), user.get_id(), content.clone(), &st.db)
411- user.get_id(),405+ .await?;
412- content.clone(),
413- &st.db,
414- )
415- .await?;
416 let answer =406 let answer =
417 ChatbotMessage::append_pending_assistant(thread.get_id(), user.get_id(), &st.db).await?;407 ChatbotMessage::append_pending_assistant(thread.get_id(), user.get_id(), &st.db).await?;
418 // Never fatal: both rows are already written, and failing here would strand408 // Never fatal: both rows are already written, and failing here would strand
src/web/etag.rsmodified+8 -5
@@ -76,10 +76,9 @@ pub async fn etag(request: Request, next: Next) -> Response {
76 // inert. `private`: these are per-user authenticated responses. But if the76 // inert. `private`: these are per-user authenticated responses. But if the
77 // handler set its own directive, it knows best — leave it untouched.77 // handler set its own directive, it knows best — leave it untouched.
78 if !parts.headers.contains_key(CACHE_CONTROL) {78 if !parts.headers.contains_key(CACHE_CONTROL) {
79- parts.headers.insert(79+ parts
80- CACHE_CONTROL,80+ .headers
81- HeaderValue::from_static("private, no-cache"),81+ .insert(CACHE_CONTROL, HeaderValue::from_static("private, no-cache"));
82- );
83 }82 }
84 83
85 if matches(if_none_match.as_ref(), &tag) {84 if matches(if_none_match.as_ref(), &tag) {
@@ -117,5 +116,9 @@ fn matches(if_none_match: Option<&HeaderValue>, tag: &str) -> bool {
117 return false;116 return false;
118 };117 };
119 let value = value.trim();118 let value = value.trim();
120- value == "*" || value.split(',').map(str::trim).any(|candidate| candidate == tag)119+ value == "*"
120+ || value
121+ .split(',')
122+ .map(str::trim)
123+ .any(|candidate| candidate == tag)
121 }124 }
src/web/exams.rsmodified+11 -7
@@ -1487,9 +1487,7 @@ impl QuestionResponse {
1487 kind: question.get_kind().as_str().to_string(),1487 kind: question.get_kind().as_str().to_string(),
1488 points: question.get_points().as_i64(),1488 points: question.get_points().as_i64(),
1489 choices: ChoiceResponse::list(question.get_choices()),1489 choices: ChoiceResponse::list(question.get_choices()),
1490- correct: question1490+ correct: question.get_correct().map(|id| id.as_str().to_string()),
1491- .get_correct()
1492- .map(|id| id.as_str().to_string()),
1493 image: image_meta(images, None),1491 image: image_meta(images, None),
1494 choice_images: choice_image_metas(question, images),1492 choice_images: choice_image_metas(question, images),
1495 from_bank: question.get_from_bank().map(|b| b.key().to_string()),1493 from_bank: question.get_from_bank().map(|b| b.key().to_string()),
@@ -2464,7 +2462,15 @@ async fn upload_choice_image(
2464 ensure_questions_editable(exam.get_id(), &st.db).await?;2462 ensure_questions_editable(exam.get_id(), &st.db).await?;
2465 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;2463 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
2466 let slot = choice_slot(&question, &choice_id)?;2464 let slot = choice_slot(&question, &choice_id)?;
2467- let stored = store_image(&st, &exam, &question, Some(&slot), content_type, &upload.data).await?;2465+ let stored = store_image(
2466+ &st,
2467+ &exam,
2468+ &question,
2469+ Some(&slot),
2470+ content_type,
2471+ &upload.data,
2472+ )
2473+ .await?;
2468 Ok((StatusCode::CREATED, Json(ImageMetaResponse::new(&stored))))2474 Ok((StatusCode::CREATED, Json(ImageMetaResponse::new(&stored))))
2469 }2475 }
2470 2476
@@ -3555,9 +3561,7 @@ async fn review_attempt_answers(
3555 Path((id, seq)): Path<(String, i64)>,3561 Path((id, seq)): Path<(String, i64)>,
3556 ) -> Result<Json<AttemptAnswersResponse>, AppError> {3562 ) -> Result<Json<AttemptAnswersResponse>, AppError> {
3557 let exam = reviewable_exam(&st, &user, &id).await?;3563 let exam = reviewable_exam(&st, &user, &id).await?;
3558- Ok(Json(3564+ Ok(Json(answer_sheet(&exam, user.get_id(), seq, &st.db).await?))
3559- answer_sheet(&exam, user.get_id(), seq, &st.db).await?,
3560- ))
3561 }3565 }
3562 3566
3563 /// The caller's own drawn-answer bytes for one of their sittings — the3567 /// The caller's own drawn-answer bytes for one of their sittings — the
src/web/settings.rsmodified+3 -1
@@ -239,7 +239,9 @@ async fn update_settings(
239 params.attendance_statuses = attendance_statuses;239 params.attendance_statuses = attendance_statuses;
240 params.grade_bands = grade_bands;240 params.grade_bands = grade_bands;
241 params.max_file_bytes = req.max_file_bytes.unwrap_or(params.max_file_bytes);241 params.max_file_bytes = req.max_file_bytes.unwrap_or(params.max_file_bytes);
242- params.chatbot_history_turns = req.chatbot_history_turns.unwrap_or(params.chatbot_history_turns);242+ params.chatbot_history_turns = req
243+ .chatbot_history_turns
244+ .unwrap_or(params.chatbot_history_turns);
243 params.max_chatbot_threads = req245 params.max_chatbot_threads = req
244 .max_chatbot_threads246 .max_chatbot_threads
245 .unwrap_or(params.max_chatbot_threads);247 .unwrap_or(params.max_chatbot_threads);
src/web/subjects.rsmodified+1 -1
@@ -14,8 +14,8 @@ use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName
14 use crate::error::{AppError, ErrorResponse, ValidationError};14 use crate::error::{AppError, ErrorResponse, ValidationError};
15 use crate::state::AppState;15 use crate::state::AppState;
16 16
17-use super::courses::{can_manage_course, can_view_course};
18 use super::bank_questions::BANK_LOCK;17 use super::bank_questions::BANK_LOCK;
18+use super::courses::{can_manage_course, can_view_course};
19 use super::exams::EXAM_LOCK;19 use super::exams::EXAM_LOCK;
20 use super::homework::HOMEWORK_LOCK;20 use super::homework::HOMEWORK_LOCK;
21 use super::{CurrentUser, RequireTeacher, SubjectResponse};21 use super::{CurrentUser, RequireTeacher, SubjectResponse};
tests/e2e.rsmodified+2 -6
@@ -1841,9 +1841,7 @@ async fn chat_stream_and_poll_agree_that_an_answer_was_truncated() {
1841 1841
1842 // The same row, read the other way: identical verdict, field for field.1842 // The same row, read the other way: identical verdict, field for field.
1843 let polled: Value = ali1843 let polled: Value = ali
1844- .get(format!(1844+ .get(format!("{base}/chatbot/threads/{thread}/messages/{mid}"))
1845- "{base}/chatbot/threads/{thread}/messages/{mid}"
1846- ))
1847 .send()1845 .send()
1848 .await1846 .await
1849 .unwrap()1847 .unwrap()
@@ -1915,9 +1913,7 @@ async fn chat_stream_replays_an_answer_that_already_landed() {
1915 let mut settled = Value::Null;1913 let mut settled = Value::Null;
1916 for _ in 0..500 {1914 for _ in 0..500 {
1917 let turn: Value = ali1915 let turn: Value = ali
1918- .get(format!(1916+ .get(format!("{base}/chatbot/threads/{thread}/messages/{mid}"))
1919- "{base}/chatbot/threads/{thread}/messages/{mid}"
1920- ))
1921 .send()1917 .send()
1922 .await1918 .await
1923 .unwrap()1919 .unwrap()
tests/etag.rsmodified+4 -1
@@ -93,7 +93,10 @@ async fn handler_cache_control_is_not_overwritten() {
93 let (status, headers, _) = get(&app, "/x", None).await;93 let (status, headers, _) = get(&app, "/x", None).await;
94 assert_eq!(status, StatusCode::OK);94 assert_eq!(status, StatusCode::OK);
95 // We still add our validator...95 // We still add our validator...
96- assert!(headers.get("etag").is_some(), "no handler ETag, so we set one");96+ assert!(
97+ headers.get("etag").is_some(),
98+ "no handler ETag, so we set one"
99+ );
97 // ...but the handler's own directive wins.100 // ...but the handler's own directive wins.
98 assert_eq!(headers.get("cache-control").unwrap(), "public, max-age=60");101 assert_eq!(headers.get("cache-control").unwrap(), "public, max-age=60");
99 }102 }
tests/integration.rsmodified+755 -144
@@ -7477,7 +7477,10 @@ async fn question_crud_validation_and_rbac() {
7477 .await;7477 .await;
7478 assert_eq!(res.status, StatusCode::OK, "{}", res.body);7478 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
7479 assert_eq!(res.body["points"], 15);7479 assert_eq!(res.body["points"], 15);
7480- assert_eq!(res.body["correct"], res.body["choices"][1]["id"], "kind bundle kept");7480+ assert_eq!(
7481+ res.body["correct"], res.body["choices"][1]["id"],
7482+ "kind bundle kept"
7483+ );
7481 assert_eq!(res.body["subject"], subject, "subject kept by omission");7484 assert_eq!(res.body["subject"], subject, "subject kept by omission");
7482 7485
7483 // Re-tagging stays inside the course: another of its subjects is fine, a7486 // Re-tagging stays inside the course: another of its subjects is fine, a
@@ -7735,7 +7738,10 @@ async fn student_question_view_hides_correct_and_embeds_answers() {
7735 7738
7736 let res = send(&app, "GET", &uri, Some(&student), None).await;7739 let res = send(&app, "GET", &uri, Some(&student), None).await;
7737 let questions = res.body.as_array().expect("questions");7740 let questions = res.body.as_array().expect("questions");
7738- assert_eq!(questions[0]["answer"]["selected"], choice_of(&choice_q_body, 0));7741+ assert_eq!(
7742+ questions[0]["answer"]["selected"],
7743+ choice_of(&choice_q_body, 0)
7744+ );
7739 assert_eq!(questions[0]["answer"]["updated_at"], saved_at);7745 assert_eq!(questions[0]["answer"]["updated_at"], saved_at);
7740 assert!(questions[1]["answer"].is_null());7746 assert!(questions[1]["answer"].is_null());
7741 }7747 }
@@ -7941,7 +7947,10 @@ async fn answer_saves_gate_on_attempt_state_and_kind() {
7941 "review after submit: {}",7947 "review after submit: {}",
7942 res.body7948 res.body
7943 );7949 );
7944- assert_eq!(res.body[0]["answer"]["selected"], choice_of(&choice_q_body, 2));7950+ assert_eq!(
7951+ res.body[0]["answer"]["selected"],
7952+ choice_of(&choice_q_body, 2)
7953+ );
7945 assert_eq!(res.body[1]["answer"]["text"], "because");7954 assert_eq!(res.body[1]["answer"]["text"], "because");
7946 }7955 }
7947 7956
@@ -8140,7 +8149,10 @@ async fn answer_saves_stop_at_the_deadline() {
8140 )8149 )
8141 .await;8150 .await;
8142 assert_eq!(res.status, StatusCode::OK, "{}", res.body);8151 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
8143- assert_eq!(res.body["answers"][0]["selected"], choice_of(&question_body, 0));8152+ assert_eq!(
8153+ res.body["answers"][0]["selected"],
8154+ choice_of(&question_body, 0)
8155+ );
8144 }8156 }
8145 8157
8146 #[tokio::test]8158 #[tokio::test]
@@ -8586,7 +8598,10 @@ async fn question_patch_revalidates_the_stale_kind_bundle() {
8586 .len(),8598 .len(),
8587 28599 2
8588 );8600 );
8589- assert_eq!(common::items(&res.body)[0]["correct"], common::items(&res.body)[0]["choices"][1]["id"]);8601+ assert_eq!(
8602+ common::items(&res.body)[0]["correct"],
8603+ common::items(&res.body)[0]["choices"][1]["id"]
8604+ );
8590 }8605 }
8591 8606
8592 #[tokio::test]8607 #[tokio::test]
@@ -10868,7 +10883,10 @@ async fn question_images_author_serve_and_cascade() {
10868 let (status, _) = post_image(10883 let (status, _) = post_image(
10869 &app,10884 &app,
10870 &teacher,10885 &teacher,
10871- &format!("/exams/{exam}/questions/{essay}/choices/{}/image", choice_of(&question_body, 0)),10886+ &format!(
10887+ "/exams/{exam}/questions/{essay}/choices/{}/image",
10888+ choice_of(&question_body, 0)
10889+ ),
10872 "image/png",10890 "image/png",
10873 b"x",10891 b"x",
10874 )10892 )
@@ -11359,7 +11377,10 @@ async fn question_image_edits_follow_the_choices() {
11359 for (path, bytes) in [11377 for (path, bytes) in [
11360 (format!("{base}/image"), b"illustration".as_slice()),11378 (format!("{base}/image"), b"illustration".as_slice()),
11361 (format!("{base}/choices/{stone}/image"), b"stone".as_slice()),11379 (format!("{base}/choices/{stone}/image"), b"stone".as_slice()),
11362- (format!("{base}/choices/{bronze}/image"), b"bronze".as_slice()),11380+ (
11381+ format!("{base}/choices/{bronze}/image"),
11382+ b"bronze".as_slice(),
11383+ ),
11363 (format!("{base}/choices/{iron}/image"), b"iron".as_slice()),11384 (format!("{base}/choices/{iron}/image"), b"iron".as_slice()),
11364 ] {11385 ] {
11365 let (status, body) = post_image(&app, &teacher, &path, "image/png", bytes).await;11386 let (status, body) = post_image(&app, &teacher, &path, "image/png", bytes).await;
@@ -14841,12 +14862,7 @@ async fn new_thread(app: &axum::Router, cookie: &str) -> String {
14841 id_of(&res.body)14862 id_of(&res.body)
14842 }14863 }
14843 14864
14844-async fn post_turn(14865+async fn post_turn(app: &axum::Router, cookie: &str, thread: &str, content: &str) -> common::Res {
14845- app: &axum::Router,
14846- cookie: &str,
14847- thread: &str,
14848- content: &str,
14849-) -> common::Res {
14850 send(14866 send(
14851 app,14867 app,
14852 "POST",14868 "POST",
@@ -14859,17 +14875,10 @@ async fn post_turn(
14859 14875
14860 /// Open the SSE stream without draining it — a `pending` turn's stream stays14876 /// Open the SSE stream without draining it — a `pending` turn's stream stays
14861 /// open, so reading its body here would hang.14877 /// open, so reading its body here would hang.
14862-async fn open_stream(14878+async fn open_stream(app: &axum::Router, cookie: &str, thread: &str, mid: &str) -> StatusCode {
14863- app: &axum::Router,
14864- cookie: &str,
14865- thread: &str,
14866- mid: &str,
14867-) -> StatusCode {
14868 let request = Request::builder()14879 let request = Request::builder()
14869 .method("GET")14880 .method("GET")
14870- .uri(format!(14881+ .uri(format!("/chatbot/threads/{thread}/messages/{mid}/stream"))
14871- "/chatbot/threads/{thread}/messages/{mid}/stream"
14872- ))
14873 .header("cookie", cookie)14882 .header("cookie", cookie)
14874 .body(Body::empty())14883 .body(Body::empty())
14875 .unwrap();14884 .unwrap();
@@ -15086,24 +15095,15 @@ async fn chat_threads_are_invisible_to_everyone_else() {
15086 ] {15095 ] {
15087 let other = login_as(&app, &db, name, role).await;15096 let other = login_as(&app, &db, name, role).await;
15088 for (method, uri) in [15097 for (method, uri) in [
15089- (15098+ ("GET", format!("/chatbot/threads/{thread}/messages")),
15090- "GET",15099+ ("GET", format!("/chatbot/threads/{thread}/messages/{mid}")),
15091- format!("/chatbot/threads/{thread}/messages"),
15092- ),
15093- (
15094- "GET",
15095- format!("/chatbot/threads/{thread}/messages/{mid}"),
15096- ),
15097 (15100 (
15098 "GET",15101 "GET",
15099 format!("/chatbot/threads/{thread}/messages/{mid}/stream"),15102 format!("/chatbot/threads/{thread}/messages/{mid}/stream"),
15100 ),15103 ),
15101 ("DELETE", format!("/chatbot/threads/{thread}")),15104 ("DELETE", format!("/chatbot/threads/{thread}")),
15102 ("PATCH", format!("/chatbot/threads/{thread}")),15105 ("PATCH", format!("/chatbot/threads/{thread}")),
15103- (15106+ ("POST", format!("/chatbot/threads/{thread}/messages")),
15104- "POST",
15105- format!("/chatbot/threads/{thread}/messages"),
15106- ),
15107 ] {15107 ] {
15108 let body = match method {15108 let body = match method {
15109 "POST" => Some(json!({ "content": "sızıntı" })),15109 "POST" => Some(json!({ "content": "sızıntı" })),
@@ -15286,9 +15286,7 @@ async fn chat_stream_stops_polling_when_the_client_hangs_up() {
15286 }15286 }
15287 let request = Request::builder()15287 let request = Request::builder()
15288 .method("GET")15288 .method("GET")
15289- .uri(format!(15289+ .uri(format!("/chatbot/threads/{thread}/messages/{mid}/stream"))
15290- "/chatbot/threads/{thread}/messages/{mid}/stream"
15291- ))
15292 .header("cookie", &ali)15290 .header("cookie", &ali)
15293 .body(Body::empty())15291 .body(Body::empty())
15294 .unwrap();15292 .unwrap();
@@ -15812,7 +15810,14 @@ async fn approval_refuses_a_teacher_double_booking() {
15812 // Teacher counter-proposes a window overlapping the just-approved meeting;15810 // Teacher counter-proposes a window overlapping the just-approved meeting;
15813 // accepting it is approval at the proposed time, and that collision is what15811 // accepting it is approval at the proposed time, and that collision is what
15814 // must be refused.15812 // must be refused.
15815- let res = propose(&app, &ali, &two, now + HOUR_MS + 600_000, now + 2 * HOUR_MS + 600_000).await;15813+ let res = propose(
15814+ &app,
15815+ &ali,
15816+ &two,
15817+ now + HOUR_MS + 600_000,
15818+ now + 2 * HOUR_MS + 600_000,
15819+ )
15820+ .await;
15816 assert_eq!(res.status, StatusCode::OK, "{}", res.body);15821 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
15817 let res = decide(&app, &ayse, &two, "reschedule/accept").await;15822 let res = decide(&app, &ayse, &two, "reschedule/accept").await;
15818 assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);15823 assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
@@ -16115,7 +16120,12 @@ async fn only_the_requester_cancels() {
16115 // a decider ends a booking by rejecting (pending) or rescheduling.16120 // a decider ends a booking by rejecting (pending) or rescheduling.
16116 let booking = book_ok(&app, &ayse, &slot).await;16121 let booking = book_ok(&app, &ayse, &slot).await;
16117 let res = decide(&app, &ali, &booking, "cancel").await;16122 let res = decide(&app, &ali, &booking, "cancel").await;
16118- assert_eq!(res.status, StatusCode::FORBIDDEN, "owner-teacher: {}", res.body);16123+ assert_eq!(
16124+ res.status,
16125+ StatusCode::FORBIDDEN,
16126+ "owner-teacher: {}",
16127+ res.body
16128+ );
16119 // An unrelated student may not either.16129 // An unrelated student may not either.
16120 let res = decide(&app, &veli, &booking, "cancel").await;16130 let res = decide(&app, &veli, &booking, "cancel").await;
16121 assert_eq!(res.status, StatusCode::FORBIDDEN, "outsider: {}", res.body);16131 assert_eq!(res.status, StatusCode::FORBIDDEN, "outsider: {}", res.body);
@@ -16488,7 +16498,14 @@ async fn attempt_history_preserves_each_prior_sitting() {
16488 let own_image = format!("/exams/{exam}/attempt/answers/{question}/image");16498 let own_image = format!("/exams/{exam}/attempt/answers/{question}/image");
16489 16499
16490 // Seq 1: answer, draw, finish.16500 // Seq 1: answer, draw, finish.
16491- let res = send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await;16501+ let res = send(
16502+ &app,
16503+ "POST",
16504+ &format!("/exams/{exam}/attempt"),
16505+ Some(&student),
16506+ None,
16507+ )
16508+ .await;
16492 assert_eq!(res.status, StatusCode::CREATED, "sit seq 1: {}", res.body);16509 assert_eq!(res.status, StatusCode::CREATED, "sit seq 1: {}", res.body);
16493 let res = send(16510 let res = send(
16494 &app,16511 &app,
@@ -16501,9 +16518,23 @@ async fn attempt_history_preserves_each_prior_sitting() {
16501 assert_eq!(res.status, StatusCode::OK, "{}", res.body);16518 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
16502 let (status, _) = post_image(&app, &student, &own_image, "image/png", b"seq1-draw").await;16519 let (status, _) = post_image(&app, &student, &own_image, "image/png", b"seq1-draw").await;
16503 assert_eq!(status, StatusCode::CREATED);16520 assert_eq!(status, StatusCode::CREATED);
16504- send(&app, "POST", &format!("/exams/{exam}/attempt/finish"), Some(&student), None).await;16521+ send(
16522+ &app,
16523+ "POST",
16524+ &format!("/exams/{exam}/attempt/finish"),
16525+ Some(&student),
16526+ None,
16527+ )
16528+ .await;
16505 // Seq 2: retake, answer + draw differently.16529 // Seq 2: retake, answer + draw differently.
16506- let res = send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await;16530+ let res = send(
16531+ &app,
16532+ "POST",
16533+ &format!("/exams/{exam}/attempt"),
16534+ Some(&student),
16535+ None,
16536+ )
16537+ .await;
16507 assert_eq!(res.body["attempt"], 2, "retake is the second sitting");16538 assert_eq!(res.body["attempt"], 2, "retake is the second sitting");
16508 let res = send(16539 let res = send(
16509 &app,16540 &app,
@@ -16548,11 +16579,15 @@ async fn attempt_history_preserves_each_prior_sitting() {
16548 .await;16579 .await;
16549 assert_eq!(seq1.body["answers"][0]["text"], "mitochondria");16580 assert_eq!(seq1.body["answers"][0]["text"], "mitochondria");
16550 assert_eq!(seq2.body["answers"][0]["text"], "chloroplast");16581 assert_eq!(seq2.body["answers"][0]["text"], "chloroplast");
16551- assert_ne!(seq1.body["answers"][0]["text"], seq2.body["answers"][0]["text"]);16582+ assert_ne!(
16583+ seq1.body["answers"][0]["text"],
16584+ seq2.body["answers"][0]["text"]
16585+ );
16552 16586
16553 // Each sitting keeps its own drawing bytes.16587 // Each sitting keeps its own drawing bytes.
16554 for (seq, want) in [(1, b"seq1-draw".as_slice()), (2, b"seq2-draw".as_slice())] {16588 for (seq, want) in [(1, b"seq1-draw".as_slice()), (2, b"seq2-draw".as_slice())] {
16555- let uri = format!("/exams/{exam}/students/{student_id}/attempts/{seq}/answers/{question}/image");16589+ let uri =
16590+ format!("/exams/{exam}/students/{student_id}/attempts/{seq}/answers/{question}/image");
16556 let (status, _, bytes) =16591 let (status, _, bytes) =
16557 common::send_raw(&app, "GET", &uri, Some(&teacher), None, Vec::new()).await;16592 common::send_raw(&app, "GET", &uri, Some(&teacher), None, Vec::new()).await;
16558 assert_eq!(status, StatusCode::OK, "seq {seq} image");16593 assert_eq!(status, StatusCode::OK, "seq {seq} image");
@@ -16583,7 +16618,14 @@ async fn grade_of_record_is_latest_but_history_keeps_both() {
16583 let results_uri = format!("/exams/{exam}/results");16618 let results_uri = format!("/exams/{exam}/results");
16584 16619
16585 // Seq 1: sit, grade 40, finish.16620 // Seq 1: sit, grade 40, finish.
16586- send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await;16621+ send(
16622+ &app,
16623+ "POST",
16624+ &format!("/exams/{exam}/attempt"),
16625+ Some(&student),
16626+ None,
16627+ )
16628+ .await;
16587 let res = send(16629 let res = send(
16588 &app,16630 &app,
16589 "POST",16631 "POST",
@@ -16593,9 +16635,23 @@ async fn grade_of_record_is_latest_but_history_keeps_both() {
16593 )16635 )
16594 .await;16636 .await;
16595 assert_eq!(res.status, StatusCode::OK, "{}", res.body);16637 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
16596- send(&app, "POST", &format!("/exams/{exam}/attempt/finish"), Some(&student), None).await;16638+ send(
16639+ &app,
16640+ "POST",
16641+ &format!("/exams/{exam}/attempt/finish"),
16642+ Some(&student),
16643+ None,
16644+ )
16645+ .await;
16597 // Seq 2: retake, grade 90 — the mark lands on the new sitting.16646 // Seq 2: retake, grade 90 — the mark lands on the new sitting.
16598- send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await;16647+ send(
16648+ &app,
16649+ "POST",
16650+ &format!("/exams/{exam}/attempt"),
16651+ Some(&student),
16652+ None,
16653+ )
16654+ .await;
16599 let res = send(16655 let res = send(
16600 &app,16656 &app,
16601 "POST",16657 "POST",
@@ -16607,7 +16663,14 @@ async fn grade_of_record_is_latest_but_history_keeps_both() {
16607 assert_eq!(res.status, StatusCode::OK, "{}", res.body);16663 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
16608 16664
16609 // The roster (latest-per-pair) reports one row, at seq 2's mark.16665 // The roster (latest-per-pair) reports one row, at seq 2's mark.
16610- let res = send(&app, "GET", &format!("/exams/{exam}/results"), Some(&teacher), None).await;16666+ let res = send(
16667+ &app,
16668+ "GET",
16669+ &format!("/exams/{exam}/results"),
16670+ Some(&teacher),
16671+ None,
16672+ )
16673+ .await;
16611 assert_eq!(res.status, StatusCode::OK, "{}", res.body);16674 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
16612 let rows = common::items(&res.body);16675 let rows = common::items(&res.body);
16613 assert_eq!(rows.len(), 1, "one grade-of-record per student");16676 assert_eq!(rows.len(), 1, "one grade-of-record per student");
@@ -16685,7 +16748,14 @@ async fn self_review_is_forbidden_until_the_teacher_enables_it() {
16685 )16748 )
16686 .await;16749 .await;
16687 16750
16688- send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await;16751+ send(
16752+ &app,
16753+ "POST",
16754+ &format!("/exams/{exam}/attempt"),
16755+ Some(&student),
16756+ None,
16757+ )
16758+ .await;
16689 let res = send(16759 let res = send(
16690 &app,16760 &app,
16691 "POST",16761 "POST",
@@ -16727,7 +16797,14 @@ async fn self_review_is_not_found_until_a_mark_exists() {
16727 .await;16797 .await;
16728 16798
16729 // Sat, but never graded — no ExamResult row.16799 // Sat, but never graded — no ExamResult row.
16730- send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await;16800+ send(
16801+ &app,
16802+ "POST",
16803+ &format!("/exams/{exam}/attempt"),
16804+ Some(&student),
16805+ None,
16806+ )
16807+ .await;
16731 16808
16732 let res = send(16809 let res = send(
16733 &app,16810 &app,
@@ -16806,7 +16883,14 @@ async fn self_review_returns_own_seqs_and_per_sitting_answers() {
16806 let results_uri = format!("/exams/{exam}/results");16883 let results_uri = format!("/exams/{exam}/results");
16807 16884
16808 // Seq 1: answer, grade, finish.16885 // Seq 1: answer, grade, finish.
16809- send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await;16886+ send(
16887+ &app,
16888+ "POST",
16889+ &format!("/exams/{exam}/attempt"),
16890+ Some(&student),
16891+ None,
16892+ )
16893+ .await;
16810 send(16894 send(
16811 &app,16895 &app,
16812 "POST",16896 "POST",
@@ -16823,9 +16907,23 @@ async fn self_review_returns_own_seqs_and_per_sitting_answers() {
16823 Some(json!({ "mark": 40, "user_id": student_id })),16907 Some(json!({ "mark": 40, "user_id": student_id })),
16824 )16908 )
16825 .await;16909 .await;
16826- send(&app, "POST", &format!("/exams/{exam}/attempt/finish"), Some(&student), None).await;16910+ send(
16911+ &app,
16912+ "POST",
16913+ &format!("/exams/{exam}/attempt/finish"),
16914+ Some(&student),
16915+ None,
16916+ )
16917+ .await;
16827 // Seq 2: retake, answer differently, grade.16918 // Seq 2: retake, answer differently, grade.
16828- send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await;16919+ send(
16920+ &app,
16921+ "POST",
16922+ &format!("/exams/{exam}/attempt"),
16923+ Some(&student),
16924+ None,
16925+ )
16926+ .await;
16829 send(16927 send(
16830 &app,16928 &app,
16831 "POST",16929 "POST",
@@ -16889,7 +16987,10 @@ async fn self_review_returns_own_seqs_and_per_sitting_answers() {
16889 assert_eq!(key.status, StatusCode::OK, "{}", key.body);16987 assert_eq!(key.status, StatusCode::OK, "{}", key.body);
16890 assert_eq!(key.body["items"][0]["id"], question);16988 assert_eq!(key.body["items"][0]["id"], question);
16891 assert!(16989 assert!(
16892- key.body["items"][0].as_object().unwrap().contains_key("correct"),16990+ key.body["items"][0]
16991+ .as_object()
16992+ .unwrap()
16993+ .contains_key("correct"),
16893 "review/questions must expose `correct`: {}",16994 "review/questions must expose `correct`: {}",
16894 key.body16995 key.body
16895 );16996 );
@@ -16933,7 +17034,14 @@ async fn self_review_is_own_scoped_between_students() {
16933 (&alice, &alice_id, "cicero", 70),17034 (&alice, &alice_id, "cicero", 70),
16934 (&bob, &bob_id, "cato", 30),17035 (&bob, &bob_id, "cato", 30),
16935 ] {17036 ] {
16936- send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(who), None).await;17037+ send(
17038+ &app,
17039+ "POST",
17040+ &format!("/exams/{exam}/attempt"),
17041+ Some(who),
17042+ None,
17043+ )
17044+ .await;
16937 send(17045 send(
16938 &app,17046 &app,
16939 "POST",17047 "POST",
@@ -16971,7 +17079,10 @@ async fn self_review_is_own_scoped_between_students() {
16971 None,17079 None,
16972 )17080 )
16973 .await;17081 .await;
16974- assert_eq!(sheet.body["answers"][0]["text"], "cicero", "A sees her own answer");17082+ assert_eq!(
17083+ sheet.body["answers"][0]["text"], "cicero",
17084+ "A sees her own answer"
17085+ );
16975 assert_ne!(sheet.body["answers"][0]["text"], "cato", "never B's answer");17086 assert_ne!(sheet.body["answers"][0]["text"], "cato", "never B's answer");
16976 }17087 }
16977 17088
@@ -17001,16 +17112,37 @@ async fn bank_question_create_get_list_and_instantiate() {
17001 let bid = id_of(&res.body);17112 let bid = id_of(&res.body);
17002 17113
17003 // School-wide read + list.17114 // School-wide read + list.
17004- let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await;17115+ let res = send(
17116+ &app,
17117+ "GET",
17118+ &format!("/bank-questions/{bid}"),
17119+ Some(&teacher),
17120+ None,
17121+ )
17122+ .await;
17005 assert_eq!(res.status, StatusCode::OK);17123 assert_eq!(res.status, StatusCode::OK);
17006 assert_eq!(res.body["text"], "2 + 2?");17124 assert_eq!(res.body["text"], "2 + 2?");
17007 let res = send(&app, "GET", "/bank-questions", Some(&teacher), None).await;17125 let res = send(&app, "GET", "/bank-questions", Some(&teacher), None).await;
17008 assert_eq!(common::items(&res.body).len(), 1);17126 assert_eq!(common::items(&res.body).len(), 1);
17009 17127
17010 // `?subject=` matches, and a foreign id excludes.17128 // `?subject=` matches, and a foreign id excludes.
17011- let res = send(&app, "GET", &format!("/bank-questions?subject={subject}"), Some(&teacher), None).await;17129+ let res = send(
17130+ &app,
17131+ "GET",
17132+ &format!("/bank-questions?subject={subject}"),
17133+ Some(&teacher),
17134+ None,
17135+ )
17136+ .await;
17012 assert_eq!(common::items(&res.body).len(), 1);17137 assert_eq!(common::items(&res.body).len(), 1);
17013- let res = send(&app, "GET", "/bank-questions?subject=nope", Some(&teacher), None).await;17138+ let res = send(
17139+ &app,
17140+ "GET",
17141+ "/bank-questions?subject=nope",
17142+ Some(&teacher),
17143+ None,
17144+ )
17145+ .await;
17014 assert_eq!(common::items(&res.body).len(), 0);17146 assert_eq!(common::items(&res.body).len(), 0);
17015 17147
17016 // Instantiate into an exam under one of the course's subjects.17148 // Instantiate into an exam under one of the course's subjects.
@@ -17038,7 +17170,14 @@ async fn bank_question_create_get_list_and_instantiate() {
17038 assert_eq!(res.body["choices"][1]["text"], "4");17170 assert_eq!(res.body["choices"][1]["text"], "4");
17039 17171
17040 // The copy is independent — the template still stands.17172 // The copy is independent — the template still stands.
17041- let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await;17173+ let res = send(
17174+ &app,
17175+ "GET",
17176+ &format!("/bank-questions/{bid}"),
17177+ Some(&teacher),
17178+ None,
17179+ )
17180+ .await;
17042 assert_eq!(res.status, StatusCode::OK);17181 assert_eq!(res.status, StatusCode::OK);
17043 }17182 }
17044 17183
@@ -17062,8 +17201,10 @@ async fn bank_question_list_pages_filters_and_names() {
17062 "POST",17201 "POST",
17063 "/bank-questions",17202 "/bank-questions",
17064 Some(&teacher),17203 Some(&teacher),
17065- Some(json!({ "subject_id": subject, "text": format!("template {i:03}"),17204+ Some(
17066- "kind": "text", "points": 1 })),17205+ json!({ "subject_id": subject, "text": format!("template {i:03}"),
17206+ "kind": "text", "points": 1 }),
17207+ ),
17067 )17208 )
17068 .await;17209 .await;
17069 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);17210 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
@@ -17074,19 +17215,35 @@ async fn bank_question_list_pages_filters_and_names() {
17074 "POST",17215 "POST",
17075 "/bank-questions",17216 "/bank-questions",
17076 Some(&other),17217 Some(&other),
17077- Some(json!({ "subject_id": other_subject, "text": "someone else's",17218+ Some(
17078- "kind": "text", "points": 1 })),17219+ json!({ "subject_id": other_subject, "text": "someone else's",
17220+ "kind": "text", "points": 1 }),
17221+ ),
17079 )17222 )
17080 .await;17223 .await;
17081 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);17224 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
17082 // Published, so it shows up in the first teacher's paging assertions below;17225 // Published, so it shows up in the first teacher's paging assertions below;
17083 // a private one would (correctly) be invisible to them.17226 // a private one would (correctly) be invisible to them.
17084 let foreign = id_of(&res.body);17227 let foreign = id_of(&res.body);
17085- let res = send(&app, "PATCH", &format!("/bank-questions/{foreign}"), Some(&other), Some(json!({ "visibility": "school" }))).await;17228+ let res = send(
17229+ &app,
17230+ "PATCH",
17231+ &format!("/bank-questions/{foreign}"),
17232+ Some(&other),
17233+ Some(json!({ "visibility": "school" })),
17234+ )
17235+ .await;
17086 assert_eq!(res.status, StatusCode::OK, "{}", res.body);17236 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
17087 17237
17088 // Page 1: newest first, full window, honest total.17238 // Page 1: newest first, full window, honest total.
17089- let res = send(&app, "GET", "/bank-questions?limit=100", Some(&teacher), None).await;17239+ let res = send(
17240+ &app,
17241+ "GET",
17242+ "/bank-questions?limit=100",
17243+ Some(&teacher),
17244+ None,
17245+ )
17246+ .await;
17090 assert_eq!(common::items(&res.body).len(), 100);17247 assert_eq!(common::items(&res.body).len(), 100);
17091 assert_eq!(res.body["total"], 121);17248 assert_eq!(res.body["total"], 121);
17092 assert_eq!(common::items(&res.body)[0]["text"], "someone else's");17249 assert_eq!(common::items(&res.body)[0]["text"], "someone else's");
@@ -17365,7 +17522,14 @@ async fn bank_question_search_folds_turkish_casing() {
17365 assert_eq!(res.body["total"], 1, "needle {needle} missed: {}", res.body);17522 assert_eq!(res.body["total"], 1, "needle {needle} missed: {}", res.body);
17366 }17523 }
17367 // Folding widens the match, it does not match everything.17524 // Folding widens the match, it does not match everything.
17368- let res = send(&app, "GET", "/bank-questions?q=ankara", Some(&teacher), None).await;17525+ let res = send(
17526+ &app,
17527+ "GET",
17528+ "/bank-questions?q=ankara",
17529+ Some(&teacher),
17530+ None,
17531+ )
17532+ .await;
17369 assert_eq!(res.body["total"], 0);17533 assert_eq!(res.body["total"], 0);
17370 }17534 }
17371 17535
@@ -17389,18 +17553,53 @@ async fn bank_question_owner_gate_cross_course_and_freeze() {
17389 let bid = id_of(&res.body);17553 let bid = id_of(&res.body);
17390 // Published, so this test is about the *owner* gate alone — the visibility17554 // Published, so this test is about the *owner* gate alone — the visibility
17391 // gate (404 while private) has its own test below.17555 // gate (404 while private) has its own test below.
17392- let res = send(&app, "PATCH", &format!("/bank-questions/{bid}"), Some(&owner), Some(json!({ "visibility": "school" }))).await;17556+ let res = send(
17557+ &app,
17558+ "PATCH",
17559+ &format!("/bank-questions/{bid}"),
17560+ Some(&owner),
17561+ Some(json!({ "visibility": "school" })),
17562+ )
17563+ .await;
17393 assert_eq!(res.status, StatusCode::OK, "{}", res.body);17564 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
17394 17565
17395 // A non-owner teacher reads it, but may not edit or delete.17566 // A non-owner teacher reads it, but may not edit or delete.
17396- let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&other), None).await;17567+ let res = send(
17568+ &app,
17569+ "GET",
17570+ &format!("/bank-questions/{bid}"),
17571+ Some(&other),
17572+ None,
17573+ )
17574+ .await;
17397 assert_eq!(res.status, StatusCode::OK);17575 assert_eq!(res.status, StatusCode::OK);
17398- let res = send(&app, "PATCH", &format!("/bank-questions/{bid}"), Some(&other), Some(json!({ "points": 7 }))).await;17576+ let res = send(
17577+ &app,
17578+ "PATCH",
17579+ &format!("/bank-questions/{bid}"),
17580+ Some(&other),
17581+ Some(json!({ "points": 7 })),
17582+ )
17583+ .await;
17399 assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);17584 assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
17400- let res = send(&app, "DELETE", &format!("/bank-questions/{bid}"), Some(&other), None).await;17585+ let res = send(
17586+ &app,
17587+ "DELETE",
17588+ &format!("/bank-questions/{bid}"),
17589+ Some(&other),
17590+ None,
17591+ )
17592+ .await;
17401 assert_eq!(res.status, StatusCode::FORBIDDEN);17593 assert_eq!(res.status, StatusCode::FORBIDDEN);
17402 // Admin bypasses ownership.17594 // Admin bypasses ownership.
17403- let res = send(&app, "PATCH", &format!("/bank-questions/{bid}"), Some(&admin), Some(json!({ "points": 7 }))).await;17595+ let res = send(
17596+ &app,
17597+ "PATCH",
17598+ &format!("/bank-questions/{bid}"),
17599+ Some(&admin),
17600+ Some(json!({ "points": 7 })),
17601+ )
17602+ .await;
17404 assert_eq!(res.status, StatusCode::OK, "{}", res.body);17603 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
17405 assert_eq!(res.body["points"], 7);17604 assert_eq!(res.body["points"], 7);
17406 17605
@@ -17430,7 +17629,14 @@ async fn bank_question_owner_gate_cross_course_and_freeze() {
17430 let student = login(&app, "sinem").await;17629 let student = login(&app, "sinem").await;
17431 let student_id = me_id(&app, &student).await;17630 let student_id = me_id(&app, &student).await;
17432 enroll(&app, &owner, &course, &student_id).await;17631 enroll(&app, &owner, &course, &student_id).await;
17433- let res = send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await;17632+ let res = send(
17633+ &app,
17634+ "POST",
17635+ &format!("/exams/{exam}/attempt"),
17636+ Some(&student),
17637+ None,
17638+ )
17639+ .await;
17434 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);17640 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
17435 let res = send(17641 let res = send(
17436 &app,17642 &app,
@@ -17485,8 +17691,14 @@ async fn bank_private_template_is_invisible_until_published() {
17485 17691
17486 let illus = b"private-illustration".as_slice();17692 let illus = b"private-illustration".as_slice();
17487 let pic = b"private-choice-pic".as_slice();17693 let pic = b"private-choice-pic".as_slice();
17488- let (status, _) =17694+ let (status, _) = post_image(
17489- post_image(&app, &owner, &format!("/bank-questions/{secret}/image"), "image/png", illus).await;17695+ &app,
17696+ &owner,
17697+ &format!("/bank-questions/{secret}/image"),
17698+ "image/png",
17699+ illus,
17700+ )
17701+ .await;
17490 assert_eq!(status, StatusCode::CREATED);17702 assert_eq!(status, StatusCode::CREATED);
17491 let (status, _) = post_image(17703 let (status, _) = post_image(
17492 &app,17704 &app,
@@ -17507,10 +17719,20 @@ async fn bank_private_template_is_invisible_until_published() {
17507 // --- the stranger sees nothing, and is told nothing ---17719 // --- the stranger sees nothing, and is told nothing ---
17508 let res = send(&app, "GET", "/bank-questions", Some(&other), None).await;17720 let res = send(&app, "GET", "/bank-questions", Some(&other), None).await;
17509 assert!(common::items(&res.body).is_empty());17721 assert!(common::items(&res.body).is_empty());
17510- assert_eq!(res.body["total"], 0, "total must count only visible templates");17722+ assert_eq!(
17511- let res = send(&app, "GET", &format!("/bank-questions/{secret}"), Some(&other), None).await;17723+ res.body["total"], 0,
17512- assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);17724+ "total must count only visible templates"
17513- let (status, _, _) = common::send_raw(17725+ );
17726+ let res = send(
17727+ &app,
17728+ "GET",
17729+ &format!("/bank-questions/{secret}"),
17730+ Some(&other),
17731+ None,
17732+ )
17733+ .await;
17734+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
17735+ let (status, _, _) = common::send_raw(
17514 &app,17736 &app,
17515 "GET",17737 "GET",
17516 &format!("/bank-questions/{secret}/image"),17738 &format!("/bank-questions/{secret}/image"),
@@ -17540,13 +17762,27 @@ async fn bank_private_template_is_invisible_until_published() {
17540 .await;17762 .await;
17541 assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);17763 assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
17542 // Not even by asking for the owner's templates by name.17764 // Not even by asking for the owner's templates by name.
17543- let res = send(&app, "GET", &format!("/bank-questions?owner={owner_id}"), Some(&other), None).await;17765+ let res = send(
17766+ &app,
17767+ "GET",
17768+ &format!("/bank-questions?owner={owner_id}"),
17769+ Some(&other),
17770+ None,
17771+ )
17772+ .await;
17544 assert_eq!(res.body["total"], 0);17773 assert_eq!(res.body["total"], 0);
17545 17774
17546 // --- the owner still has full use of their own template ---17775 // --- the owner still has full use of their own template ---
17547 let res = send(&app, "GET", "/bank-questions", Some(&owner), None).await;17776 let res = send(&app, "GET", "/bank-questions", Some(&owner), None).await;
17548 assert_eq!(res.body["total"], 2);17777 assert_eq!(res.body["total"], 2);
17549- let res = send(&app, "GET", &format!("/bank-questions/{secret}"), Some(&owner), None).await;17778+ let res = send(
17779+ &app,
17780+ "GET",
17781+ &format!("/bank-questions/{secret}"),
17782+ Some(&owner),
17783+ None,
17784+ )
17785+ .await;
17550 assert_eq!(res.status, StatusCode::OK, "{}", res.body);17786 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
17551 assert_eq!(res.body["correct"], res.body["choices"][0]["id"]);17787 assert_eq!(res.body["correct"], res.body["choices"][0]["id"]);
17552 let (status, _, bytes) = common::send_raw(17788 let (status, _, bytes) = common::send_raw(
@@ -17581,13 +17817,27 @@ async fn bank_private_template_is_invisible_until_published() {
17581 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);17817 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
17582 17818
17583 // --- publishing one template opens exactly that one ---17819 // --- publishing one template opens exactly that one ---
17584- let res = send(&app, "PATCH", &format!("/bank-questions/{shared}"), Some(&owner), Some(json!({ "visibility": "school" }))).await;17820+ let res = send(
17821+ &app,
17822+ "PATCH",
17823+ &format!("/bank-questions/{shared}"),
17824+ Some(&owner),
17825+ Some(json!({ "visibility": "school" })),
17826+ )
17827+ .await;
17585 assert_eq!(res.status, StatusCode::OK, "{}", res.body);17828 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
17586 assert_eq!(res.body["visibility"], "school");17829 assert_eq!(res.body["visibility"], "school");
17587 let res = send(&app, "GET", "/bank-questions", Some(&other), None).await;17830 let res = send(&app, "GET", "/bank-questions", Some(&other), None).await;
17588 assert_eq!(res.body["total"], 1, "the private one must still be hidden");17831 assert_eq!(res.body["total"], 1, "the private one must still be hidden");
17589 assert_eq!(common::items(&res.body)[0]["id"], shared);17832 assert_eq!(common::items(&res.body)[0]["id"], shared);
17590- let res = send(&app, "GET", &format!("/bank-questions/{shared}"), Some(&other), None).await;17833+ let res = send(
17834+ &app,
17835+ "GET",
17836+ &format!("/bank-questions/{shared}"),
17837+ Some(&other),
17838+ None,
17839+ )
17840+ .await;
17591 assert_eq!(res.status, StatusCode::OK, "{}", res.body);17841 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
17592 let res = send(17842 let res = send(
17593 &app,17843 &app,
@@ -17599,7 +17849,14 @@ async fn bank_private_template_is_invisible_until_published() {
17599 .await;17849 .await;
17600 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);17850 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
17601 // The still-private one stays shut on every path.17851 // The still-private one stays shut on every path.
17602- let res = send(&app, "GET", &format!("/bank-questions/{secret}"), Some(&other), None).await;17852+ let res = send(
17853+ &app,
17854+ "GET",
17855+ &format!("/bank-questions/{secret}"),
17856+ Some(&other),
17857+ None,
17858+ )
17859+ .await;
17603 assert_eq!(res.status, StatusCode::NOT_FOUND);17860 assert_eq!(res.status, StatusCode::NOT_FOUND);
17604 let res = send(17861 let res = send(
17605 &app,17862 &app,
@@ -17611,12 +17868,33 @@ async fn bank_private_template_is_invisible_until_published() {
17611 .await;17868 .await;
17612 assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);17869 assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
17613 // Unpublishing closes it again.17870 // Unpublishing closes it again.
17614- let res = send(&app, "PATCH", &format!("/bank-questions/{shared}"), Some(&owner), Some(json!({ "visibility": "private" }))).await;17871+ let res = send(
17872+ &app,
17873+ "PATCH",
17874+ &format!("/bank-questions/{shared}"),
17875+ Some(&owner),
17876+ Some(json!({ "visibility": "private" })),
17877+ )
17878+ .await;
17615 assert_eq!(res.status, StatusCode::OK, "{}", res.body);17879 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
17616- let res = send(&app, "GET", &format!("/bank-questions/{shared}"), Some(&other), None).await;17880+ let res = send(
17881+ &app,
17882+ "GET",
17883+ &format!("/bank-questions/{shared}"),
17884+ Some(&other),
17885+ None,
17886+ )
17887+ .await;
17617 assert_eq!(res.status, StatusCode::NOT_FOUND);17888 assert_eq!(res.status, StatusCode::NOT_FOUND);
17618 // A bogus value is a 400, not a silent publish.17889 // A bogus value is a 400, not a silent publish.
17619- let res = send(&app, "PATCH", &format!("/bank-questions/{shared}"), Some(&owner), Some(json!({ "visibility": "public" }))).await;17890+ let res = send(
17891+ &app,
17892+ "PATCH",
17893+ &format!("/bank-questions/{shared}"),
17894+ Some(&owner),
17895+ Some(json!({ "visibility": "public" })),
17896+ )
17897+ .await;
17620 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);17898 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
17621 }17899 }
17622 17900
@@ -17639,7 +17917,14 @@ async fn bank_private_template_is_visible_to_admins() {
17639 .await;17917 .await;
17640 let bid = id_of(&res.body);17918 let bid = id_of(&res.body);
17641 17919
17642- let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&admin), None).await;17920+ let res = send(
17921+ &app,
17922+ "GET",
17923+ &format!("/bank-questions/{bid}"),
17924+ Some(&admin),
17925+ None,
17926+ )
17927+ .await;
17643 assert_eq!(res.status, StatusCode::OK, "{}", res.body);17928 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
17644 let res = send(&app, "GET", "/bank-questions", Some(&admin), None).await;17929 let res = send(&app, "GET", "/bank-questions", Some(&admin), None).await;
17645 assert_eq!(res.body["total"], 1);17930 assert_eq!(res.body["total"], 1);
@@ -17661,7 +17946,14 @@ async fn exam_question_saves_to_bank() {
17661 )17946 )
17662 .await;17947 .await;
17663 17948
17664- let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await;17949+ let res = send(
17950+ &app,
17951+ "POST",
17952+ &format!("/exams/{exam}/questions/{qid}/to-bank"),
17953+ Some(&teacher),
17954+ None,
17955+ )
17956+ .await;
17665 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);17957 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
17666 assert_eq!(res.body["text"], "v=?");17958 assert_eq!(res.body["text"], "v=?");
17667 assert_eq!(res.body["correct"], res.body["choices"][0]["id"]);17959 assert_eq!(res.body["correct"], res.body["choices"][0]["id"]);
@@ -17673,7 +17965,14 @@ async fn exam_question_saves_to_bank() {
17673 let bid = id_of(&res.body);17965 let bid = id_of(&res.body);
17674 17966
17675 // It now lives in their bank.17967 // It now lives in their bank.
17676- let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await;17968+ let res = send(
17969+ &app,
17970+ "GET",
17971+ &format!("/bank-questions/{bid}"),
17972+ Some(&teacher),
17973+ None,
17974+ )
17975+ .await;
17677 assert_eq!(res.status, StatusCode::OK);17976 assert_eq!(res.status, StatusCode::OK);
17678 }17977 }
17679 17978
@@ -17703,8 +18002,14 @@ async fn bank_instantiate_copies_images() {
17703 18002
17704 let illus = b"bank-illustration".as_slice();18003 let illus = b"bank-illustration".as_slice();
17705 let choice = b"bank-choice-pic".as_slice();18004 let choice = b"bank-choice-pic".as_slice();
17706- let (status, _) =18005+ let (status, _) = post_image(
17707- post_image(&app, &teacher, &format!("/bank-questions/{bid}/image"), "image/png", illus).await;18006+ &app,
18007+ &teacher,
18008+ &format!("/bank-questions/{bid}/image"),
18009+ "image/png",
18010+ illus,
18011+ )
18012+ .await;
17708 assert_eq!(status, StatusCode::CREATED);18013 assert_eq!(status, StatusCode::CREATED);
17709 let (status, _) = post_image(18014 let (status, _) = post_image(
17710 &app,18015 &app,
@@ -17759,7 +18064,10 @@ async fn bank_instantiate_copies_images() {
17759 let exam_keys = image_blob_keys(&db).await;18064 let exam_keys = image_blob_keys(&db).await;
17760 assert_eq!(exam_keys.len(), 2);18065 assert_eq!(exam_keys.len(), 2);
17761 for k in &exam_keys {18066 for k in &exam_keys {
17762- assert!(!src_bank_keys.contains(k), "copied blob reused a source file");18067+ assert!(
18068+ !src_bank_keys.contains(k),
18069+ "copied blob reused a source file"
18070+ );
17763 }18071 }
17764 18072
17765 // Source bank images untouched — still 200 with the same bytes and keys.18073 // Source bank images untouched — still 200 with the same bytes and keys.
@@ -17785,7 +18093,11 @@ async fn bank_instantiate_copies_images() {
17785 .await;18093 .await;
17786 assert_eq!(status, StatusCode::OK);18094 assert_eq!(status, StatusCode::OK);
17787 assert_eq!(bytes, choice);18095 assert_eq!(bytes, choice);
17788- assert_eq!(bank_image_blob_keys(&db).await, src_bank_keys, "source keys changed");18096+ assert_eq!(
18097+ bank_image_blob_keys(&db).await,
18098+ src_bank_keys,
18099+ "source keys changed"
18100+ );
17789 }18101 }
17790 18102
17791 /// Saving an exam question to the bank copies its image blobs to fresh files18103 /// Saving an exam question to the bank copies its image blobs to fresh files
@@ -17871,9 +18183,16 @@ async fn bank_save_copies_images() {
17871 let bank_keys = bank_image_blob_keys(&db).await;18183 let bank_keys = bank_image_blob_keys(&db).await;
17872 assert_eq!(bank_keys.len(), 2);18184 assert_eq!(bank_keys.len(), 2);
17873 for k in &bank_keys {18185 for k in &bank_keys {
17874- assert!(!src_exam_keys.contains(k), "copied blob reused a source file");18186+ assert!(
18187+ !src_exam_keys.contains(k),
18188+ "copied blob reused a source file"
18189+ );
17875 }18190 }
17876- assert_eq!(image_blob_keys(&db).await, src_exam_keys, "source keys changed");18191+ assert_eq!(
18192+ image_blob_keys(&db).await,
18193+ src_exam_keys,
18194+ "source keys changed"
18195+ );
17877 let (status, _, bytes) = common::send_raw(18196 let (status, _, bytes) = common::send_raw(
17878 &app,18197 &app,
17879 "GET",18198 "GET",
@@ -17975,8 +18294,14 @@ async fn bank_instantiate_rolls_back_on_missing_source_blob() {
17975 .await;18294 .await;
17976 let bid = id_of(&res.body);18295 let bid = id_of(&res.body);
17977 let opt = choice_of(&res.body, 0);18296 let opt = choice_of(&res.body, 0);
17978- let (status, _) =18297+ let (status, _) = post_image(
17979- post_image(&app, &teacher, &format!("/bank-questions/{bid}/image"), "image/png", b"illus").await;18298+ &app,
18299+ &teacher,
18300+ &format!("/bank-questions/{bid}/image"),
18301+ "image/png",
18302+ b"illus",
18303+ )
18304+ .await;
17980 assert_eq!(status, StatusCode::CREATED);18305 assert_eq!(status, StatusCode::CREATED);
17981 let (status, _) = post_image(18306 let (status, _) = post_image(
17982 &app,18307 &app,
@@ -18005,12 +18330,24 @@ async fn bank_instantiate_rolls_back_on_missing_source_blob() {
18005 Some(json!({ "subject_id": subject })),18330 Some(json!({ "subject_id": subject })),
18006 )18331 )
18007 .await;18332 .await;
18008- assert_eq!(res.status, StatusCode::INTERNAL_SERVER_ERROR, "{}", res.body);18333+ assert_eq!(
18334+ res.status,
18335+ StatusCode::INTERNAL_SERVER_ERROR,
18336+ "{}",
18337+ res.body
18338+ );
18009 18339
18010 // No partial destination: no question row, no exam image rows (isolated18340 // No partial destination: no question row, no exam image rows (isolated
18011 // per-test DB is the race-safe source of truth; the shared parallel blob18341 // per-test DB is the race-safe source of truth; the shared parallel blob
18012 // dir rules out an exact on-disk diff).18342 // dir rules out an exact on-disk diff).
18013- let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await;18343+ let res = send(
18344+ &app,
18345+ "GET",
18346+ &format!("/exams/{exam}/questions"),
18347+ Some(&teacher),
18348+ None,
18349+ )
18350+ .await;
18014 assert!(18351 assert!(
18015 common::items(&res.body).is_empty(),18352 common::items(&res.body).is_empty(),
18016 "orphan question survived rollback"18353 "orphan question survived rollback"
@@ -18022,9 +18359,20 @@ async fn bank_instantiate_rolls_back_on_missing_source_blob() {
18022 18359
18023 // Source intact: the template still reads, and its surviving blob is still18360 // Source intact: the template still reads, and its surviving blob is still
18024 // on disk.18361 // on disk.
18025- let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await;18362+ let res = send(
18363+ &app,
18364+ "GET",
18365+ &format!("/bank-questions/{bid}"),
18366+ Some(&teacher),
18367+ None,
18368+ )
18369+ .await;
18026 assert_eq!(res.status, StatusCode::OK);18370 assert_eq!(res.status, StatusCode::OK);
18027- assert_eq!(bank_image_blob_keys(&db).await, src_keys, "source bank rows changed");18371+ assert_eq!(
18372+ bank_image_blob_keys(&db).await,
18373+ src_keys,
18374+ "source bank rows changed"
18375+ );
18028 assert!(18376 assert!(
18029 common::files_dir().join(&src_keys[1]).exists(),18377 common::files_dir().join(&src_keys[1]).exists(),
18030 "surviving source blob vanished"18378 "surviving source blob vanished"
@@ -18101,15 +18449,36 @@ async fn subject_delete_clears_the_bank_templates_subject() {
18101 let (bid, kept) = (&ids[0], &ids[1]);18449 let (bid, kept) = (&ids[0], &ids[1]);
18102 18450
18103 // The manager owns none of these templates, yet the delete goes through.18451 // The manager owns none of these templates, yet the delete goes through.
18104- let res = send(&app, "DELETE", &format!("/subjects/{subject}"), Some(&manager), None).await;18452+ let res = send(
18453+ &app,
18454+ "DELETE",
18455+ &format!("/subjects/{subject}"),
18456+ Some(&manager),
18457+ None,
18458+ )
18459+ .await;
18105 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);18460 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
18106 18461
18107 // The template survives with a cleared origin; the other one is untouched.18462 // The template survives with a cleared origin; the other one is untouched.
18108- let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await;18463+ let res = send(
18464+ &app,
18465+ "GET",
18466+ &format!("/bank-questions/{bid}"),
18467+ Some(&teacher),
18468+ None,
18469+ )
18470+ .await;
18109 assert_eq!(res.status, StatusCode::OK, "{}", res.body);18471 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
18110 assert_eq!(res.body["subject"], serde_json::Value::Null);18472 assert_eq!(res.body["subject"], serde_json::Value::Null);
18111 assert_eq!(res.body["text"], "q");18473 assert_eq!(res.body["text"], "q");
18112- let res = send(&app, "GET", &format!("/bank-questions/{kept}"), Some(&teacher), None).await;18474+ let res = send(
18475+ &app,
18476+ "GET",
18477+ &format!("/bank-questions/{kept}"),
18478+ Some(&teacher),
18479+ None,
18480+ )
18481+ .await;
18113 assert_eq!(res.body["subject"], json!(other));18482 assert_eq!(res.body["subject"], json!(other));
18114 18483
18115 // The list join renders the cleared one with an empty subject name.18484 // The list join renders the cleared one with an empty subject name.
@@ -18157,7 +18526,14 @@ async fn bank_owner_filter() {
18157 .await;18526 .await;
18158 // Published, so this test is about the owner filter, not visibility.18527 // Published, so this test is about the owner filter, not visibility.
18159 let bid = id_of(&res.body);18528 let bid = id_of(&res.body);
18160- let res = send(&app, "PATCH", &format!("/bank-questions/{bid}"), Some(who), Some(json!({ "visibility": "school" }))).await;18529+ let res = send(
18530+ &app,
18531+ "PATCH",
18532+ &format!("/bank-questions/{bid}"),
18533+ Some(who),
18534+ Some(json!({ "visibility": "school" })),
18535+ )
18536+ .await;
18161 assert_eq!(res.status, StatusCode::OK, "{}", res.body);18537 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
18162 }18538 }
18163 let alice_id = me_id(&app, &alice).await;18539 let alice_id = me_id(&app, &alice).await;
@@ -18174,7 +18550,14 @@ async fn bank_owner_filter() {
18174 assert_eq!(items[0]["owner"], alice_id);18550 assert_eq!(items[0]["owner"], alice_id);
18175 18551
18176 // An explicit id filters to that owner.18552 // An explicit id filters to that owner.
18177- let res = send(&app, "GET", &format!("/bank-questions?owner={bob_id}"), Some(&alice), None).await;18553+ let res = send(
18554+ &app,
18555+ "GET",
18556+ &format!("/bank-questions?owner={bob_id}"),
18557+ Some(&alice),
18558+ None,
18559+ )
18560+ .await;
18178 let items = common::items(&res.body);18561 let items = common::items(&res.body);
18179 assert_eq!(items.len(), 1);18562 assert_eq!(items.len(), 1);
18180 assert_eq!(items[0]["owner"], bob_id);18563 assert_eq!(items[0]["owner"], bob_id);
@@ -18204,8 +18587,14 @@ async fn bank_response_carries_image_metas() {
18204 assert!(res.body["image"].is_null());18587 assert!(res.body["image"].is_null());
18205 assert_eq!(res.body["choice_images"], json!([null, null]));18588 assert_eq!(res.body["choice_images"], json!([null, null]));
18206 18589
18207- let (status, _) =18590+ let (status, _) = post_image(
18208- post_image(&app, &teacher, &format!("/bank-questions/{bid}/image"), "image/png", b"illus").await;18591+ &app,
18592+ &teacher,
18593+ &format!("/bank-questions/{bid}/image"),
18594+ "image/png",
18595+ b"illus",
18596+ )
18597+ .await;
18209 assert_eq!(status, StatusCode::CREATED);18598 assert_eq!(status, StatusCode::CREATED);
18210 let (status, _) = post_image(18599 let (status, _) = post_image(
18211 &app,18600 &app,
@@ -18217,14 +18606,28 @@ async fn bank_response_carries_image_metas() {
18217 .await;18606 .await;
18218 assert_eq!(status, StatusCode::CREATED);18607 assert_eq!(status, StatusCode::CREATED);
18219 18608
18220- let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await;18609+ let res = send(
18610+ &app,
18611+ "GET",
18612+ &format!("/bank-questions/{bid}"),
18613+ Some(&teacher),
18614+ None,
18615+ )
18616+ .await;
18221 assert_eq!(res.body["image"]["content_type"], "image/png");18617 assert_eq!(res.body["image"]["content_type"], "image/png");
18222 assert_eq!(res.body["image"]["size"], 5);18618 assert_eq!(res.body["image"]["size"], 5);
18223 assert_eq!(res.body["choice_images"][0]["content_type"], "image/jpeg");18619 assert_eq!(res.body["choice_images"][0]["content_type"], "image/jpeg");
18224 assert!(res.body["choice_images"][1].is_null());18620 assert!(res.body["choice_images"][1].is_null());
18225 18621
18226 // The list carries them too (batched, not per-row).18622 // The list carries them too (batched, not per-row).
18227- let res = send(&app, "GET", "/bank-questions?owner=me", Some(&teacher), None).await;18623+ let res = send(
18624+ &app,
18625+ "GET",
18626+ "/bank-questions?owner=me",
18627+ Some(&teacher),
18628+ None,
18629+ )
18630+ .await;
18228 let items = common::items(&res.body);18631 let items = common::items(&res.body);
18229 assert_eq!(items[0]["image"]["content_type"], "image/png");18632 assert_eq!(items[0]["image"]["content_type"], "image/png");
18230 assert_eq!(items[0]["choice_images"][0]["content_type"], "image/jpeg");18633 assert_eq!(items[0]["choice_images"][0]["content_type"], "image/jpeg");
@@ -18278,7 +18681,14 @@ async fn bank_provenance_both_directions() {
18278 .await;18681 .await;
18279 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);18682 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
18280 let template = id_of(&res.body);18683 let template = id_of(&res.body);
18281- let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await;18684+ let res = send(
18685+ &app,
18686+ "GET",
18687+ &format!("/exams/{exam}/questions"),
18688+ Some(&teacher),
18689+ None,
18690+ )
18691+ .await;
18282 let question = common::items(&res.body)18692 let question = common::items(&res.body)
18283 .iter()18693 .iter()
18284 .find(|q| q["id"] == inserted)18694 .find(|q| q["id"] == inserted)
@@ -18298,12 +18708,26 @@ async fn bank_provenance_both_directions() {
18298 .await;18708 .await;
18299 18709
18300 // Exam -> bank: source_exam is the origin exam id.18710 // Exam -> bank: source_exam is the origin exam id.
18301- let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await;18711+ let res = send(
18712+ &app,
18713+ "POST",
18714+ &format!("/exams/{exam}/questions/{qid}/to-bank"),
18715+ Some(&teacher),
18716+ None,
18717+ )
18718+ .await;
18302 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);18719 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
18303 assert_eq!(res.body["source_exam"], exam);18720 assert_eq!(res.body["source_exam"], exam);
18304 18721
18305 // A directly authored template has no source_exam.18722 // A directly authored template has no source_exam.
18306- let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await;18723+ let res = send(
18724+ &app,
18725+ "GET",
18726+ &format!("/bank-questions/{bid}"),
18727+ Some(&teacher),
18728+ None,
18729+ )
18730+ .await;
18307 assert!(res.body["source_exam"].is_null());18731 assert!(res.body["source_exam"].is_null());
18308 }18732 }
18309 18733
@@ -18334,21 +18758,56 @@ async fn to_bank_links_the_question_at_the_new_template() {
18334 .expect("question in list")["banked_as"]18758 .expect("question in list")["banked_as"]
18335 .clone()18759 .clone()
18336 };18760 };
18337- let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await;18761+ let res = send(
18762+ &app,
18763+ "GET",
18764+ &format!("/exams/{exam}/questions"),
18765+ Some(&teacher),
18766+ None,
18767+ )
18768+ .await;
18338 assert!(banked_as_of(&res.body).is_null());18769 assert!(banked_as_of(&res.body).is_null());
18339 18770
18340- let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await;18771+ let res = send(
18772+ &app,
18773+ "POST",
18774+ &format!("/exams/{exam}/questions/{qid}/to-bank"),
18775+ Some(&teacher),
18776+ None,
18777+ )
18778+ .await;
18341 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);18779 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
18342 let first = id_of(&res.body);18780 let first = id_of(&res.body);
18343- let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await;18781+ let res = send(
18782+ &app,
18783+ "GET",
18784+ &format!("/exams/{exam}/questions"),
18785+ Some(&teacher),
18786+ None,
18787+ )
18788+ .await;
18344 assert_eq!(banked_as_of(&res.body), json!(first));18789 assert_eq!(banked_as_of(&res.body), json!(first));
18345 18790
18346 // Second save: still 201, a distinct template, and the link follows it.18791 // Second save: still 201, a distinct template, and the link follows it.
18347- let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await;18792+ let res = send(
18793+ &app,
18794+ "POST",
18795+ &format!("/exams/{exam}/questions/{qid}/to-bank"),
18796+ Some(&teacher),
18797+ None,
18798+ )
18799+ .await;
18348 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);18800 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
18349 let second = id_of(&res.body);18801 let second = id_of(&res.body);
18350 assert_ne!(first, second);18802 assert_ne!(first, second);
18351- let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await;18803+ let res = send(
18804+ &app,
18805+ "GET",
18806+ &format!("/exams/{exam}/questions"),
18807+ Some(&teacher),
18808+ None,
18809+ )
18810+ .await;
18352 assert_eq!(banked_as_of(&res.body), json!(second));18811 assert_eq!(banked_as_of(&res.body), json!(second));
18353 }18812 }
18354 18813
@@ -18406,7 +18865,14 @@ async fn linking_the_banked_template_does_not_clobber_a_concurrent_edit() {
18406 .expect("link written");18865 .expect("link written");
18407 18866
18408 // The edit survives and the link is set.18867 // The edit survives and the link is set.
18409- let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await;18868+ let res = send(
18869+ &app,
18870+ "GET",
18871+ &format!("/exams/{exam}/questions"),
18872+ Some(&teacher),
18873+ None,
18874+ )
18875+ .await;
18410 let question = common::items(&res.body)18876 let question = common::items(&res.body)
18411 .iter()18877 .iter()
18412 .find(|q| q["id"] == qid)18878 .find(|q| q["id"] == qid)
@@ -18442,7 +18908,14 @@ async fn a_bank_patch_does_not_clobber_a_concurrent_write() {
18442 json!({ "text": "original", "kind": "text", "points": 5 }),18908 json!({ "text": "original", "kind": "text", "points": 5 }),
18443 )18909 )
18444 .await;18910 .await;
18445- let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await;18911+ let res = send(
18912+ &app,
18913+ "POST",
18914+ &format!("/exams/{exam}/questions/{qid}/to-bank"),
18915+ Some(&teacher),
18916+ None,
18917+ )
18918+ .await;
18446 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);18919 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
18447 let bid = id_of(&res.body);18920 let bid = id_of(&res.body);
18448 assert_eq!(res.body["source_exam"], json!(exam));18921 assert_eq!(res.body["source_exam"], json!(exam));
@@ -18454,7 +18927,14 @@ async fn a_bank_patch_does_not_clobber_a_concurrent_write() {
18454 .unwrap()18927 .unwrap()
18455 .expect("template exists");18928 .expect("template exists");
18456 assert!(stale.get_source_exam().is_some());18929 assert!(stale.get_source_exam().is_some());
18457- let res = send(&app, "DELETE", &format!("/exams/{exam}"), Some(&teacher), None).await;18930+ let res = send(
18931+ &app,
18932+ "DELETE",
18933+ &format!("/exams/{exam}"),
18934+ Some(&teacher),
18935+ None,
18936+ )
18937+ .await;
18458 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);18938 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
18459 18939
18460 // The stale struct writes its own fields only.18940 // The stale struct writes its own fields only.
@@ -18470,10 +18950,20 @@ async fn a_bank_patch_does_not_clobber_a_concurrent_write() {
18470 .await18950 .await
18471 .expect("update written");18951 .expect("update written");
18472 assert_eq!(updated.get_text().as_str(), "edited");18952 assert_eq!(updated.get_text().as_str(), "edited");
18473- assert!(updated.get_source_exam().is_none(), "the dead exam link came back");18953+ assert!(
18954+ updated.get_source_exam().is_none(),
18955+ "the dead exam link came back"
18956+ );
18474 18957
18475 // The edit landed and the cleared provenance stayed cleared.18958 // The edit landed and the cleared provenance stayed cleared.
18476- let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await;18959+ let res = send(
18960+ &app,
18961+ "GET",
18962+ &format!("/bank-questions/{bid}"),
18963+ Some(&teacher),
18964+ None,
18965+ )
18966+ .await;
18477 assert_eq!(res.body["source_exam"], serde_json::Value::Null);18967 assert_eq!(res.body["source_exam"], serde_json::Value::Null);
18478 assert_eq!(res.body["subject"], serde_json::Value::Null);18968 assert_eq!(res.body["subject"], serde_json::Value::Null);
18479 assert_eq!(res.body["text"], "edited");18969 assert_eq!(res.body["text"], "edited");
@@ -18502,7 +18992,14 @@ async fn deleting_a_template_clears_both_question_links() {
18502 json!({ "text": "plain", "kind": "text", "points": 5 }),18992 json!({ "text": "plain", "kind": "text", "points": 5 }),
18503 )18993 )
18504 .await;18994 .await;
18505- let res = send(&app, "POST", &format!("/exams/{exam}/questions/{authored}/to-bank"), Some(&teacher), None).await;18995+ let res = send(
18996+ &app,
18997+ "POST",
18998+ &format!("/exams/{exam}/questions/{authored}/to-bank"),
18999+ Some(&teacher),
19000+ None,
19001+ )
19002+ .await;
18506 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);19003 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
18507 let saved = id_of(&res.body);19004 let saved = id_of(&res.body);
18508 19005
@@ -18534,20 +19031,49 @@ async fn deleting_a_template_clears_both_question_links() {
18534 .expect("question in list")[field]19031 .expect("question in list")[field]
18535 .clone()19032 .clone()
18536 };19033 };
18537- let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await;19034+ let res = send(
19035+ &app,
19036+ "GET",
19037+ &format!("/exams/{exam}/questions"),
19038+ Some(&teacher),
19039+ None,
19040+ )
19041+ .await;
18538 assert_eq!(link_of(&res.body, &authored, "banked_as"), json!(saved));19042 assert_eq!(link_of(&res.body, &authored, "banked_as"), json!(saved));
18539 assert_eq!(link_of(&res.body, &inserted, "from_bank"), json!(origin));19043 assert_eq!(link_of(&res.body, &inserted, "from_bank"), json!(origin));
18540 19044
18541 for bid in [&saved, &origin] {19045 for bid in [&saved, &origin] {
18542- let res = send(&app, "DELETE", &format!("/bank-questions/{bid}"), Some(&teacher), None).await;19046+ let res = send(
19047+ &app,
19048+ "DELETE",
19049+ &format!("/bank-questions/{bid}"),
19050+ Some(&teacher),
19051+ None,
19052+ )
19053+ .await;
18543 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);19054 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
18544 }19055 }
18545 19056
18546 // Both questions survive their templates with no dangling link.19057 // Both questions survive their templates with no dangling link.
18547- let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await;19058+ let res = send(
19059+ &app,
19060+ "GET",
19061+ &format!("/exams/{exam}/questions"),
19062+ Some(&teacher),
19063+ None,
19064+ )
19065+ .await;
18548 assert_eq!(res.status, StatusCode::OK, "{}", res.body);19066 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
18549- assert!(link_of(&res.body, &authored, "banked_as").is_null(), "{}", res.body);19067+ assert!(
18550- assert!(link_of(&res.body, &inserted, "from_bank").is_null(), "{}", res.body);19068+ link_of(&res.body, &authored, "banked_as").is_null(),
19069+ "{}",
19070+ res.body
19071+ );
19072+ assert!(
19073+ link_of(&res.body, &inserted, "from_bank").is_null(),
19074+ "{}",
19075+ res.body
19076+ );
18551 }19077 }
18552 19078
18553 /// The mirror: deleting the origin exam clears `source_exam` on the templates19079 /// The mirror: deleting the origin exam clears `source_exam` on the templates
@@ -18569,15 +19095,36 @@ async fn deleting_an_exam_clears_the_templates_source_exam() {
18569 )19095 )
18570 .await;19096 .await;
18571 19097
18572- let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await;19098+ let res = send(
19099+ &app,
19100+ "POST",
19101+ &format!("/exams/{exam}/questions/{qid}/to-bank"),
19102+ Some(&teacher),
19103+ None,
19104+ )
19105+ .await;
18573 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);19106 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
18574 let bid = id_of(&res.body);19107 let bid = id_of(&res.body);
18575 assert_eq!(res.body["source_exam"], exam);19108 assert_eq!(res.body["source_exam"], exam);
18576 19109
18577- let res = send(&app, "DELETE", &format!("/exams/{exam}"), Some(&teacher), None).await;19110+ let res = send(
19111+ &app,
19112+ "DELETE",
19113+ &format!("/exams/{exam}"),
19114+ Some(&teacher),
19115+ None,
19116+ )
19117+ .await;
18578 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);19118 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
18579 19119
18580- let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await;19120+ let res = send(
19121+ &app,
19122+ "GET",
19123+ &format!("/bank-questions/{bid}"),
19124+ Some(&teacher),
19125+ None,
19126+ )
19127+ .await;
18581 assert_eq!(res.status, StatusCode::OK, "{}", res.body);19128 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
18582 assert!(res.body["source_exam"].is_null(), "{}", res.body);19129 assert!(res.body["source_exam"].is_null(), "{}", res.body);
18583 }19130 }
@@ -18635,7 +19182,14 @@ async fn bank_list_counts_the_copies_made_from_each_template() {
18635 )19182 )
18636 .await;19183 .await;
18637 19184
18638- let res = send(&app, "GET", "/bank-questions?limit=100", Some(&teacher), None).await;19185+ let res = send(
19186+ &app,
19187+ "GET",
19188+ "/bank-questions?limit=100",
19189+ Some(&teacher),
19190+ None,
19191+ )
19192+ .await;
18639 assert_eq!(res.status, StatusCode::OK, "{}", res.body);19193 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
18640 let counts: std::collections::HashMap<String, i64> = common::items(&res.body)19194 let counts: std::collections::HashMap<String, i64> = common::items(&res.body)
18641 .iter()19195 .iter()
@@ -18663,7 +19217,14 @@ async fn bank_list_counts_the_copies_made_from_each_template() {
18663 )19217 )
18664 .await;19218 .await;
18665 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);19219 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
18666- let res = send(&app, "GET", "/bank-questions?limit=100", Some(&teacher), None).await;19220+ let res = send(
19221+ &app,
19222+ "GET",
19223+ "/bank-questions?limit=100",
19224+ Some(&teacher),
19225+ None,
19226+ )
19227+ .await;
18667 let after = common::items(&res.body)19228 let after = common::items(&res.body)
18668 .iter()19229 .iter()
18669 .find(|item| id_of(item) == used)19230 .find(|item| id_of(item) == used)
@@ -18672,7 +19233,14 @@ async fn bank_list_counts_the_copies_made_from_each_template() {
18672 assert_eq!(after["used_count"], 2, "{}", res.body);19233 assert_eq!(after["used_count"], 2, "{}", res.body);
18673 19234
18674 // List-only, like the other joined fields: the single-template GET says 0.19235 // List-only, like the other joined fields: the single-template GET says 0.
18675- let res = send(&app, "GET", &format!("/bank-questions/{used}"), Some(&teacher), None).await;19236+ let res = send(
19237+ &app,
19238+ "GET",
19239+ &format!("/bank-questions/{used}"),
19240+ Some(&teacher),
19241+ None,
19242+ )
19243+ .await;
18676 assert_eq!(res.body["used_count"], 0, "{}", res.body);19244 assert_eq!(res.body["used_count"], 0, "{}", res.body);
18677 }19245 }
18678 19246
@@ -18802,13 +19370,21 @@ async fn refreshing_a_question_recopies_its_template() {
18802 assert_eq!(res.body["points"], 7);19370 assert_eq!(res.body["points"], 7);
18803 assert_eq!(res.body["subject"], subject, "the exam-side subject stays");19371 assert_eq!(res.body["subject"], subject, "the exam-side subject stays");
18804 assert_eq!(res.body["from_bank"], bid, "provenance survives");19372 assert_eq!(res.body["from_bank"], bid, "provenance survives");
18805- assert_eq!(choice_of(&res.body, 0), keep_choice, "template choice ids adopted");19373+ assert_eq!(
19374+ choice_of(&res.body, 0),
19375+ keep_choice,
19376+ "template choice ids adopted"
19377+ );
18806 assert_eq!(choice_of(&res.body, 1), fresh_choice);19378 assert_eq!(choice_of(&res.body, 1), fresh_choice);
18807 assert_eq!(res.body["choices"][1]["text"], "Marseille");19379 assert_eq!(res.body["choices"][1]["text"], "Marseille");
18808 assert_eq!(res.body["correct"], keep_choice);19380 assert_eq!(res.body["correct"], keep_choice);
18809 // Pictures match the template: the new illustration landed, and the19381 // Pictures match the template: the new illustration landed, and the
18810 // dropped option's picture is gone rather than orphaned on a stale slot.19382 // dropped option's picture is gone rather than orphaned on a stale slot.
18811- assert_eq!(res.body["image"]["content_type"], "image/png", "{}", res.body);19383+ assert_eq!(
19384+ res.body["image"]["content_type"], "image/png",
19385+ "{}",
19386+ res.body
19387+ );
18812 assert!(res.body["choice_images"][0].is_null(), "{}", res.body);19388 assert!(res.body["choice_images"][0].is_null(), "{}", res.body);
18813 assert!(res.body["choice_images"][1].is_null(), "{}", res.body);19389 assert!(res.body["choice_images"][1].is_null(), "{}", res.body);
18814 let (status, _, bytes) = common::send_raw(19390 let (status, _, bytes) = common::send_raw(
@@ -18821,7 +19397,10 @@ async fn refreshing_a_question_recopies_its_template() {
18821 )19397 )
18822 .await;19398 .await;
18823 assert_eq!(status, StatusCode::OK);19399 assert_eq!(status, StatusCode::OK);
18824- assert_eq!(bytes, b"new-illustration", "the blob was re-copied, not kept");19400+ assert_eq!(
19401+ bytes, b"new-illustration",
19402+ "the blob was re-copied, not kept"
19403+ );
18825 // No orphan blob rows left behind by the dropped option.19404 // No orphan blob rows left behind by the dropped option.
18826 assert_eq!(image_blob_keys(&db).await.len(), 1);19405 assert_eq!(image_blob_keys(&db).await.len(), 1);
18827 19406
@@ -18869,7 +19448,14 @@ async fn refreshing_a_question_recopies_its_template() {
18869 let student = login(&app, "bref_s").await;19448 let student = login(&app, "bref_s").await;
18870 let student_id = me_id(&app, &student).await;19449 let student_id = me_id(&app, &student).await;
18871 enroll(&app, &teacher, &course, &student_id).await;19450 enroll(&app, &teacher, &course, &student_id).await;
18872- let res = send(&app, "POST", &format!("/exams/{live}/attempt"), Some(&student), None).await;19451+ let res = send(
19452+ &app,
19453+ "POST",
19454+ &format!("/exams/{live}/attempt"),
19455+ Some(&student),
19456+ None,
19457+ )
19458+ .await;
18873 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);19459 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
18874 let res = send(19460 let res = send(
18875 &app,19461 &app,
@@ -18883,7 +19469,14 @@ async fn refreshing_a_question_recopies_its_template() {
18883 19469
18884 // Deleting the template clears `from_bank`, so the copy has nothing left to19470 // Deleting the template clears `from_bank`, so the copy has nothing left to
18885 // refresh from — the action stops existing rather than half-working.19471 // refresh from — the action stops existing rather than half-working.
18886- let res = send(&app, "DELETE", &format!("/bank-questions/{bid}"), Some(&teacher), None).await;19472+ let res = send(
19473+ &app,
19474+ "DELETE",
19475+ &format!("/bank-questions/{bid}"),
19476+ Some(&teacher),
19477+ None,
19478+ )
19479+ .await;
18887 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);19480 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
18888 let res = send(19481 let res = send(
18889 &app,19482 &app,
@@ -18955,10 +19548,21 @@ async fn a_course_patch_does_not_clobber_a_concurrent_teacher_assignment() {
18955 )19548 )
18956 .await19549 .await
18957 .expect("update written");19550 .expect("update written");
18958- assert_eq!(updated.get_teachers().len(), 1, "the assignment was reverted");19551+ assert_eq!(
19552+ updated.get_teachers().len(),
19553+ 1,
19554+ "the assignment was reverted"
19555+ );
18959 19556
18960 // The rename landed and the assigned teacher stayed assigned.19557 // The rename landed and the assigned teacher stayed assigned.
18961- let res = send(&app, "GET", &format!("/courses/{course}"), Some(&owner), None).await;19558+ let res = send(
19559+ &app,
19560+ "GET",
19561+ &format!("/courses/{course}"),
19562+ Some(&owner),
19563+ None,
19564+ )
19565+ .await;
18962 assert_eq!(res.body["title"], "renamed");19566 assert_eq!(res.body["title"], "renamed");
18963 assert_eq!(res.body["teachers"][0]["username"], "cclob_h");19567 assert_eq!(res.body["teachers"][0]["username"], "cclob_h");
18964 }19568 }
@@ -19023,7 +19627,14 @@ async fn staffing_a_course_does_not_clobber_a_concurrent_edit() {
19023 assert_eq!(dropped.get_title().as_str(), "edited again");19627 assert_eq!(dropped.get_title().as_str(), "edited again");
19024 assert!(dropped.get_teachers().is_empty());19628 assert!(dropped.get_teachers().is_empty());
19025 19629
19026- let res = send(&app, "GET", &format!("/courses/{course}"), Some(&owner), None).await;19630+ let res = send(
19631+ &app,
19632+ "GET",
19633+ &format!("/courses/{course}"),
19634+ Some(&owner),
19635+ None,
19636+ )
19637+ .await;
19027 assert_eq!(res.body["title"], "edited again");19638 assert_eq!(res.body["title"], "edited again");
19028 assert_eq!(res.body["capacity"], 9);19639 assert_eq!(res.body["capacity"], 9);
19029 assert_eq!(res.body["teachers"].as_array().unwrap().len(), 0);19640 assert_eq!(res.body["teachers"].as_array().unwrap().len(), 0);
tests/persistence.rsmodified+59 -16
@@ -357,7 +357,10 @@ async fn legacy_subjectless_questions_are_destroyed_on_boot() {
357 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);357 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
358 let question_id = common::id_of(&res.body);358 let question_id = common::id_of(&res.body);
359 // Choice ids are minted server-side, so the answer names one off the response.359 // Choice ids are minted server-side, so the answer names one off the response.
360- let picked = res.body["choices"][1]["id"].as_str().expect("choice id").to_string();360+ let picked = res.body["choices"][1]["id"]
361+ .as_str()
362+ .expect("choice id")
363+ .to_string();
361 let res = send(364 let res = send(
362 &app,365 &app,
363 "POST",366 "POST",
@@ -748,14 +751,26 @@ async fn attempt_history_survives_remigration() {
748 );751 );
749 }752 }
750 set_role(&db, "ali", "teacher").await;753 set_role(&db, "ali", "teacher").await;
751- let teacher = send(&app, "POST", "/auth/login", None, Some(teacher_creds.clone()))754+ let teacher = send(
752- .await755+ &app,
753- .cookie756+ "POST",
754- .unwrap();757+ "/auth/login",
755- let student = send(&app, "POST", "/auth/login", None, Some(student_creds.clone()))758+ None,
756- .await759+ Some(teacher_creds.clone()),
757- .cookie760+ )
758- .unwrap();761+ .await
762+ .cookie
763+ .unwrap();
764+ let student = send(
765+ &app,
766+ "POST",
767+ "/auth/login",
768+ None,
769+ Some(student_creds.clone()),
770+ )
771+ .await
772+ .cookie
773+ .unwrap();
759 let student_id = me_id(&app, &student).await;774 let student_id = me_id(&app, &student).await;
760 775
761 let course = create_course(&app, &teacher, "biology").await;776 let course = create_course(&app, &teacher, "biology").await;
@@ -786,9 +801,15 @@ async fn attempt_history_survives_remigration() {
786 // Two sittings: distinct answer text + distinct mark on each.801 // Two sittings: distinct answer text + distinct mark on each.
787 for (text, mark) in [("mitochondria", 40), ("chloroplast", 90)] {802 for (text, mark) in [("mitochondria", 40), ("chloroplast", 90)] {
788 assert_eq!(803 assert_eq!(
789- send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None)804+ send(
790- .await805+ &app,
791- .status,806+ "POST",
807+ &format!("/exams/{exam}/attempt"),
808+ Some(&student),
809+ None
810+ )
811+ .await
812+ .status,
792 StatusCode::CREATED813 StatusCode::CREATED
793 );814 );
794 let res = send(815 let res = send(
@@ -809,7 +830,14 @@ async fn attempt_history_survives_remigration() {
809 )830 )
810 .await;831 .await;
811 assert_eq!(res.status, StatusCode::OK, "{}", res.body);832 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
812- send(&app, "POST", &format!("/exams/{exam}/attempt/finish"), Some(&student), None).await;833+ send(
834+ &app,
835+ "POST",
836+ &format!("/exams/{exam}/attempt/finish"),
837+ Some(&student),
838+ None,
839+ )
840+ .await;
813 }841 }
814 842
815 // Second boot: migration re-applied over the two sittings' live rows.843 // Second boot: migration re-applied over the two sittings' live rows.
@@ -859,9 +887,24 @@ async fn attempt_history_survives_remigration() {
859 .iter()887 .iter()
860 .map(|r| r["mark"].as_i64().unwrap())888 .map(|r| r["mark"].as_i64().unwrap())
861 .collect();889 .collect();
862- assert_eq!(marks, vec![40, 90], "both sittings' marks durable, oldest first");890+ assert_eq!(
863- let res = send(&app, "GET", &format!("/exams/{exam}/results"), Some(&teacher), None).await;891+ marks,
864- assert_eq!(common::items(&res.body)[0]["mark"], 90, "seq 2 is grade-of-record");892+ vec![40, 90],
893+ "both sittings' marks durable, oldest first"
894+ );
895+ let res = send(
896+ &app,
897+ "GET",
898+ &format!("/exams/{exam}/results"),
899+ Some(&teacher),
900+ None,
901+ )
902+ .await;
903+ assert_eq!(
904+ common::items(&res.body)[0]["mark"],
905+ 90,
906+ "seq 2 is grade-of-record"
907+ );
865 }908 }
866 909
867 /// A chatbot thread and every turn in it die together: deleting the910 /// A chatbot thread and every turn in it die together: deleting the