forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

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

exam_answer.rs262 lines, 9.0 KiBHistoryRawDownload
1use crate::constant::MAX_ANSWER_TEXT_LEN;
2use crate::domain::exam::ExamId;
3use crate::domain::exam_question::{ChoiceId, ExamQuestion, ExamQuestionId};
4use crate::domain::key;
5use crate::domain::timestamp::Timestamp;
6use crate::domain::user::UserId;
7use crate::error::ValidationError;
8use crate::validate::validate_optional;
9
10/// The identity of one (question, user, seq) triple — a sitting's answer. Not
11/// a row column: the table's primary key *is* the triple, which is what makes
12/// saving a single atomic UPSERT keyed by seq: re-answering *within a sitting*
13/// overwrites its one row, but a retake's `seq` writes a new row, so every
14/// sitting keeps its own answer history. See [`key::sitting`] for the wire
15/// shape and why the first sitting stays bare.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct ExamAnswerId {
18 pub(crate) question: ExamQuestionId,
19 pub(crate) user: UserId,
20 pub(crate) seq: i64,
21}
22
23impl ExamAnswerId {
24 pub fn composite(question: &ExamQuestionId, user: &UserId, seq: i64) -> Self {
25 Self {
26 question: question.clone(),
27 user: *user,
28 seq,
29 }
30 }
31
32 /// The underscore-joined wire form (`{question}_{user}[_{seq}]`).
33 pub fn key(&self) -> String {
34 key::sitting(
35 self.question.key().as_str(),
36 self.user.key().as_str(),
37 self.seq,
38 )
39 }
40}
41
42/// A free-text answer: may be empty (a student clearing their draft is a valid
43/// save), at most `MAX_ANSWER_TEXT_LEN` characters.
44#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
45#[sqlx(transparent)]
46pub struct AnswerText(String);
47
48impl AnswerText {
49 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
50 validate_optional("text", value, MAX_ANSWER_TEXT_LEN)?;
51 Ok(Self(value.to_string()))
52 }
53
54 pub fn as_str(&self) -> &str {
55 &self.0
56 }
57}
58
59/// One student's answer to one question, autosaved as they type or pick.
60/// `exam` is denormalized from the question so per-exam reads (live monitor,
61/// cascades) don't fan out through `exam_question`.
62#[derive(Debug, Clone, sqlx::FromRow)]
63pub struct ExamAnswer {
64 pub(crate) exam: ExamId,
65 pub(crate) question: ExamQuestionId,
66 #[sqlx(rename = "app_user")]
67 pub(crate) user: UserId,
68 pub(crate) seq: i64,
69 pub(crate) selected: Option<ChoiceId>,
70 pub(crate) text: Option<AnswerText>,
71 pub(crate) updated_at: Timestamp,
72}
73
74impl ExamAnswer {
75 /// The row's identity, built back from its primary-key columns.
76 pub fn get_id(&self) -> ExamAnswerId {
77 ExamAnswerId::composite(&self.question, &self.user, self.seq)
78 }
79
80 pub fn get_exam(&self) -> &ExamId {
81 &self.exam
82 }
83
84 pub fn get_question(&self) -> &ExamQuestionId {
85 &self.question
86 }
87
88 pub fn get_user(&self) -> &UserId {
89 &self.user
90 }
91
92 /// Which sitting this answer belongs to — 1 for the first attempt, up.
93 pub fn get_seq(&self) -> i64 {
94 self.seq
95 }
96
97 pub fn get_selected(&self) -> Option<&ChoiceId> {
98 self.selected.as_ref()
99 }
100
101 pub fn get_text(&self) -> Option<&AnswerText> {
102 self.text.as_ref()
103 }
104
105 pub fn get_updated_at(&self) -> Timestamp {
106 self.updated_at
107 }
108
109 /// Whether this answer hits the question's correct choice. `None` for a
110 /// text question — correctness is the grader's call, not the machine's.
111 pub fn is_correct(&self, question: &ExamQuestion) -> Option<bool> {
112 let correct = question.get_correct()?;
113 Some(self.selected.as_ref() == Some(correct))
114 }
115}
116
117/// The choice-question score suggested by the machine: `earned` points from
118/// answers hitting `correct`, out of `possible` points across all choice
119/// questions. Text questions never count — the final mark stays a human call
120/// (`POST /exams/{id}/results`).
121pub fn auto_score(questions: &[ExamQuestion], answers: &[ExamAnswer]) -> (i64, i64) {
122 let mut earned = 0;
123 let mut possible = 0;
124 for question in questions {
125 let Some(correct) = question.get_correct() else {
126 continue;
127 };
128 possible += question.get_points().as_i64();
129 if answers
130 .iter()
131 .any(|a| a.get_question() == question.get_id() && a.get_selected() == Some(correct))
132 {
133 earned += question.get_points().as_i64();
134 }
135 }
136 (earned, possible)
137}
138
139#[cfg(test)]
140mod tests {
141 use super::*;
142 use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec};
143
144 /// A three-option question whose `correct` is the option at `correct`.
145 /// Positions are a *test* convenience only — the ids are minted, and every
146 /// assertion below goes through `choice_id`.
147 fn choice_question(exam: &ExamId, points: i64, correct: usize) -> ExamQuestion {
148 let labels = ["a", "b", "c"];
149 let spec = QuestionSpec::try_new(
150 QuestionKind::try_new("choice").unwrap(),
151 Some(
152 labels
153 .iter()
154 .map(|l| ChoiceInput {
155 id: Some((*l).into()),
156 text: (*l).into(),
157 })
158 .collect(),
159 ),
160 Some(labels[correct].into()),
161 &[],
162 )
163 .unwrap();
164 ExamQuestion::test_new(exam, "pick one", points, spec)
165 }
166
167 fn text_question(exam: &ExamId, points: i64) -> ExamQuestion {
168 let spec =
169 QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap();
170 ExamQuestion::test_new(exam, "explain", points, spec)
171 }
172
173 /// The minted id of the question's option at `index`.
174 fn choice_id(question: &ExamQuestion, index: usize) -> ChoiceId {
175 question.get_choices().unwrap()[index].get_id().clone()
176 }
177
178 fn answer(question: &ExamQuestion, user: &UserId, selected: Option<usize>) -> ExamAnswer {
179 let selected = selected.map(|index| choice_id(question, index));
180 ExamAnswer {
181 exam: question.get_exam().clone(),
182 question: question.get_id().clone(),
183 user: *user,
184 seq: 1,
185 text: selected
186 .is_none()
187 .then(|| AnswerText::try_new("essay").unwrap()),
188 selected,
189 updated_at: Timestamp::from_millis(1),
190 }
191 }
192
193 fn student() -> UserId {
194 UserId::from_key("0198f1a2-3b4c-7d5e-8f90-aa2b3c4d5e6f")
195 }
196
197 #[tokio::test]
198 async fn seqs_key_distinct_rows_but_seq_one_keeps_the_bare_key() {
199 let question = ExamQuestionId::from_key("0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f");
200 let user = student();
201 // seq 1 keeps the pre-history bare `{question}_{user}` key…
202 let first = ExamAnswerId::composite(&question, &user, 1);
203 assert_eq!(
204 first.key(),
205 format!("{}_{}", question.key(), user.key()),
206 "seq 1 stays addressable at its historical key"
207 );
208 // …and a later sitting is a *different* id, so its answer is a new row.
209 let second = ExamAnswerId::composite(&question, &user, 2);
210 assert_ne!(first, second, "two seqs must not collide onto one row");
211 assert_eq!(second.key(), format!("{}_{}_2", question.key(), user.key()));
212 }
213
214 #[tokio::test]
215 async fn answer_text_may_be_empty_but_bounded() {
216 assert!(AnswerText::try_new("").is_ok());
217 assert!(AnswerText::try_new(&"x".repeat(10_000)).is_ok());
218 assert!(AnswerText::try_new(&"x".repeat(10_001)).is_err());
219 }
220
221 #[tokio::test]
222 async fn auto_score_counts_correct_choices_only() {
223 let exam = ExamId::from_key("0198f1a2-3b4c-7d5e-8f90-be2b3c4d5e6f");
224 let user = student();
225 let q1 = choice_question(&exam, 10, 0); // answered right
226 let q2 = choice_question(&exam, 20, 1); // answered wrong
227 let q3 = choice_question(&exam, 30, 2); // unanswered
228 let q4 = text_question(&exam, 40); // never auto-scored
229 let questions = vec![q1.clone(), q2.clone(), q3, q4.clone()];
230 let answers = vec![
231 answer(&q1, &user, Some(0)),
232 answer(&q2, &user, Some(0)),
233 answer(&q4, &user, None),
234 ];
235 assert_eq!(auto_score(&questions, &answers), (10, 60));
236 }
237
238 #[tokio::test]
239 async fn auto_score_of_nothing_is_zero() {
240 assert_eq!(auto_score(&[], &[]), (0, 0));
241 let exam = ExamId::from_key("0198f1a2-3b4c-7d5e-8f90-be2b3c4d5e6f");
242 let questions = vec![text_question(&exam, 50)];
243 assert_eq!(auto_score(&questions, &[]), (0, 0));
244 }
245
246 #[tokio::test]
247 async fn is_correct_judges_choice_questions_only() {
248 let exam = ExamId::from_key("0198f1a2-3b4c-7d5e-8f90-be2b3c4d5e6f");
249 let user = student();
250 let choice = choice_question(&exam, 10, 1);
251 assert_eq!(
252 answer(&choice, &user, Some(1)).is_correct(&choice),
253 Some(true)
254 );
255 assert_eq!(
256 answer(&choice, &user, Some(0)).is_correct(&choice),
257 Some(false)
258 );
259 let text = text_question(&exam, 10);
260 assert_eq!(answer(&text, &user, None).is_correct(&text), None);
261 }
262}