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

name_refs.rs357 lines, 11.4 KiBHistoryRawDownload
1//! The settings' two removal guards, now that they are reference counters
2//! rather than a count-then-write under a process-wide lock: an exam kind may
3//! leave `exam_kinds` only while no mark is written under it, and a meal slot
4//! may leave `meal_slots` only while no menu is published for it.
5//!
6//! Each test below bites on one half of the pair — the retirement's `WHERE`
7//! (nothing may leave while it is referenced) or the claim's (nothing may be
8//! referenced once it has left). Drop either predicate and a test here fails;
9//! that is the point of the suite, because the guard itself is invisible in
10//! the happy path.
11
12mod common;
13
14use axum::http::StatusCode;
15use common::{create_exam, enroll, login_as, me_id, send, taught};
16use serde_json::{Value, json};
17
18/// The two kinds these tests move in and out of the school's list.
19fn kinds(names: &[&str]) -> Value {
20 json!(
21 names
22 .iter()
23 .map(|name| json!({ "name": name, "weight": 1 }))
24 .collect::<Vec<_>>()
25 )
26}
27
28fn slots(names: &[&str]) -> Value {
29 json!(
30 names
31 .iter()
32 .map(|name| json!({ "name": name, "serving_minute": 720 }))
33 .collect::<Vec<_>>()
34 )
35}
36
37fn listed_kinds(body: &Value) -> Vec<String> {
38 body["exam_kinds"]
39 .as_array()
40 .expect("exam_kinds")
41 .iter()
42 .map(|kind| kind["name"].as_str().expect("name").to_string())
43 .collect()
44}
45
46/// A graded student, an exam of `kind`, and the manager's cookie.
47struct School {
48 app: axum::Router,
49 boss: String,
50 instance: String,
51 term: String,
52 exam: String,
53 student: String,
54}
55
56async fn school_with_kinds(names: &[&str]) -> School {
57 let (app, db) = common::app_and_db().await;
58 let boss = login_as(&app, &db, "boss", "manager").await;
59 let student_cookie = login_as(&app, &db, "kid", "student").await;
60 let student = me_id(&app, &student_cookie).await;
61 let res = send(
62 &app,
63 "PATCH",
64 "/settings",
65 Some(&boss),
66 Some(json!({ "exam_kinds": kinds(names) })),
67 )
68 .await;
69 assert_eq!(res.status, StatusCode::OK, "seed exam kinds");
70 // The instance is the anchor: exams, marks and rosters hang off it, not the
71 // catalog course. A manager mints the şube (school structure) and is its
72 // homeroom teacher too, so the same cookie keeps rights over the instance.
73 let t = taught(&app, &boss, "Maths").await;
74 enroll(&app, &boss, &t.instance, &student).await;
75 let exam = create_exam(&app, &boss, &t.instance, &t.term, "Midterm", names[0]).await;
76 School {
77 app,
78 boss,
79 instance: t.instance,
80 term: t.term,
81 exam,
82 student,
83 }
84}
85
86impl School {
87 async fn grade(&self, mark: i64) -> common::Res {
88 self.grade_exam(&self.exam.clone(), mark).await
89 }
90
91 async fn grade_exam(&self, exam: &str, mark: i64) -> common::Res {
92 send(
93 &self.app,
94 "POST",
95 &format!("/exams/{exam}/results"),
96 Some(&self.boss),
97 Some(json!({ "user_id": self.student, "mark": mark })),
98 )
99 .await
100 }
101
102 async fn set_kinds(&self, names: &[&str]) -> common::Res {
103 send(
104 &self.app,
105 "PATCH",
106 "/settings",
107 Some(&self.boss),
108 Some(json!({ "exam_kinds": kinds(names) })),
109 )
110 .await
111 }
112
113 async fn settings(&self) -> Value {
114 send(&self.app, "GET", "/settings", Some(&self.boss), None)
115 .await
116 .body
117 }
118}
119
120/// The retirement's `WHERE`: a kind a mark is written under does not leave the
121/// list, and the refused edit changes *nothing* — not the stored list, and not
122/// the kind's own usability.
123#[tokio::test]
124async fn a_graded_kind_cannot_be_removed_and_nothing_moves() {
125 let school = school_with_kinds(&["lab", "quiz"]).await;
126 assert_eq!(school.grade(80).await.status, StatusCode::OK);
127
128 let res = school.set_kinds(&["quiz"]).await;
129 assert_eq!(res.status, StatusCode::CONFLICT);
130 assert_eq!(
131 res.body["error"],
132 "exams of kind 'lab' are already graded — the kind cannot be removed"
133 );
134
135 // The list the school reads back still carries the kind...
136 assert_eq!(listed_kinds(&school.settings().await), ["lab", "quiz"]);
137 // ...and so does the counter: a refused removal must not leave the kind
138 // retired, or every later grade under it would be refused instead.
139 assert_eq!(school.grade(90).await.status, StatusCode::OK);
140}
141
142/// A regrade is not a second reference: one mark, one reference, however many
143/// times it is overwritten — otherwise the counter would drift upward and the
144/// kind could never be removed again.
145#[tokio::test]
146async fn marks_release_their_kind_when_they_are_deleted() {
147 let school = school_with_kinds(&["lab", "quiz"]).await;
148 for mark in [10, 20, 30] {
149 assert_eq!(school.grade(mark).await.status, StatusCode::OK);
150 }
151
152 let res = send(
153 &school.app,
154 "DELETE",
155 &format!("/exams/{}/results/{}", school.exam, school.student),
156 Some(&school.boss),
157 None,
158 )
159 .await;
160 assert_eq!(res.status, StatusCode::NO_CONTENT);
161
162 // Nothing is graded under it any more, so it leaves freely.
163 assert_eq!(school.set_kinds(&["quiz"]).await.status, StatusCode::OK);
164 assert_eq!(listed_kinds(&school.settings().await), ["quiz"]);
165}
166
167/// The claim's `WHERE`, the other half of the same race: once the kind is out
168/// of the list, a mark can no longer land under it. Whichever of the two
169/// writes reaches the counter first, the other is refused — which is what makes
170/// the pair safe without a lock spanning both writes.
171#[tokio::test]
172async fn a_removed_kind_refuses_a_grade() {
173 let school = school_with_kinds(&["lab", "quiz"]).await;
174 // Nothing graded yet, so the kind leaves — the exam keeps carrying it.
175 assert_eq!(school.set_kinds(&["quiz"]).await.status, StatusCode::OK);
176
177 let res = school.grade(80).await;
178 assert_eq!(res.status, StatusCode::CONFLICT);
179 assert_eq!(
180 res.body["error"],
181 "the 'lab' exam kind has been removed from the school's settings — \
182 add it back before grading this exam"
183 );
184
185 // Adding it back puts it in service again.
186 assert_eq!(
187 school.set_kinds(&["quiz", "lab"]).await.status,
188 StatusCode::OK
189 );
190 assert_eq!(school.grade(80).await.status, StatusCode::OK);
191}
192
193/// An exam's kind is frozen once it carries marks: re-pointing it would
194/// re-weight them silently (and strand their references on the kind they were
195/// counted under). Ungraded, it moves freely — and its next mark is counted
196/// under the kind it moved to.
197#[tokio::test]
198async fn a_graded_exams_kind_is_frozen() {
199 let school = school_with_kinds(&["lab", "quiz"]).await;
200 let repoint = async || {
201 send(
202 &school.app,
203 "PATCH",
204 &format!("/exams/{}", school.exam),
205 Some(&school.boss),
206 Some(json!({ "kind": "quiz" })),
207 )
208 .await
209 };
210 // Ungraded: the move lands.
211 assert_eq!(repoint().await.status, StatusCode::OK);
212 assert_eq!(school.grade(80).await.status, StatusCode::OK);
213 // The mark went to the kind the exam now carries, not the one it left.
214 assert_eq!(school.set_kinds(&["quiz"]).await.status, StatusCode::OK);
215 assert_eq!(
216 school.set_kinds(&["lab", "quiz"]).await.status,
217 StatusCode::OK
218 );
219
220 // Graded: the move is refused, and the exam keeps the kind it had.
221 let back = send(
222 &school.app,
223 "PATCH",
224 &format!("/exams/{}", school.exam),
225 Some(&school.boss),
226 Some(json!({ "kind": "lab" })),
227 )
228 .await;
229 assert_eq!(back.status, StatusCode::CONFLICT);
230 assert_eq!(
231 back.body["error"],
232 "cannot change the kind of an exam that already has marks"
233 );
234 // Everything else on the exam still edits, marks or no marks.
235 let title = send(
236 &school.app,
237 "PATCH",
238 &format!("/exams/{}", school.exam),
239 Some(&school.boss),
240 Some(json!({ "title": "Midterm II" })),
241 )
242 .await;
243 assert_eq!(title.status, StatusCode::OK);
244}
245
246/// Deleting an exam frees exactly the marks it cascaded — no more. Two exams
247/// share the kind here: releasing one mark too many (the shape a count taken
248/// outside the cascade's transaction produces) would read as no marks left and
249/// let the kind walk out of the settings while the second exam is still graded.
250#[tokio::test]
251async fn deleting_one_exam_frees_only_its_own_marks() {
252 let school = school_with_kinds(&["lab", "quiz"]).await;
253 let second = create_exam(
254 &school.app,
255 &school.boss,
256 &school.instance,
257 &school.term,
258 "Final",
259 "lab",
260 )
261 .await;
262 assert_eq!(school.grade(80).await.status, StatusCode::OK);
263 assert_eq!(school.grade_exam(&second, 70).await.status, StatusCode::OK);
264
265 let gone = send(
266 &school.app,
267 "DELETE",
268 &format!("/exams/{}", school.exam),
269 Some(&school.boss),
270 None,
271 )
272 .await;
273 assert_eq!(gone.status, StatusCode::NO_CONTENT);
274
275 // The other exam's mark still holds the kind down.
276 let refused = school.set_kinds(&["quiz"]).await;
277 assert_eq!(refused.status, StatusCode::CONFLICT);
278 assert_eq!(
279 refused.body["error"],
280 "exams of kind 'lab' are already graded — the kind cannot be removed"
281 );
282
283 // Only when the last graded exam goes does the kind go free.
284 let last = send(
285 &school.app,
286 "DELETE",
287 &format!("/exams/{second}"),
288 Some(&school.boss),
289 None,
290 )
291 .await;
292 assert_eq!(last.status, StatusCode::NO_CONTENT);
293 assert_eq!(school.set_kinds(&["quiz"]).await.status, StatusCode::OK);
294}
295
296/// The same pair for meal slots, whose reference is a published menu.
297#[tokio::test]
298async fn a_published_menu_pins_its_meal_slot() {
299 let (app, db) = common::app_and_db().await;
300 let boss = login_as(&app, &db, "boss", "manager").await;
301 let set_slots = async |names: &[&str]| {
302 send(
303 &app,
304 "PATCH",
305 "/settings",
306 Some(&boss),
307 Some(json!({ "meal_slots": slots(names) })),
308 )
309 .await
310 };
311 assert_eq!(set_slots(&["lunch", "snack"]).await.status, StatusCode::OK);
312
313 let menu = send(
314 &app,
315 "POST",
316 "/meals/menus",
317 Some(&boss),
318 Some(json!({ "date": "2030-01-09", "slot": "lunch" })),
319 )
320 .await;
321 assert_eq!(menu.status, StatusCode::CREATED);
322 let menu_id = common::id_of(&menu.body);
323
324 let refused = set_slots(&["snack"]).await;
325 assert_eq!(refused.status, StatusCode::CONFLICT);
326 assert_eq!(
327 refused.body["error"],
328 "menus are already published for the 'lunch' slot — it cannot be removed"
329 );
330
331 // Retire the menu and the slot is free to leave — then no new menu may be
332 // published under it.
333 let deleted = send(
334 &app,
335 "DELETE",
336 &format!("/meals/menus/{menu_id}"),
337 Some(&boss),
338 None,
339 )
340 .await;
341 assert_eq!(deleted.status, StatusCode::NO_CONTENT);
342 assert_eq!(set_slots(&["snack"]).await.status, StatusCode::OK);
343
344 let late = send(
345 &app,
346 "POST",
347 "/meals/menus",
348 Some(&boss),
349 Some(json!({ "date": "2030-01-10", "slot": "lunch" })),
350 )
351 .await;
352 assert_eq!(
353 late.status,
354 StatusCode::BAD_REQUEST,
355 "slot is no longer served"
356 );
357}