forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBc9b707aAhmet Kaan Gümüş4 months ago189 commits

classes.rs613 lines, 24.4 KiBHistoryRawDownload
1//! Classes (şube): a named set of students the school moves as one.
2//!
3//! Nothing here is a second kind of membership — adding a student to a class
4//! enrolls them into every course the class carries, and attaching a course
5//! enrolls the whole roster into it, as real `enrollment` rows. So the two
6//! write axes are gated exactly like the writes they stand in for: the class
7//! and its roster are the office's (manager+), while attaching a course writes
8//! *that course's* roster and takes the same right enrolling into it does.
9
10use axum::Json;
11use axum::extract::{Path, Query, State};
12use axum::http::StatusCode;
13use serde::{Deserialize, Serialize};
14use utoipa::ToSchema;
15use utoipa_axum::router::OpenApiRouter;
16use utoipa_axum::routes;
17
18use crate::database::Database;
19use crate::domain::class_course::ClassCourse;
20use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName};
21use crate::domain::class_member::ClassMember;
22use crate::domain::course::{Course, CourseId};
23use crate::domain::role::Role;
24use crate::domain::user::{User, UserId};
25use crate::error::{AppError, ErrorResponse, ValidationError};
26use crate::state::AppState;
27
28use super::courses::can_manage_course;
29use super::terms::resolve_term;
30use super::{
31 Page, PageParams, PersonRef, RequireManager, RequireTeacher, person_map, set_or_clear,
32};
33
34pub fn routes() -> OpenApiRouter<AppState> {
35 OpenApiRouter::new()
36 .routes(routes!(create_class, list_classes))
37 .routes(routes!(get_class, update_class, delete_class))
38 .routes(routes!(add_member, list_members))
39 .routes(routes!(remove_member))
40 .routes(routes!(attach_course, list_class_courses))
41 .routes(routes!(detach_course))
42}
43
44#[derive(Deserialize, ToSchema)]
45struct CreateClass {
46 #[schema(max_length = 200, example = "9-A")]
47 name: String,
48 /// The school's own label for the year this class sits in ("9", "10-A",
49 /// "anaokulu"). Free text; omit (or send `""`) for a class with no grade.
50 #[schema(max_length = 20, example = "9")]
51 grade: Option<String>,
52 /// The academic term this class belongs to (`GET /terms`). Optional.
53 term_id: Option<String>,
54}
55
56#[derive(Deserialize, ToSchema)]
57struct UpdateClass {
58 #[schema(max_length = 200)]
59 name: Option<String>,
60 /// Omit to keep the current grade, send `null` (or `""`) to clear it, or
61 /// send a label to (re)set it.
62 #[serde(default, deserialize_with = "set_or_clear")]
63 #[schema(value_type = Option<String>, max_length = 20)]
64 grade: Option<Option<String>>,
65 /// Omit to keep the current term, send `null` to unlink, or send a term id
66 /// to (re)assign.
67 #[serde(default, deserialize_with = "set_or_clear")]
68 #[schema(value_type = Option<String>)]
69 term_id: Option<Option<String>>,
70}
71
72#[derive(Deserialize, ToSchema)]
73struct AddMember {
74 /// The student to put in the class.
75 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
76 user_id: String,
77}
78
79#[derive(Deserialize, ToSchema)]
80struct AttachCourse {
81 /// The course the whole class takes.
82 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
83 course_id: String,
84}
85
86#[derive(Serialize, ToSchema)]
87struct ClassResponse {
88 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
89 id: String,
90 /// Who created the class.
91 creator: PersonRef,
92 #[schema(example = "9-A")]
93 name: String,
94 /// The school's own free-text grade label; `null` when the class has none.
95 #[schema(example = "9")]
96 grade: Option<String>,
97 /// The academic term this class belongs to (`GET /terms`); `null` when
98 /// unassigned.
99 term: Option<String>,
100}
101
102impl ClassResponse {
103 fn new(class: &ClassGroup, people: &std::collections::HashMap<String, PersonRef>) -> Self {
104 Self {
105 id: class.get_id().key().to_string(),
106 creator: PersonRef::resolve(people, class.get_creator()),
107 name: class.get_name().as_str().to_string(),
108 grade: class.get_grade().map(|g| g.as_str().to_string()),
109 term: class.get_term().map(|term| term.key().to_string()),
110 }
111 }
112}
113
114#[derive(Serialize, ToSchema)]
115struct ClassMemberResponse {
116 id: String,
117 class: String,
118 /// The student in the class.
119 user: PersonRef,
120 /// Who put them there.
121 added_by: PersonRef,
122}
123
124impl ClassMemberResponse {
125 fn new(member: &ClassMember, people: &std::collections::HashMap<String, PersonRef>) -> Self {
126 Self {
127 id: member.get_id().key().to_string(),
128 class: member.get_class().key().to_string(),
129 user: PersonRef::resolve(people, member.get_user()),
130 added_by: PersonRef::resolve(people, member.get_added_by()),
131 }
132 }
133}
134
135#[derive(Serialize, ToSchema)]
136struct ClassCourseResponse {
137 id: String,
138 class: String,
139 /// The course the class takes.
140 course: String,
141 /// Who attached it.
142 attached_by: PersonRef,
143}
144
145impl ClassCourseResponse {
146 fn new(link: &ClassCourse, people: &std::collections::HashMap<String, PersonRef>) -> Self {
147 Self {
148 id: link.get_id().key().to_string(),
149 class: link.get_class().key().to_string(),
150 course: link.get_course().key().to_string(),
151 attached_by: PersonRef::resolve(people, link.get_attached_by()),
152 }
153 }
154}
155
156/// The class a path id names, or a 404 — every route under `/classes/{id}`
157/// gates on it, so a missing class never reads as an empty roster.
158async fn class_or_404(id: &str, db: &Database) -> Result<ClassGroup, AppError> {
159 ClassGroup::read(&ClassGroupId::from_key(id), db)
160 .await?
161 .ok_or(AppError::NotFound)
162}
163
164/// An empty grade is *no* grade: the column is nullable, so a client that omits
165/// it and one that sends `""` must land on the same stored row.
166fn grade_or_none(text: Option<&str>) -> Result<Option<ClassGrade>, AppError> {
167 match text {
168 None | Some("") => Ok(None),
169 Some(text) => Ok(Some(ClassGrade::try_new(text)?)),
170 }
171}
172
173/// Create a class. Requires manager+ — a class is school structure, not a
174/// teacher's own room. `grade` is a free-text label for the year ("9", "10-A"),
175/// `term_id` links the school calendar; both optional.
176#[utoipa::path(
177 post,
178 path = "/",
179 tag = "classes",
180 security(("session_cookie" = [])),
181 request_body = CreateClass,
182 responses(
183 (status = 201, description = "Class created", body = ClassResponse),
184 (status = 400, description = "Invalid name or grade, or an unknown term", body = ErrorResponse),
185 (status = 401, description = "Not authenticated", body = ErrorResponse),
186 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
187 ),
188)]
189async fn create_class(
190 State(st): State<AppState>,
191 RequireManager(user): RequireManager,
192 Json(req): Json<CreateClass>,
193) -> Result<(StatusCode, Json<ClassResponse>), AppError> {
194 let name = ClassName::try_new(&req.name)?;
195 let grade = grade_or_none(req.grade.as_deref())?;
196 // Pre-flight only: `ClassGroup::create` claims a reference on the term
197 // before it writes the link, and a term deleted in between fails that claim
198 // with this very error — so an unknown id reads the same whichever side wins.
199 let term = resolve_term(req.term_id.as_deref(), &st.db).await?;
200 let class = ClassGroup::create(user.get_id(), name, grade, term, &st.db).await?;
201 // The creator is the caller — already loaded, no extra lookup.
202 let people = PersonRef::map_of(&[&user]);
203 Ok((
204 StatusCode::CREATED,
205 Json(ClassResponse::new(&class, &people)),
206 ))
207}
208
209/// List every class, newest first. Requires teacher+. Paged via `?limit=&offset=`
210/// (omit `limit` for the full list); returns a `{items, total, limit, offset}`
211/// envelope.
212#[utoipa::path(
213 get,
214 path = "/",
215 tag = "classes",
216 security(("session_cookie" = [])),
217 params(PageParams),
218 responses(
219 (status = 200, description = "A page of classes (the full list when unpaged)", body = Page<ClassResponse>),
220 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
221 (status = 401, description = "Not authenticated", body = ErrorResponse),
222 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
223 ),
224)]
225async fn list_classes(
226 State(st): State<AppState>,
227 RequireTeacher(_user): RequireTeacher,
228 Query(page): Query<PageParams>,
229) -> Result<Json<Page<ClassResponse>>, AppError> {
230 let (limit, offset) = page.resolve()?;
231 let (classes, total) = ClassGroup::list_all(limit, offset, &st.db).await?;
232 // Join creators onto the page alone — the lookup shrinks with the window.
233 let people = person_map(
234 classes.iter().map(|class| class.get_creator().clone()),
235 &st.db,
236 )
237 .await?;
238 let items = classes
239 .iter()
240 .map(|class| ClassResponse::new(class, &people))
241 .collect();
242 Ok(Json(Page::new(items, total, limit, offset)))
243}
244
245/// Fetch a single class by id. Requires teacher+.
246#[utoipa::path(
247 get,
248 path = "/{id}",
249 tag = "classes",
250 security(("session_cookie" = [])),
251 params(("id" = String, Path, description = "Class id")),
252 responses(
253 (status = 200, description = "The class", body = ClassResponse),
254 (status = 401, description = "Not authenticated", body = ErrorResponse),
255 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
256 (status = 404, description = "Not found", body = ErrorResponse),
257 ),
258)]
259async fn get_class(
260 State(st): State<AppState>,
261 RequireTeacher(_user): RequireTeacher,
262 Path(id): Path<String>,
263) -> Result<Json<ClassResponse>, AppError> {
264 let class = class_or_404(&id, &st.db).await?;
265 let people = person_map(std::iter::once(class.get_creator().clone()), &st.db).await?;
266 Ok(Json(ClassResponse::new(&class, &people)))
267}
268
269/// Update a class. Requires manager+. Omitted fields keep their value; `grade`
270/// and `term_id` are nullable, so an explicit `null` clears them.
271#[utoipa::path(
272 patch,
273 path = "/{id}",
274 tag = "classes",
275 security(("session_cookie" = [])),
276 params(("id" = String, Path, description = "Class id")),
277 request_body = UpdateClass,
278 responses(
279 (status = 200, description = "Updated class", body = ClassResponse),
280 (status = 400, description = "Invalid name or grade, or an unknown term", body = ErrorResponse),
281 (status = 401, description = "Not authenticated", body = ErrorResponse),
282 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
283 (status = 404, description = "Not found", body = ErrorResponse),
284 (status = 409, description = "The term this update moves the class off changed since the caller read it — nothing was written, re-read and retry", body = ErrorResponse),
285 ),
286)]
287async fn update_class(
288 State(st): State<AppState>,
289 RequireManager(_user): RequireManager,
290 Path(id): Path<String>,
291 Json(req): Json<UpdateClass>,
292) -> Result<Json<ClassResponse>, AppError> {
293 let class = class_or_404(&id, &st.db).await?;
294
295 // Only what the request actually carried is validated and written — an
296 // omitted field stays `None` so the save never re-sends this snapshot's
297 // value over a concurrent PATCH of that field.
298 let name = req.name.as_deref().map(ClassName::try_new).transpose()?;
299 let grade = match req.grade {
300 Some(ref update) => Some(grade_or_none(update.as_deref())?),
301 None => None,
302 };
303 let term = match req.term_id {
304 // Explicit `null` clears the link; a value must name a real term.
305 Some(ref update) => Some(resolve_term(update.as_deref(), &st.db).await?),
306 None => None,
307 };
308
309 let updated = class.update(name, grade, term, &st.db).await?;
310 let people = person_map(std::iter::once(updated.get_creator().clone()), &st.db).await?;
311 Ok(Json(ClassResponse::new(&updated, &people)))
312}
313
314/// Delete a class. Requires manager+. Refused with a 409 while it still holds
315/// students or courses — nothing cascades, because dropping the class silently
316/// would leave the enrollments it pumped with nothing left to sweep them.
317#[utoipa::path(
318 delete,
319 path = "/{id}",
320 tag = "classes",
321 security(("session_cookie" = [])),
322 params(("id" = String, Path, description = "Class id")),
323 responses(
324 (status = 204, description = "Deleted"),
325 (status = 401, description = "Not authenticated", body = ErrorResponse),
326 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
327 (status = 404, description = "Not found", body = ErrorResponse),
328 (status = 409, description = "Students or courses are still on this class", body = ErrorResponse),
329 ),
330)]
331async fn delete_class(
332 State(st): State<AppState>,
333 RequireManager(_user): RequireManager,
334 Path(id): Path<String>,
335) -> Result<StatusCode, AppError> {
336 let class = class_or_404(&id, &st.db).await?;
337 if !class.delete(&st.db).await? {
338 return Err(AppError::Conflict(
339 "this class still holds students or courses — remove its members and detach its courses first",
340 ));
341 }
342 Ok(StatusCode::NO_CONTENT)
343}
344
345// ---- members ---------------------------------------------------------------
346
347/// Put a student in a class. Requires manager+. They are enrolled into every
348/// course the class already carries, in one go: a course with no free seat
349/// refuses the whole join with a 409 naming it, and a student already enrolled
350/// by hand keeps the row they have (no second seat, and it survives their
351/// removal from the class). Adding the same student twice is a 409.
352#[utoipa::path(
353 post,
354 path = "/{id}/members",
355 tag = "classes",
356 security(("session_cookie" = [])),
357 params(("id" = String, Path, description = "Class id")),
358 request_body = AddMember,
359 responses(
360 (status = 201, description = "Student added to the class", body = ClassMemberResponse),
361 (status = 400, description = "Unknown user, or user is not a student", body = ErrorResponse),
362 (status = 401, description = "Not authenticated", body = ErrorResponse),
363 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
364 (status = 404, description = "Class not found", body = ErrorResponse),
365 (status = 409, description = "Already in this class, or one of its courses is full", body = ErrorResponse),
366 ),
367)]
368async fn add_member(
369 State(st): State<AppState>,
370 RequireManager(user): RequireManager,
371 Path(id): Path<String>,
372 Json(req): Json<AddMember>,
373) -> Result<(StatusCode, Json<ClassMemberResponse>), AppError> {
374 let class = class_or_404(&id, &st.db).await?;
375
376 let target = UserId::from_key(&req.user_id);
377 let Some(target_user) = User::read(&target, &st.db).await? else {
378 return Err(AppError::Validation(ValidationError::Invalid {
379 field: "user_id",
380 reason: "target user does not exist",
381 }));
382 };
383 // A class membership is enrollment in bulk, and enrollment is student
384 // membership — the same bar `POST /courses/{id}/enrollments` holds.
385 if target_user.get_role() != Role::Student {
386 return Err(AppError::Validation(ValidationError::Invalid {
387 field: "user_id",
388 reason: "only students can be added to a class",
389 }));
390 }
391
392 let member = ClassMember::add(class.get_id(), &target, user.get_id(), &st.db).await?;
393 let people = PersonRef::map_of(&[&target_user, &user]);
394 Ok((
395 StatusCode::CREATED,
396 Json(ClassMemberResponse::new(&member, &people)),
397 ))
398}
399
400/// List a class's roster, newest first, paged via `?limit=&offset=` (omit
401/// `limit` for the whole roster). Requires teacher+. Returns a
402/// `{items, total, limit, offset}` envelope.
403#[utoipa::path(
404 get,
405 path = "/{id}/members",
406 tag = "classes",
407 security(("session_cookie" = [])),
408 params(("id" = String, Path, description = "Class id"), PageParams),
409 responses(
410 (status = 200, description = "A page of class members (the whole roster when unpaged)", body = Page<ClassMemberResponse>),
411 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
412 (status = 401, description = "Not authenticated", body = ErrorResponse),
413 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
414 (status = 404, description = "Class not found", body = ErrorResponse),
415 ),
416)]
417async fn list_members(
418 State(st): State<AppState>,
419 RequireTeacher(_user): RequireTeacher,
420 Path(id): Path<String>,
421 Query(page): Query<PageParams>,
422) -> Result<Json<Page<ClassMemberResponse>>, AppError> {
423 let (limit, offset) = page.resolve()?;
424 let class = class_or_404(&id, &st.db).await?;
425 let (rows, total) = ClassMember::list_for_class(class.get_id(), limit, offset, &st.db).await?;
426 // Join people onto the page alone — the lookup shrinks with the window.
427 let people = person_map(
428 rows.iter()
429 .flat_map(|row| [row.get_user().clone(), row.get_added_by().clone()]),
430 &st.db,
431 )
432 .await?;
433 let items = rows
434 .iter()
435 .map(|row| ClassMemberResponse::new(row, &people))
436 .collect();
437 Ok(Json(Page::new(items, total, limit, offset)))
438}
439
440/// Take a student out of a class. Requires manager+. The enrollments the class
441/// pumped for them are swept with it — except rows another attached class still
442/// claims (re-tagged to it) and rows placed by hand (left standing). A student
443/// who was not in the class is a 404.
444#[utoipa::path(
445 delete,
446 path = "/{id}/members/{user}",
447 tag = "classes",
448 security(("session_cookie" = [])),
449 params(
450 ("id" = String, Path, description = "Class id"),
451 ("user" = String, Path, description = "User id"),
452 ),
453 responses(
454 (status = 204, description = "Removed"),
455 (status = 401, description = "Not authenticated", body = ErrorResponse),
456 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
457 (status = 404, description = "Class not found, or that student was not in it", body = ErrorResponse),
458 ),
459)]
460async fn remove_member(
461 State(st): State<AppState>,
462 RequireManager(_user): RequireManager,
463 Path((id, target)): Path<(String, String)>,
464) -> Result<StatusCode, AppError> {
465 let class = class_or_404(&id, &st.db).await?;
466 ClassMember::remove(class.get_id(), &UserId::from_key(&target), &st.db).await?;
467 Ok(StatusCode::NO_CONTENT)
468}
469
470// ---- attached courses ------------------------------------------------------
471
472/// Attach a course to a class. Requires teacher+ and management rights **on
473/// that course** — attaching writes its roster, so it takes exactly the right
474/// enrolling into it does. The class's whole roster is enrolled in one go: a
475/// course that cannot hold all of them takes none (409), and students already
476/// enrolled by hand keep their own rows. Attaching the same course twice is a
477/// 409.
478#[utoipa::path(
479 post,
480 path = "/{id}/courses",
481 tag = "classes",
482 security(("session_cookie" = [])),
483 params(("id" = String, Path, description = "Class id")),
484 request_body = AttachCourse,
485 responses(
486 (status = 201, description = "Course attached to the class", body = ClassCourseResponse),
487 (status = 400, description = "Unknown course", body = ErrorResponse),
488 (status = 401, description = "Not authenticated", body = ErrorResponse),
489 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
490 (status = 404, description = "Class not found", body = ErrorResponse),
491 (status = 409, description = "Already attached, or the course cannot hold the whole class", body = ErrorResponse),
492 ),
493)]
494async fn attach_course(
495 State(st): State<AppState>,
496 RequireTeacher(user): RequireTeacher,
497 Path(id): Path<String>,
498 Json(req): Json<AttachCourse>,
499) -> Result<(StatusCode, Json<ClassCourseResponse>), AppError> {
500 let class = class_or_404(&id, &st.db).await?;
501 let Some(course) = Course::read(&CourseId::from_key(&req.course_id), &st.db).await? else {
502 return Err(AppError::Validation(ValidationError::Invalid {
503 field: "course_id",
504 reason: "course does not exist",
505 }));
506 };
507 if !can_manage_course(&course, &user) {
508 return Err(AppError::Forbidden(
509 "only the course creator, an assigned teacher, or a manager/admin can attach this course to a class",
510 ));
511 }
512
513 let link = ClassCourse::attach(class.get_id(), course.get_id(), user.get_id(), &st.db).await?;
514 let people = PersonRef::map_of(&[&user]);
515 Ok((
516 StatusCode::CREATED,
517 Json(ClassCourseResponse::new(&link, &people)),
518 ))
519}
520
521/// List the courses a class is attached to, newest first, paged via
522/// `?limit=&offset=` (omit `limit` for all of them). Requires teacher+. Returns
523/// a `{items, total, limit, offset}` envelope.
524#[utoipa::path(
525 get,
526 path = "/{id}/courses",
527 tag = "classes",
528 security(("session_cookie" = [])),
529 params(("id" = String, Path, description = "Class id"), PageParams),
530 responses(
531 (status = 200, description = "A page of the class's courses (all of them when unpaged)", body = Page<ClassCourseResponse>),
532 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
533 (status = 401, description = "Not authenticated", body = ErrorResponse),
534 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
535 (status = 404, description = "Class not found", body = ErrorResponse),
536 ),
537)]
538async fn list_class_courses(
539 State(st): State<AppState>,
540 RequireTeacher(_user): RequireTeacher,
541 Path(id): Path<String>,
542 Query(page): Query<PageParams>,
543) -> Result<Json<Page<ClassCourseResponse>>, AppError> {
544 let (limit, offset) = page.resolve()?;
545 let class = class_or_404(&id, &st.db).await?;
546 let (rows, total) = ClassCourse::list_for_class(class.get_id(), limit, offset, &st.db).await?;
547 let people = person_map(rows.iter().map(|row| row.get_attached_by().clone()), &st.db).await?;
548 let items = rows
549 .iter()
550 .map(|row| ClassCourseResponse::new(row, &people))
551 .collect();
552 Ok(Json(Page::new(items, total, limit, offset)))
553}
554
555/// Detach a course from a class. Requires teacher+ and management rights on
556/// that course, like attaching. The enrollments the class pumped into it are
557/// swept — except rows another attached class still claims (re-tagged to it)
558/// and rows placed by hand (left standing). A course that was not attached is a
559/// 404.
560#[utoipa::path(
561 delete,
562 path = "/{id}/courses/{course}",
563 tag = "classes",
564 security(("session_cookie" = [])),
565 params(
566 ("id" = String, Path, description = "Class id"),
567 ("course" = String, Path, description = "Course id"),
568 ),
569 responses(
570 (status = 204, description = "Detached"),
571 (status = 401, description = "Not authenticated", body = ErrorResponse),
572 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
573 (status = 404, description = "Class or course not found, or that course was not attached", body = ErrorResponse),
574 ),
575)]
576async fn detach_course(
577 State(st): State<AppState>,
578 RequireTeacher(user): RequireTeacher,
579 Path((id, course)): Path<(String, String)>,
580) -> Result<StatusCode, AppError> {
581 let class = class_or_404(&id, &st.db).await?;
582 let course = Course::read(&CourseId::from_key(&course), &st.db)
583 .await?
584 .ok_or(AppError::NotFound)?;
585 if !can_manage_course(&course, &user) {
586 return Err(AppError::Forbidden(
587 "only the course creator, an assigned teacher, or a manager/admin can detach this course from a class",
588 ));
589 }
590 ClassCourse::detach(class.get_id(), course.get_id(), &st.db).await?;
591 Ok(StatusCode::NO_CONTENT)
592}
593
594#[cfg(test)]
595mod tests {
596 use super::*;
597
598 /// The nullable-grade rule both write paths share: absent and `""` are the
599 /// same *no grade*, so a PATCH clearing with `""` cannot store a blank
600 /// label a create could never make.
601 #[test]
602 fn an_empty_grade_is_no_grade() {
603 assert!(grade_or_none(None).unwrap().is_none());
604 assert!(grade_or_none(Some("")).unwrap().is_none());
605 assert_eq!(
606 grade_or_none(Some("9"))
607 .unwrap()
608 .map(|g| g.as_str().to_string()),
609 Some("9".to_string())
610 );
611 assert!(grade_or_none(Some(&"x".repeat(1000))).is_err());
612 }
613}