From a3d12c36f89b9500555e0e70bf016f2a2f9d498e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 12 Jul 2026 02:23:31 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=85=20test:=20cover=20profiles,=20courses?= =?UTF-8?q?,=20marks,=20statistics,=20and=20admin=20seed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Integration: course CRUD with creator/manager guards and validation, idempotent enrollment with roster and /courses/me, in-course exam creation, grading gated on enrollment and course management, exam statistics, weighted course averages and self-or-teacher mark reports, course-delete cascade, concurrent enrollments converging on one row, profile lifecycle (empty start, /users/me patch semantics, invalid fields, admin read/edit), and the admin seed (creates a working admin, idempotent, refuses to promote an existing non-admin). Persistence: profiles and course marks survive a database reopen. Common helpers: me_id, create_course, create_exam, enroll. --- tests/common/mod.rs | 55 ++ tests/integration.rs | 1266 +++++++++++++++++++++++++++++++++++++++--- tests/persistence.rs | 156 +++++- 3 files changed, 1394 insertions(+), 83 deletions(-) diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 5db46ef..3dc033d 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -119,3 +119,58 @@ pub async fn login(app: &Router, username: &str) -> String { pub fn id_of(v: &Value) -> String { v["id"].as_str().expect("id field").to_string() } + +/// The caller's own user id via `GET /auth/me`. +pub async fn me_id(app: &Router, cookie: &str) -> String { + let res = send(app, "GET", "/auth/me", Some(cookie), None).await; + assert_eq!(res.status, StatusCode::OK, "GET /auth/me"); + id_of(&res.body) +} + +/// Create a course as `cookie` (asserts 201); returns its id. +pub async fn create_course(app: &Router, cookie: &str, title: &str) -> String { + let res = send( + app, + "POST", + "/courses", + Some(cookie), + Some(json!({ "title": title })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "create course {title}"); + id_of(&res.body) +} + +/// Create an exam inside `course` as `cookie` (asserts 201); returns its id. +pub async fn create_exam( + app: &Router, + cookie: &str, + course: &str, + title: &str, + kind: &str, + weight: i64, +) -> String { + let res = send( + app, + "POST", + &format!("/courses/{course}/exams"), + Some(cookie), + Some(json!({ "title": title, "kind": kind, "weight": weight })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "create exam {title}"); + id_of(&res.body) +} + +/// Enroll `user_id` into `course` as `cookie` (asserts 200). +pub async fn enroll(app: &Router, cookie: &str, course: &str, user_id: &str) { + let res = send( + app, + "POST", + &format!("/courses/{course}/enrollments"), + Some(cookie), + Some(json!({ "user_id": user_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "enroll {user_id}"); +} diff --git a/tests/integration.rs b/tests/integration.rs index a2eeadb..5f17765 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -5,8 +5,11 @@ mod common; use axum::body::Body; use axum::http::{Request, StatusCode}; -use common::{app_and_db, id_of, login, login_as, mem_app, send}; +use common::{ + app_and_db, create_course, create_exam, enroll, id_of, login, login_as, me_id, mem_app, send, +}; use hezarfen_backend::domain::session::Session; +use hezarfen_backend::domain::user::{Password, User, Username}; use hezarfen_backend::state::AppState; use hezarfen_backend::{build_router, database}; use serde_json::json; @@ -94,7 +97,10 @@ async fn protected_routes_require_session() { ("GET", "/events"), ("POST", "/events"), ("GET", "/exams"), - ("POST", "/exams"), + ("GET", "/courses"), + ("POST", "/courses"), + ("GET", "/courses/me"), + ("GET", "/marks/me"), ] { let res = send(&app, method, uri, None, None).await; assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{method} {uri}"); @@ -705,24 +711,27 @@ async fn event_timestamps_echo_and_validate() { // --- exams + results ----------------------------------------------------- #[tokio::test] -async fn exams_are_shared_but_creator_guarded() { +async fn exams_are_shared_but_course_guarded() { let (app, db) = app_and_db().await; let ali = login_as(&app, &db, "ali", "teacher").await; let veli = login_as(&app, &db, "veli", "teacher").await; + let course_id = create_course(&app, &ali, "algebra").await; let ex = send( &app, "POST", - "/exams", + &format!("/courses/{course_id}/exams"), Some(&ali), - Some(json!({ "title": "ch3", "description": "algebra", "kind": "quiz" })), + Some(json!({ "title": "ch3", "description": "algebra", "kind": "quiz", "weight": 2 })), ) .await; assert_eq!(ex.status, StatusCode::CREATED); assert_eq!(ex.body["kind"], "quiz"); + assert_eq!(ex.body["course"], course_id); + assert_eq!(ex.body["weight"], 2); let exam_id = id_of(&ex.body); - // Any authenticated user can read the exam and the list. + // Any authenticated user can read the exam and the lists. assert_eq!( send(&app, "GET", &format!("/exams/{exam_id}"), Some(&veli), None) .await @@ -738,8 +747,23 @@ async fn exams_are_shared_but_creator_guarded() { .len(), 1 ); + assert_eq!( + send( + &app, + "GET", + &format!("/courses/{course_id}/exams"), + Some(&veli), + None + ) + .await + .body + .as_array() + .unwrap() + .len(), + 1 + ); - // Non-creator teacher cannot edit or delete. + // A teacher who doesn't manage the course cannot edit or delete its exams. assert_eq!( send( &app, @@ -765,7 +789,7 @@ async fn exams_are_shared_but_creator_guarded() { StatusCode::FORBIDDEN ); - // Creator edits (partial) — kind flips homework, title kept. + // Course creator edits (partial) — kind flips homework, title/weight kept. let res = send( &app, "PATCH", @@ -777,39 +801,83 @@ async fn exams_are_shared_but_creator_guarded() { assert_eq!(res.status, StatusCode::OK); assert_eq!(res.body["kind"], "homework"); assert_eq!(res.body["title"], "ch3"); + assert_eq!(res.body["weight"], 2); } #[tokio::test] async fn exam_input_validation() { let (app, db) = app_and_db().await; let ali = login_as(&app, &db, "ali", "teacher").await; + let course_id = create_course(&app, &ali, "algebra").await; + let exams_uri = format!("/courses/{course_id}/exams"); // Missing/blank title -> 400. assert_eq!( send( &app, "POST", - "/exams", + &exams_uri, Some(&ali), - Some(json!({"title":" ","kind":"quiz"})) + Some(json!({"title":" ","kind":"quiz","weight":1})) ) .await .status, StatusCode::BAD_REQUEST ); - // Unknown kind -> 400. + // Unknown kind -> 400 ("final" is valid now; "essay" is not). assert_eq!( send( &app, "POST", - "/exams", + &exams_uri, Some(&ali), - Some(json!({"title":"t","kind":"final"})) + Some(json!({"title":"t","kind":"essay","weight":1})) ) .await .status, StatusCode::BAD_REQUEST ); + assert_eq!( + send( + &app, + "POST", + &exams_uri, + Some(&ali), + Some(json!({"title":"t","kind":"final","weight":1})) + ) + .await + .status, + StatusCode::CREATED + ); + // Weight out of range or missing -> 400 / 422. + for weight in [json!(0), json!(101), json!(-1)] { + assert_eq!( + send( + &app, + "POST", + &exams_uri, + Some(&ali), + Some(json!({"title":"t","kind":"quiz","weight":weight})) + ) + .await + .status, + StatusCode::BAD_REQUEST, + "weight {weight}" + ); + } + assert_eq!( + send( + &app, + "POST", + &exams_uri, + Some(&ali), + Some(json!({"title":"t","kind":"quiz"})) + ) + .await + .status, + StatusCode::UNPROCESSABLE_ENTITY, + "missing weight is a body schema error" + ); // Missing exam -> 404. assert_eq!( send(&app, "GET", "/exams/nope", Some(&ali), None) @@ -825,19 +893,11 @@ async fn grading_upsert_and_own_result() { let teacher = login_as(&app, &db, "teacher", "teacher").await; let alice = login(&app, "alice").await; // student let bob = login(&app, "bob").await; // student - let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body); + let alice_id = me_id(&app, &alice).await; - let exam_id = id_of( - &send( - &app, - "POST", - "/exams", - Some(&teacher), - Some(json!({"title":"mt","kind":"quiz"})), - ) - .await - .body, - ); + let course_id = create_course(&app, &teacher, "algebra").await; + enroll(&app, &teacher, &course_id, &alice_id).await; + let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz", 1).await; // Before grading, the student's own result is 404. assert_eq!( @@ -964,28 +1024,21 @@ async fn grading_rbac_and_validation() { let teacher = login_as(&app, &db, "teacher", "teacher").await; let alice = login(&app, "alice").await; // student let bob = login(&app, "bob").await; // student - let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body); + let alice_id = me_id(&app, &alice).await; + let bob_id = me_id(&app, &bob).await; - let exam_id = id_of( - &send( - &app, - "POST", - "/exams", - Some(&teacher), - Some(json!({"title":"e","kind":"homework"})), - ) - .await - .body, - ); + let course_id = create_course(&app, &teacher, "algebra").await; + enroll(&app, &teacher, &course_id, &alice_id).await; + let exam_id = create_exam(&app, &teacher, &course_id, "e", "homework", 1).await; // Students cannot create exams, grade anyone, list all results, or delete a result. assert_eq!( send( &app, "POST", - "/exams", + &format!("/courses/{course_id}/exams"), Some(&alice), - Some(json!({"title":"x","kind":"quiz"})) + Some(json!({"title":"x","kind":"quiz","weight":1})) ) .await .status, @@ -1054,6 +1107,19 @@ async fn grading_rbac_and_validation() { .status, StatusCode::BAD_REQUEST ); + // Target exists but is not enrolled in the course -> 400. + assert_eq!( + send( + &app, + "POST", + &format!("/exams/{exam_id}/results"), + Some(&teacher), + Some(json!({"mark":50,"user_id":bob_id})) + ) + .await + .status, + StatusCode::BAD_REQUEST + ); // Grading on a missing exam -> 404. assert_eq!( send( @@ -1074,25 +1140,709 @@ async fn deleting_exam_cascades_results() { let (app, db) = app_and_db().await; let teacher = login_as(&app, &db, "teacher", "teacher").await; let alice = login(&app, "alice").await; - let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body); + let alice_id = me_id(&app, &alice).await; - let exam_id = id_of( - &send( + let course_id = create_course(&app, &teacher, "algebra").await; + enroll(&app, &teacher, &course_id, &alice_id).await; + let exam_id = create_exam(&app, &teacher, &course_id, "e", "quiz", 1).await; + send( + &app, + "POST", + &format!("/exams/{exam_id}/results"), + Some(&teacher), + Some(json!({"mark":60,"user_id":alice_id})), + ) + .await; + + assert_eq!( + send( &app, - "POST", - "/exams", + "DELETE", + &format!("/exams/{exam_id}"), Some(&teacher), - Some(json!({"title":"e","kind":"quiz"})), + None ) .await - .body, + .status, + StatusCode::NO_CONTENT + ); + // Exam gone; the student's result is gone with it. + assert_eq!( + send( + &app, + "GET", + &format!("/exams/{exam_id}"), + Some(&teacher), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); + assert_eq!( + send( + &app, + "GET", + &format!("/exams/{exam_id}/result"), + Some(&alice), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); +} + +// --- courses + enrollments + marks ---------------------------------------- + +#[tokio::test] +async fn courses_are_shared_but_creator_guarded() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + let veli = login_as(&app, &db, "veli", "teacher").await; + let boss = login_as(&app, &db, "boss", "manager").await; + + let res = send( + &app, + "POST", + "/courses", + Some(&ali), + Some(json!({ "title": "algebra", "description": "numbers" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + assert_eq!(res.body["title"], "algebra"); + let course_id = id_of(&res.body); + + // Any authenticated user can read the course and the list. + assert_eq!( + send( + &app, + "GET", + &format!("/courses/{course_id}"), + Some(&veli), + None + ) + .await + .status, + StatusCode::OK + ); + assert_eq!( + send(&app, "GET", "/courses", Some(&veli), None) + .await + .body + .as_array() + .unwrap() + .len(), + 1 + ); + + // Non-creator teacher cannot edit or delete. + assert_eq!( + send( + &app, + "PATCH", + &format!("/courses/{course_id}"), + Some(&veli), + Some(json!({"title":"hijack"})) + ) + .await + .status, + StatusCode::FORBIDDEN + ); + assert_eq!( + send( + &app, + "DELETE", + &format!("/courses/{course_id}"), + Some(&veli), + None + ) + .await + .status, + StatusCode::FORBIDDEN + ); + + // Creator edits (partial) — description flips, title kept. + let res = send( + &app, + "PATCH", + &format!("/courses/{course_id}"), + Some(&ali), + Some(json!({ "description": "letters" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["title"], "algebra"); + assert_eq!(res.body["description"], "letters"); + + // A manager can edit anyone's course. + assert_eq!( + send( + &app, + "PATCH", + &format!("/courses/{course_id}"), + Some(&boss), + Some(json!({"title":"algebra II"})) + ) + .await + .status, + StatusCode::OK + ); +} + +#[tokio::test] +async fn course_input_validation() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + + // Missing/blank title -> 400. + assert_eq!( + send( + &app, + "POST", + "/courses", + Some(&ali), + Some(json!({"title":" "})) + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + // Missing course -> 404. + assert_eq!( + send(&app, "GET", "/courses/nope", Some(&ali), None) + .await + .status, + StatusCode::NOT_FOUND ); +} + +#[tokio::test] +async fn enrollment_upsert_roster_and_my_courses() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let alice = login(&app, "alice").await; // student + let bob = login(&app, "bob").await; // student + let alice_id = me_id(&app, &alice).await; + let course_id = create_course(&app, &teacher, "algebra").await; + + // Enrolling twice is an upsert: same row id both times. + let first = send( + &app, + "POST", + &format!("/courses/{course_id}/enrollments"), + Some(&teacher), + Some(json!({ "user_id": alice_id })), + ) + .await; + assert_eq!(first.status, StatusCode::OK); + let second = send( + &app, + "POST", + &format!("/courses/{course_id}/enrollments"), + Some(&teacher), + Some(json!({ "user_id": alice_id })), + ) + .await; + assert_eq!(id_of(&first.body), id_of(&second.body), "upsert same row"); + + // Roster lists alice once; students can't read the roster. + let roster = send( + &app, + "GET", + &format!("/courses/{course_id}/enrollments"), + Some(&teacher), + None, + ) + .await; + assert_eq!(roster.body.as_array().unwrap().len(), 1); + assert_eq!( + send( + &app, + "GET", + &format!("/courses/{course_id}/enrollments"), + Some(&alice), + None + ) + .await + .status, + StatusCode::FORBIDDEN + ); + + // /courses/me shows the course for alice, stays empty for bob. + assert_eq!( + send(&app, "GET", "/courses/me", Some(&alice), None) + .await + .body + .as_array() + .unwrap() + .len(), + 1 + ); + assert_eq!( + send(&app, "GET", "/courses/me", Some(&bob), None) + .await + .body + .as_array() + .unwrap() + .len(), + 0 + ); + + // Unenroll -> 204; repeating -> 404. + assert_eq!( + send( + &app, + "DELETE", + &format!("/courses/{course_id}/enrollments/{alice_id}"), + Some(&teacher), + None + ) + .await + .status, + StatusCode::NO_CONTENT + ); + assert_eq!( + send( + &app, + "DELETE", + &format!("/courses/{course_id}/enrollments/{alice_id}"), + Some(&teacher), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); +} + +#[tokio::test] +async fn enrollment_requires_course_management() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let veli = login_as(&app, &db, "veli", "teacher").await; + let boss = login_as(&app, &db, "boss", "manager").await; + let alice = login(&app, "alice").await; // student + let alice_id = me_id(&app, &alice).await; + let course_id = create_course(&app, &teacher, "algebra").await; + + // A teacher who doesn't manage the course cannot enroll anyone. + assert_eq!( + send( + &app, + "POST", + &format!("/courses/{course_id}/enrollments"), + Some(&veli), + Some(json!({ "user_id": alice_id })) + ) + .await + .status, + StatusCode::FORBIDDEN + ); + // A manager can. + assert_eq!( + send( + &app, + "POST", + &format!("/courses/{course_id}/enrollments"), + Some(&boss), + Some(json!({ "user_id": alice_id })) + ) + .await + .status, + StatusCode::OK + ); + // Unknown target -> 400; missing course -> 404. + assert_eq!( + send( + &app, + "POST", + &format!("/courses/{course_id}/enrollments"), + Some(&teacher), + Some(json!({ "user_id": "ghost" })) + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + assert_eq!( + send( + &app, + "POST", + "/courses/nope/enrollments", + Some(&teacher), + Some(json!({ "user_id": alice_id })) + ) + .await + .status, + StatusCode::NOT_FOUND + ); +} + +#[tokio::test] +async fn exam_creation_lives_under_courses() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let veli = login_as(&app, &db, "veli", "teacher").await; + let alice = login(&app, "alice").await; // student + + // The old flat creation route is gone: /exams only serves GET now. + assert_eq!( + send( + &app, + "POST", + "/exams", + Some(&teacher), + Some(json!({"title":"t","kind":"quiz","weight":1})) + ) + .await + .status, + StatusCode::METHOD_NOT_ALLOWED + ); + + let course_id = create_course(&app, &teacher, "algebra").await; + // Creation inside the course echoes course + weight. + let res = send( + &app, + "POST", + &format!("/courses/{course_id}/exams"), + Some(&teacher), + Some(json!({"title":"mt","kind":"midterm","weight":3})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + assert_eq!(res.body["course"], course_id); + assert_eq!(res.body["weight"], 3); + + // A teacher who doesn't manage the course cannot add exams to it. + assert_eq!( + send( + &app, + "POST", + &format!("/courses/{course_id}/exams"), + Some(&veli), + Some(json!({"title":"x","kind":"quiz","weight":1})) + ) + .await + .status, + StatusCode::FORBIDDEN + ); + + // Any authenticated user (a student) can list the course's exams. + assert_eq!( + send( + &app, + "GET", + &format!("/courses/{course_id}/exams"), + Some(&alice), + None + ) + .await + .body + .as_array() + .unwrap() + .len(), + 1 + ); +} + +#[tokio::test] +async fn grading_requires_enrollment() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let alice = login(&app, "alice").await; // student + let alice_id = me_id(&app, &alice).await; + + let course_id = create_course(&app, &teacher, "algebra").await; + let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz", 1).await; + let grade_uri = format!("/exams/{exam_id}/results"); + let grade_body = json!({ "mark": 70, "user_id": alice_id }); + + // Not enrolled -> 400. + assert_eq!( + send( + &app, + "POST", + &grade_uri, + Some(&teacher), + Some(grade_body.clone()) + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + + // Enrolled -> 200. + enroll(&app, &teacher, &course_id, &alice_id).await; + assert_eq!( + send( + &app, + "POST", + &grade_uri, + Some(&teacher), + Some(grade_body.clone()) + ) + .await + .status, + StatusCode::OK + ); + + // Unenrolling blocks further grading but keeps the recorded result: + // the row still lists for the teacher and the student still reads it. + assert_eq!( + send( + &app, + "DELETE", + &format!("/courses/{course_id}/enrollments/{alice_id}"), + Some(&teacher), + None + ) + .await + .status, + StatusCode::NO_CONTENT + ); + assert_eq!( + send(&app, "POST", &grade_uri, Some(&teacher), Some(grade_body)) + .await + .status, + StatusCode::BAD_REQUEST + ); + assert_eq!( + send(&app, "GET", &grade_uri, Some(&teacher), None) + .await + .body + .as_array() + .unwrap() + .len(), + 1 + ); + assert_eq!( + send( + &app, + "GET", + &format!("/exams/{exam_id}/result"), + Some(&alice), + None + ) + .await + .body["mark"], + 70 + ); + + // ...but the mark vanishes from the report until re-enrollment restores it. + let report = send(&app, "GET", "/marks/me", Some(&alice), None).await; + assert_eq!(report.body["courses"].as_array().unwrap().len(), 0); + enroll(&app, &teacher, &course_id, &alice_id).await; + let report = send(&app, "GET", "/marks/me", Some(&alice), None).await; + assert_eq!(report.body["courses"][0]["average"], 70.0); +} + +#[tokio::test] +async fn exam_writes_follow_course_management() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let veli = login_as(&app, &db, "veli", "teacher").await; + let boss = login_as(&app, &db, "boss", "manager").await; + let course_id = create_course(&app, &teacher, "algebra").await; + + // A manager creates an exam in the teacher's course... + let exam_id = create_exam(&app, &boss, &course_id, "mt", "midterm", 2).await; + + // ...and the course creator (not the exam's creator) can edit and delete it. + assert_eq!( + send( + &app, + "PATCH", + &format!("/exams/{exam_id}"), + Some(&teacher), + Some(json!({"weight":5})) + ) + .await + .body["weight"], + 5 + ); + // An unrelated teacher still cannot. + assert_eq!( + send( + &app, + "PATCH", + &format!("/exams/{exam_id}"), + Some(&veli), + Some(json!({"weight":1})) + ) + .await + .status, + StatusCode::FORBIDDEN + ); + assert_eq!( + send( + &app, + "DELETE", + &format!("/exams/{exam_id}"), + Some(&teacher), + None + ) + .await + .status, + StatusCode::NO_CONTENT + ); +} + +#[tokio::test] +async fn exam_statistics_summarize_results() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let alice = login(&app, "alice").await; + let bob = login(&app, "bob").await; + let alice_id = me_id(&app, &alice).await; + let bob_id = me_id(&app, &bob).await; + + let course_id = create_course(&app, &teacher, "algebra").await; + enroll(&app, &teacher, &course_id, &alice_id).await; + enroll(&app, &teacher, &course_id, &bob_id).await; + let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz", 1).await; + let stats_uri = format!("/exams/{exam_id}/statistics"); + + // Nothing graded yet: zero count, null aggregates. + let res = send(&app, "GET", &stats_uri, Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["graded"], 0); + assert_eq!(res.body["average"], serde_json::Value::Null); + assert_eq!(res.body["min"], serde_json::Value::Null); + assert_eq!(res.body["max"], serde_json::Value::Null); + + for (id, mark) in [(&alice_id, 60), (&bob_id, 80)] { + send( + &app, + "POST", + &format!("/exams/{exam_id}/results"), + Some(&teacher), + Some(json!({ "mark": mark, "user_id": id })), + ) + .await; + } + + let res = send(&app, "GET", &stats_uri, Some(&teacher), None).await; + assert_eq!(res.body["graded"], 2); + assert_eq!(res.body["average"], 70.0); + assert_eq!(res.body["min"], 60); + assert_eq!(res.body["max"], 80); + + // Students don't see statistics; missing exam is a 404. + assert_eq!( + send(&app, "GET", &stats_uri, Some(&alice), None) + .await + .status, + StatusCode::FORBIDDEN + ); +} + +#[tokio::test] +async fn weighted_averages_follow_exam_weights() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let alice = login(&app, "alice").await; + let alice_id = me_id(&app, &alice).await; + + // Course A: quiz (w1, mark 50) + midterm (w3, mark 90) -> (50 + 270) / 4 = 80. + let algebra = create_course(&app, &teacher, "algebra").await; + enroll(&app, &teacher, &algebra, &alice_id).await; + let quiz = create_exam(&app, &teacher, &algebra, "quiz", "quiz", 1).await; + let midterm = create_exam(&app, &teacher, &algebra, "midterm", "midterm", 3).await; + // A third exam stays ungraded and must not drag the average. + create_exam(&app, &teacher, &algebra, "final", "final", 4).await; + for (exam, mark) in [(&quiz, 50), (&midterm, 90)] { + let res = send( + &app, + "POST", + &format!("/exams/{exam}/results"), + Some(&teacher), + Some(json!({ "mark": mark, "user_id": alice_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + } + + // Course B: enrolled, nothing graded -> null average. + let physics = create_course(&app, &teacher, "physics").await; + enroll(&app, &teacher, &physics, &alice_id).await; + create_exam(&app, &teacher, &physics, "hw", "homework", 1).await; + + let report = send(&app, "GET", "/marks/me", Some(&alice), None).await; + assert_eq!(report.status, StatusCode::OK); + let courses = report.body["courses"].as_array().unwrap(); + assert_eq!(courses.len(), 2); + let algebra_block = courses + .iter() + .find(|c| c["course"]["title"] == "algebra") + .unwrap(); + let physics_block = courses + .iter() + .find(|c| c["course"]["title"] == "physics") + .unwrap(); + + assert_eq!(algebra_block["average"], 80.0); + assert_eq!(algebra_block["results"].as_array().unwrap().len(), 2); + assert_eq!(physics_block["average"], serde_json::Value::Null); + assert_eq!(physics_block["results"].as_array().unwrap().len(), 0); + // Overall skips the null course instead of zeroing it. + assert_eq!(report.body["overall_average"], 80.0); + assert_eq!(report.body["user"], alice_id); +} + +#[tokio::test] +async fn marks_reports_are_self_or_teacher_scoped() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let alice = login(&app, "alice").await; + let bob = login(&app, "bob").await; + let alice_id = me_id(&app, &alice).await; + + // Own report works for a student. + assert_eq!( + send(&app, "GET", "/marks/me", Some(&alice), None) + .await + .status, + StatusCode::OK + ); + // Another user's report needs teacher+. + assert_eq!( + send(&app, "GET", &format!("/marks/{alice_id}"), Some(&bob), None) + .await + .status, + StatusCode::FORBIDDEN + ); + assert_eq!( + send( + &app, + "GET", + &format!("/marks/{alice_id}"), + Some(&teacher), + None + ) + .await + .status, + StatusCode::OK + ); +} + +#[tokio::test] +async fn deleting_course_cascades_enrollments_exams_and_results() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let alice = login(&app, "alice").await; + let alice_id = me_id(&app, &alice).await; + + let course_id = create_course(&app, &teacher, "algebra").await; + enroll(&app, &teacher, &course_id, &alice_id).await; + let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz", 1).await; send( &app, "POST", &format!("/exams/{exam_id}/results"), Some(&teacher), - Some(json!({"mark":60,"user_id":alice_id})), + Some(json!({ "mark": 70, "user_id": alice_id })), ) .await; @@ -1100,7 +1850,7 @@ async fn deleting_exam_cascades_results() { send( &app, "DELETE", - &format!("/exams/{exam_id}"), + &format!("/courses/{course_id}"), Some(&teacher), None ) @@ -1108,7 +1858,20 @@ async fn deleting_exam_cascades_results() { .status, StatusCode::NO_CONTENT ); - // Exam gone; the student's result is gone with it. + + // Course, exam, result, and enrollment are all gone. + assert_eq!( + send( + &app, + "GET", + &format!("/courses/{course_id}"), + Some(&teacher), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); assert_eq!( send( &app, @@ -1133,6 +1896,69 @@ async fn deleting_exam_cascades_results() { .status, StatusCode::NOT_FOUND ); + assert_eq!( + send(&app, "GET", "/courses/me", Some(&alice), None) + .await + .body + .as_array() + .unwrap() + .len(), + 0 + ); + assert_eq!( + send(&app, "GET", "/marks/me", Some(&alice), None) + .await + .body["courses"] + .as_array() + .unwrap() + .len(), + 0 + ); +} + +/// Same guarantee as attendance/grading: concurrent enrolls of the same pair +/// converge on one row instead of racing the unique index into a 500. +#[tokio::test] +async fn concurrent_enrollments_never_collide() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let alice = login(&app, "alice").await; + let alice_id = me_id(&app, &alice).await; + let course_id = create_course(&app, &teacher, "algebra").await; + + let mut handles = Vec::new(); + for _ in 0..24 { + let app = app.clone(); + let teacher = teacher.clone(); + let uri = format!("/courses/{course_id}/enrollments"); + let body = json!({ "user_id": alice_id }); + handles.push(tokio::spawn(async move { + send(&app, "POST", &uri, Some(&teacher), Some(body)) + .await + .status + })); + } + for h in handles { + assert_eq!( + h.await.unwrap(), + StatusCode::OK, + "concurrent enroll must not fail" + ); + } + + let roster = send( + &app, + "GET", + &format!("/courses/{course_id}/enrollments"), + Some(&teacher), + None, + ) + .await; + assert_eq!( + roster.body.as_array().unwrap().len(), + 1, + "upsert keeps a single row" + ); } // --- roles / RBAC -------------------------------------------------------- @@ -1362,6 +2188,208 @@ async fn admin_manages_roles_with_guards() { ); } +// --- users: personal info (profile) --------------------------------------- + +#[tokio::test] +async fn profile_starts_empty_and_updates_via_users_me() { + let app = mem_app().await; + let bob = login(&app, "bob").await; + + // A fresh account carries no personal info. + let me = send(&app, "GET", "/auth/me", Some(&bob), None).await; + assert_eq!(me.status, StatusCode::OK); + for field in ["name", "surname", "email", "phone", "birth_date"] { + assert!(me.body[field].is_null(), "{field} should start null"); + } + + // Fill everything in via the self-service endpoint. + let res = send( + &app, + "PATCH", + "/users/me", + Some(&bob), + Some(json!({ + "name": "Bob", + "surname": "Gümüş", + "email": "bob@example.com", + "phone": "+90 555 123 45 67", + "birth_date": "1990-1-2", + })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["name"], "Bob"); + assert_eq!(res.body["surname"], "Gümüş"); // unicode names allowed + assert_eq!(res.body["email"], "bob@example.com"); + assert_eq!(res.body["phone"], "+90 555 123 45 67"); + assert_eq!(res.body["birth_date"], "1990-01-02"); // canonicalized + assert!(res.body.get("password_hash").is_none()); + + // Partial patch: only phone changes, everything else survives. + let res = send( + &app, + "PATCH", + "/users/me", + Some(&bob), + Some(json!({ "phone": "05551112233" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["phone"], "05551112233"); + assert_eq!(res.body["name"], "Bob"); + assert_eq!(res.body["email"], "bob@example.com"); + + // Empty string clears a field; the others stay. + let res = send( + &app, + "PATCH", + "/users/me", + Some(&bob), + Some(json!({ "phone": "" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert!(res.body["phone"].is_null()); + assert_eq!(res.body["name"], "Bob"); + + // The merged state is what /auth/me reports afterwards. + let me = send(&app, "GET", "/auth/me", Some(&bob), None).await; + assert_eq!(me.body["name"], "Bob"); + assert_eq!(me.body["surname"], "Gümüş"); + assert_eq!(me.body["birth_date"], "1990-01-02"); + assert!(me.body["phone"].is_null()); + + // No session -> 401. + assert_eq!( + send(&app, "PATCH", "/users/me", None, Some(json!({"name":"x"}))) + .await + .status, + StatusCode::UNAUTHORIZED + ); +} + +#[tokio::test] +async fn profile_rejects_invalid_fields() { + let app = mem_app().await; + let bob = login(&app, "bob").await; + + let bad = [ + json!({ "email": "not-an-email" }), + json!({ "email": "bob@nodot" }), + json!({ "phone": "123" }), + json!({ "phone": "letters" }), + json!({ "birth_date": "02/01/1990" }), + json!({ "birth_date": "1990-02-30" }), + json!({ "birth_date": "9999-01-01" }), + json!({ "name": " " }), + json!({ "name": "x".repeat(101) }), + ]; + for body in bad { + let res = send(&app, "PATCH", "/users/me", Some(&bob), Some(body.clone())).await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "should reject {body}"); + } + + // A rejected patch must not have half-applied: profile is still empty. + let me = send(&app, "GET", "/auth/me", Some(&bob), None).await; + for field in ["name", "surname", "email", "phone", "birth_date"] { + assert!(me.body[field].is_null(), "{field} should still be null"); + } +} + +#[tokio::test] +async fn admin_reads_and_edits_any_profile_with_guards() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "admin", "admin").await; + let alice = login(&app, "alice").await; + let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body); + let admin_id = id_of(&send(&app, "GET", "/auth/me", Some(&admin), None).await.body); + + // Students can neither look up nor edit someone else's record. + assert_eq!( + send( + &app, + "GET", + &format!("/users/{admin_id}"), + Some(&alice), + None + ) + .await + .status, + StatusCode::FORBIDDEN + ); + assert_eq!( + send( + &app, + "PATCH", + &format!("/users/{admin_id}/profile"), + Some(&alice), + Some(json!({"name":"Mallory"})) + ) + .await + .status, + StatusCode::FORBIDDEN + ); + + // Admin maintains alice's record on her behalf. + let res = send( + &app, + "PATCH", + &format!("/users/{alice_id}/profile"), + Some(&admin), + Some(json!({ "name": "Alice", "email": "alice@school.edu" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["name"], "Alice"); + + // Admin reads a single user; alice sees the change on /auth/me. + let one = send( + &app, + "GET", + &format!("/users/{alice_id}"), + Some(&admin), + None, + ) + .await; + assert_eq!(one.status, StatusCode::OK); + assert_eq!(one.body["username"], "alice"); + assert_eq!(one.body["email"], "alice@school.edu"); + let me = send(&app, "GET", "/auth/me", Some(&alice), None).await; + assert_eq!(me.body["name"], "Alice"); + + // The admin listing now carries the info columns too. + let list = send(&app, "GET", "/users", Some(&admin), None).await; + let listed = list + .body + .as_array() + .unwrap() + .iter() + .find(|u| u["username"] == "alice") + .expect("alice listed") + .clone(); + assert_eq!(listed["email"], "alice@school.edu"); + + // Unknown ids -> 404 on both admin endpoints. + assert_eq!( + send(&app, "GET", "/users/does-not-exist", Some(&admin), None) + .await + .status, + StatusCode::NOT_FOUND + ); + assert_eq!( + send( + &app, + "PATCH", + "/users/does-not-exist/profile", + Some(&admin), + Some(json!({"name":"Nobody"})) + ) + .await + .status, + StatusCode::NOT_FOUND + ); +} + // --- regression: race safety, session hygiene, CORS ---------------------- /// #1 — Many concurrent marks for the *same* (event, user). A find-then-insert @@ -1431,22 +2459,10 @@ async fn concurrent_exam_grades_never_collide() { let (app, db) = app_and_db().await; let teacher = login_as(&app, &db, "teacher", "teacher").await; let student = login(&app, "student").await; - let student_id = id_of( - &send(&app, "GET", "/auth/me", Some(&student), None) - .await - .body, - ); - let exam_id = id_of( - &send( - &app, - "POST", - "/exams", - Some(&teacher), - Some(json!({ "title": "e", "kind": "quiz" })), - ) - .await - .body, - ); + let student_id = me_id(&app, &student).await; + let course_id = create_course(&app, &teacher, "algebra").await; + enroll(&app, &teacher, &course_id, &student_id).await; + let exam_id = create_exam(&app, &teacher, &course_id, "e", "quiz", 1).await; let mut handles = Vec::new(); for mark in 0..24i64 { @@ -1589,26 +2605,16 @@ async fn graders_cannot_grade_themselves() { let (app, db) = app_and_db().await; let teacher = login_as(&app, &db, "teacher", "teacher").await; let boss = login_as(&app, &db, "boss", "manager").await; - let teacher_id = id_of( - &send(&app, "GET", "/auth/me", Some(&teacher), None) - .await - .body, - ); - let boss_id = id_of(&send(&app, "GET", "/auth/me", Some(&boss), None).await.body); + let teacher_id = me_id(&app, &teacher).await; + let boss_id = me_id(&app, &boss).await; - let exam_id = id_of( - &send( - &app, - "POST", - "/exams", - Some(&teacher), - Some(json!({"title":"t","kind":"quiz"})), - ) - .await - .body, - ); + let course_id = create_course(&app, &teacher, "algebra").await; + enroll(&app, &teacher, &course_id, &teacher_id).await; + enroll(&app, &teacher, &course_id, &boss_id).await; + let exam_id = create_exam(&app, &teacher, &course_id, "t", "quiz", 1).await; // Self-grading is forbidden at every privilege level, not just for teachers. + // (The teacher owns the course; the manager clears the gate by role.) for (cookie, own_id) in [(&teacher, &teacher_id), (&boss, &boss_id)] { let res = send( &app, @@ -1725,6 +2731,36 @@ async fn child_lists_of_missing_parents_are_404() { .status, StatusCode::NOT_FOUND ); + assert_eq!( + send( + &app, + "GET", + "/courses/nope/enrollments", + Some(&teacher), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); + assert_eq!( + send(&app, "GET", "/courses/nope/exams", Some(&teacher), None) + .await + .status, + StatusCode::NOT_FOUND + ); + assert_eq!( + send(&app, "GET", "/exams/nope/statistics", Some(&teacher), None) + .await + .status, + StatusCode::NOT_FOUND + ); + assert_eq!( + send(&app, "GET", "/marks/ghost", Some(&teacher), None) + .await + .status, + StatusCode::NOT_FOUND + ); } /// Regression: the session cookie never carried the `Secure` attribute, so a @@ -1893,3 +2929,69 @@ async fn cors_is_credential_safe_not_wildcard() { "true", ); } + +// --- admin seed (ADMIN_USERNAME / ADMIN_PASSWORD bootstrap) ---------------- + +/// The seed creates a ready-to-use admin: login works with the configured +/// credentials and the account can reach admin-only endpoints immediately. +#[tokio::test] +async fn admin_seed_creates_working_admin() { + let (app, db) = app_and_db().await; + let username = Username::try_new("root").unwrap(); + let password = Password::try_new("secret1").unwrap(); + User::ensure_admin(username, password, &db).await.unwrap(); + + let creds = json!({ "username": "root", "password": "secret1" }); + let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["role"], "admin"); + + let cookie = res.cookie.expect("session cookie"); + let res = send(&app, "GET", "/users", Some(&cookie), None).await; + assert_eq!(res.status, StatusCode::OK, "admin-only listing must open"); +} + +/// Re-running the seed (every boot does) must not duplicate the account, +/// demote it, or overwrite its password. +#[tokio::test] +async fn admin_seed_is_idempotent() { + let (app, db) = app_and_db().await; + for _ in 0..2 { + let username = Username::try_new("root").unwrap(); + let password = Password::try_new("secret1").unwrap(); + User::ensure_admin(username, password, &db).await.unwrap(); + } + + let cookie = { + let creds = json!({ "username": "root", "password": "secret1" }); + let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; + assert_eq!(res.status, StatusCode::OK); + res.cookie.expect("session cookie") + }; + let res = send(&app, "GET", "/users", Some(&cookie), None).await; + let listed = res.body.as_array().expect("user list"); + assert_eq!(listed.len(), 1, "seed must not duplicate the account"); + assert_eq!(listed[0]["role"], "admin"); +} + +/// A username already registered by someone else is never promoted (or its +/// password replaced) by the seed — that would be privilege escalation. +#[tokio::test] +async fn admin_seed_refuses_existing_non_admin() { + let (app, db) = app_and_db().await; + let cookie = login(&app, "squatter").await; // registers with password `secret1` + + let username = Username::try_new("squatter").unwrap(); + let password = Password::try_new("attacker-pw").unwrap(); + User::ensure_admin(username, password, &db).await.unwrap(); + + // Still a student: the admin-only listing stays closed... + let res = send(&app, "GET", "/users", Some(&cookie), None).await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "must not be promoted"); + + // ...and the original password still logs in (nothing was overwritten). + let creds = json!({ "username": "squatter", "password": "secret1" }); + let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["role"], "student"); +} diff --git a/tests/persistence.rs b/tests/persistence.rs index dc73ed2..1592ac5 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -7,7 +7,7 @@ mod common; use std::time::Duration; use axum::http::StatusCode; -use common::send; +use common::{create_course, create_exam, enroll, me_id, send, set_role}; use hezarfen_backend::config::Config; use hezarfen_backend::database::Database; use hezarfen_backend::rate_limit::RateLimitConfig; @@ -38,6 +38,8 @@ fn config_at(dir: &TempDir) -> Config { db_name: "hezarfen".into(), cookie_secure: false, rate_limit: RateLimitConfig::unlimited(), + admin_username: None, + admin_password: None, } } @@ -145,3 +147,155 @@ async fn data_survives_reopen() { assert_eq!(rows[0]["title"], "persisted"); } } + +/// Personal info written through `PATCH /users/me` is still on the account +/// after a close + reopen. +#[tokio::test] +async fn profile_survives_reopen() { + let dir = tempfile::tempdir().unwrap(); + let cfg = config_at(&dir); + let creds = json!({ "username": "ali", "password": "secret1" }); + + // First boot: register and fill in the profile. + { + let db = database::init(&cfg).await.expect("first open"); + let app = build_router(state(db)); + assert_eq!( + send(&app, "POST", "/auth/register", None, Some(creds.clone())) + .await + .status, + StatusCode::CREATED + ); + let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) + .await + .cookie + .unwrap(); + let res = send( + &app, + "PATCH", + "/users/me", + Some(&cookie), + Some(json!({ + "name": "Ali", + "surname": "Gümüş", + "email": "ali@example.com", + "phone": "+90 555 123 45 67", + "birth_date": "1990-01-02", + })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + } + + // Second boot: the info comes back from disk. + { + let db = reopen(&cfg).await; + let app = build_router(state(db)); + let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) + .await + .cookie + .unwrap(); + let me = send(&app, "GET", "/auth/me", Some(&cookie), None).await; + assert_eq!(me.status, StatusCode::OK); + assert_eq!(me.body["name"], "Ali"); + assert_eq!(me.body["surname"], "Gümüş"); + assert_eq!(me.body["email"], "ali@example.com"); + assert_eq!(me.body["phone"], "+90 555 123 45 67"); + assert_eq!(me.body["birth_date"], "1990-01-02"); + } +} + +/// A course with an enrollment, a weighted exam, and a graded mark survives a +/// close + reopen — the weighted report is rebuilt from disk. +#[tokio::test] +async fn course_marks_survive_reopen() { + let dir = tempfile::tempdir().unwrap(); + let cfg = config_at(&dir); + let teacher_creds = json!({ "username": "hoca", "password": "secret1" }); + let student_creds = json!({ "username": "ali", "password": "secret1" }); + + // First boot: teacher sets up a course, enrolls the student, grades 80. + { + let db = database::init(&cfg).await.expect("first open"); + let app = build_router(state(db.clone())); + for creds in [&teacher_creds, &student_creds] { + assert_eq!( + send(&app, "POST", "/auth/register", None, Some((*creds).clone())) + .await + .status, + StatusCode::CREATED + ); + } + set_role(&db, "hoca", "teacher").await; + let teacher = send( + &app, + "POST", + "/auth/login", + None, + Some(teacher_creds.clone()), + ) + .await + .cookie + .unwrap(); + let student = send( + &app, + "POST", + "/auth/login", + None, + Some(student_creds.clone()), + ) + .await + .cookie + .unwrap(); + let student_id = me_id(&app, &student).await; + + let course_id = create_course(&app, &teacher, "algebra").await; + enroll(&app, &teacher, &course_id, &student_id).await; + let exam_id = create_exam(&app, &teacher, &course_id, "midterm", "midterm", 2).await; + assert_eq!( + send( + &app, + "POST", + &format!("/exams/{exam_id}/results"), + Some(&teacher), + Some(json!({ "mark": 80, "user_id": student_id })) + ) + .await + .status, + StatusCode::OK + ); + } + + // Second boot: the report, roster, and exam weight are all rebuilt from disk. + { + let db = reopen(&cfg).await; + let app = build_router(state(db)); + let student = send(&app, "POST", "/auth/login", None, Some(student_creds)) + .await + .cookie + .unwrap(); + let report = send(&app, "GET", "/marks/me", Some(&student), None).await; + assert_eq!(report.status, StatusCode::OK); + let course = &report.body["courses"][0]; + assert_eq!(course["course"]["title"], "algebra"); + assert_eq!(course["average"], 80.0); + assert_eq!(course["results"][0]["weight"], 2); + assert_eq!(course["results"][0]["mark"], 80); + assert_eq!(report.body["overall_average"], 80.0); + + let teacher = send(&app, "POST", "/auth/login", None, Some(teacher_creds)) + .await + .cookie + .unwrap(); + let course_id = course["course"]["id"].as_str().unwrap(); + let roster = send( + &app, + "GET", + &format!("/courses/{course_id}/enrollments"), + Some(&teacher), + None, + ) + .await; + assert_eq!(roster.body.as_array().unwrap().len(), 1, "roster intact"); + } +}