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

mod.rs1006 lines, 33.3 KiBHistoryRawDownload
1//! Shared helpers for the router-level test binaries (`integration`,
2//! `persistence`, and friends). Drives an `axum::Router` in-process via
3//! `tower::ServiceExt::oneshot`, over a **per-test pair of Postgres
4//! databases** — control plus demo school, cloned from the shared school
5//! template by `database::init_test_tenants`, dropped with the test.
6#![allow(dead_code)]
7
8use std::path::PathBuf;
9use std::sync::OnceLock;
10
11use axum::Router;
12use axum::body::Body;
13use axum::http::{HeaderMap, Request, StatusCode};
14use hezarfen_backend::ai::AiBridge;
15use hezarfen_backend::database::Database;
16use hezarfen_backend::module::ModuleSet;
17use hezarfen_backend::rate_limit::RateLimitConfig;
18use hezarfen_backend::state::AppState;
19use hezarfen_backend::telemetry::Metrics;
20use hezarfen_backend::tenant::{BETA_SCHOOL_ID, DEMO_SCHOOL_ID, SchoolId, Tenants};
21use hezarfen_backend::{build_router, database};
22use serde_json::{Value, json};
23use tempfile::TempDir;
24use tower::ServiceExt;
25
26pub struct Res {
27 pub status: StatusCode,
28 pub body: Value,
29 /// The `session=<token>` pair, if the response set one.
30 pub cookie: Option<String>,
31}
32
33/// A well-formed id for a row that exists nowhere — the canonical ghost
34/// parent every FK-refusal test aims at. Replaces the ULID literal
35/// `01J8XZ0K3Q8G7X2M4N5P6R7S8T` the suites used before the UUID v7 port.
36pub const GHOST_ID: &str = "019732e3-7b00-7000-8000-00000000dead";
37
38/// A second well-formed, never-minted id, for "look this up, expect a miss".
39/// Replaces `01ZZZZZZZZZZZZZZZZZZZZZZZZ`.
40pub const ABSENT_ID: &str = "019732e3-7b00-7000-8000-00000000eeee";
41
42/// One shared blob directory for every app in this test process. Blob names
43/// are per-row ids, so apps never collide; the static keeps the `TempDir`
44/// (and so the directory) alive for the whole run.
45static FILES_DIR: OnceLock<TempDir> = OnceLock::new();
46
47pub fn files_dir() -> PathBuf {
48 FILES_DIR
49 .get_or_init(|| tempfile::tempdir().expect("files tempdir"))
50 .path()
51 .to_path_buf()
52}
53
54/// A router plus a handle to its demo school's database. Tests that need to
55/// grant roles use the handle to seed them directly — the app's only role
56/// bootstrap path is out-of-band, exactly like production's manual SQL.
57pub async fn app_and_db() -> (Router, Database) {
58 app_with_ai(None).await
59}
60
61/// [`app_and_db`] plus the registry behind it, for the suites whose subject is
62/// tenancy itself (a second school, a suspension, the builder surface).
63pub async fn app_and_tenants() -> (Router, Database, Tenants) {
64 let (app, db, tenants) = app_parts(None, Metrics::noop()).await;
65 (app, db, tenants)
66}
67
68/// The hyphenated uuid a test label names. `demo` and `beta` are pinned to
69/// the ids [`init_test_tenants`] / [`deployment_with`] register; a value that
70/// is already a uuid is returned unchanged.
71pub fn school_wire(label: &str) -> &str {
72 match label {
73 "demo" => DEMO_SCHOOL_ID,
74 "beta" => BETA_SCHOOL_ID,
75 "ata-koleji" => "019732e3-7b00-7000-8000-00000000a7a1",
76 "2024school" => "019732e3-7b00-7000-8000-000000002024",
77 "gamma" => "019732e3-7b00-7000-8000-00000000a11a",
78 "p4a" => "019732e3-7b00-7000-8000-00000000a4a1",
79 other => other,
80 }
81}
82
83pub fn school_id(label: &str) -> SchoolId {
84 SchoolId::try_parse(school_wire(label)).unwrap_or_else(|_| panic!("{label} is not a school id"))
85}
86
87/// Where the demo school's blobs land: one directory per school under
88/// `FILES_PATH`, created on the school's first upload.
89pub fn blob_dir() -> PathBuf {
90 let dir = files_dir().join(DEMO_SCHOOL_ID);
91 std::fs::create_dir_all(&dir).expect("blob dir");
92 dir
93}
94
95/// The raw session token out of a `session=<school>.<token>` cookie value —
96/// what a test needs when it writes a session row by hand.
97pub fn cookie_token(cookie: &str) -> &str {
98 cookie
99 .trim_start_matches("session=")
100 .split_once('.')
101 .expect("a session cookie carries its school")
102 .1
103}
104
105/// A test deployment: the registry, plus the demo school's handle. For the
106/// suites that build their own `AppState` instead of using [`app_and_db`].
107/// (The name outlived the in-memory engine; the shape is what the suites
108/// bind to.)
109pub async fn mem_deployment() -> (Tenants, Database) {
110 let tenants = database::init_test_tenants().await;
111 let db = demo_db(&tenants).await;
112 (tenants, db)
113}
114
115/// The demo school's handle out of a registry.
116pub async fn demo_db(tenants: &Tenants) -> Database {
117 tenants
118 .get(&SchoolId::try_parse(DEMO_SCHOOL_ID).expect("the demo school"))
119 .await
120 .expect("the demo school resolves")
121}
122
123/// The same router, with the AI bridge wired into its state. `build_router`
124/// arms the bridge's api-read handle whenever `ai` is `Some`, so this is the
125/// bootstrap that makes a QUIC service's reads dispatch into a real router.
126pub async fn app_with_ai(ai: Option<AiBridge>) -> (Router, Database) {
127 let (app, db, _) = app_parts(ai, Metrics::noop()).await;
128 (app, db)
129}
130
131/// [`app_with_ai`] plus the registry behind it, for the suites whose subject is
132/// an AI service reading *across* schools.
133pub async fn app_with_ai_tenants(ai: Option<AiBridge>) -> (Router, Database, Tenants) {
134 app_parts(ai, Metrics::noop()).await
135}
136
137/// The one bootstrap: a fresh test deployment (control database + the demo
138/// school), a router over it, and the demo school's handle — which is what
139/// every suite means by "the database", since that is where users and rows
140/// live.
141async fn app_parts(ai: Option<AiBridge>, metrics: Metrics) -> (Router, Database, Tenants) {
142 let tenants = database::init_test_tenants().await;
143 let db = demo_db(&tenants).await;
144 let app = build_router(AppState {
145 db: tenants.control().clone(),
146 tenants: tenants.clone(),
147 files_path: files_dir(),
148 cookie_secure: false,
149 // Off, so suites hammering the API never trip a limit; the dedicated
150 // `rate_limit` test binary opts into tight configs on purpose.
151 rate_limit: RateLimitConfig::unlimited(),
152 chatbot_limit: Default::default(),
153 rag_limit: Default::default(),
154 exam_presence: Default::default(),
155 board_hub: Default::default(),
156 ai,
157 metrics,
158 });
159 (app, db, tenants)
160}
161
162/// The same router with the caller's instruments, so a test can read back what
163/// the HTTP edge recorded without touching the process-global meter provider.
164pub async fn app_with_metrics(metrics: Metrics) -> (Router, Database) {
165 let (app, db, _) = app_parts(None, metrics).await;
166 (app, db)
167}
168
169/// Attribute keys that would carry personal data out of the process. KVKK
170/// analysis fixed this list: telemetry names the school and the route, never
171/// the person, their address, or what they sent. Shared so the HTTP edge
172/// (`telemetry.rs`) and the AI bridge (`ai_bridge.rs`) are held to one list.
173///
174/// `server.address` is deliberately absent: that is our own bind address, not
175/// a caller's.
176pub const FORBIDDEN_TELEMETRY_KEYS: &[&str] = &[
177 "url.path",
178 "url.full",
179 "url.query",
180 "client.address",
181 "network.peer.address",
182 "user_agent.original",
183 "user.id",
184 "user.name",
185 "username",
186 "email",
187 "enduser.id",
188 "cookie",
189 "http.request.body",
190 "http.response.body",
191];
192
193/// [`FORBIDDEN_TELEMETRY_KEYS`] plus the two header prefixes — any captured
194/// request or response header is personal data by default.
195pub fn is_forbidden_key(key: &str) -> bool {
196 FORBIDDEN_TELEMETRY_KEYS.contains(&key)
197 || key.starts_with("http.request.header.")
198 || key.starts_with("http.response.header.")
199}
200
201/// A router backed by a fresh per-test Postgres deployment.
202pub async fn mem_app() -> Router {
203 app_and_db().await.0
204}
205
206/// Force `username`'s role, mirroring the manual `UPDATE app_user SET
207/// role=...` bootstrap. Roles are read fresh per request, so this takes
208/// effect at once.
209pub async fn set_role(db: &Database, username: &str, role: &str) {
210 sqlx::query("UPDATE app_user SET role = $2 WHERE username = $1")
211 .bind(username)
212 .bind(role)
213 .execute(db)
214 .await
215 .expect("set_role query");
216}
217
218/// Register (password `secret1`), promote to `role`, then log in. Returns the
219/// session `Cookie` value.
220pub async fn login_as(app: &Router, db: &Database, username: &str, role: &str) -> String {
221 login_as_school(app, db, DEMO_SCHOOL_ID, username, role).await
222}
223
224/// [`login_as`] in a named school. `db` must be that school's own handle — the
225/// role is written where the user was created, which is what makes two schools
226/// able to hold the same username independently.
227pub async fn login_as_school(
228 app: &Router,
229 db: &Database,
230 school: &str,
231 username: &str,
232 role: &str,
233) -> String {
234 let reg = send(
235 app,
236 "POST",
237 "/auth/register",
238 None,
239 Some(json!({ "school": school_wire(school), "username": username, "password": "secret1" })),
240 )
241 .await;
242 assert_eq!(reg.status, StatusCode::CREATED, "register {username}");
243 set_role(db, username, role).await;
244 let res = send(
245 app,
246 "POST",
247 "/auth/login",
248 None,
249 Some(json!({ "username": username, "password": "secret1" })),
250 )
251 .await;
252 assert_eq!(res.status, StatusCode::OK, "login {username}");
253 // The account is a person: if `username` already belongs to another
254 // school, login answers a choice list and never names a school — bind
255 // the school this helper was called for.
256 if res.body["schools"].is_array() {
257 let selected = send(
258 app,
259 "POST",
260 "/auth/school",
261 res.cookie.as_deref(),
262 Some(json!({ "school": school_wire(school) })),
263 )
264 .await;
265 assert_eq!(
266 selected.status,
267 StatusCode::OK,
268 "select {school} for {username}: {}",
269 selected.body
270 );
271 selected.cookie.expect("school cookie after selection")
272 } else {
273 res.cookie.expect("session cookie set on login")
274 }
275}
276
277/// Send one request through `app`. `cookie` is a raw `Cookie` header value.
278pub async fn send(
279 app: &Router,
280 method: &str,
281 uri: &str,
282 cookie: Option<&str>,
283 body: Option<Value>,
284) -> Res {
285 let mut builder = Request::builder().method(method).uri(uri);
286 if let Some(c) = cookie {
287 builder = builder.header("cookie", c);
288 }
289 let request = match body {
290 Some(b) => builder
291 .header("content-type", "application/json")
292 .body(Body::from(b.to_string()))
293 .unwrap(),
294 None => builder.body(Body::empty()).unwrap(),
295 };
296
297 let response = app.clone().oneshot(request).await.unwrap();
298 let status = response.status();
299 let cookie = response
300 .headers()
301 .get("set-cookie")
302 .and_then(|v| v.to_str().ok())
303 .and_then(|s| s.split(';').next())
304 .map(|s| s.to_string());
305 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
306 .await
307 .unwrap();
308 let body = if bytes.is_empty() {
309 Value::Null
310 } else {
311 serde_json::from_slice(&bytes).unwrap_or(Value::Null)
312 };
313 Res {
314 status,
315 body,
316 cookie,
317 }
318}
319
320/// Send one request with a raw body and content type; returns the raw
321/// response (status, headers, body bytes) — for driving the file endpoints.
322pub async fn send_raw(
323 app: &Router,
324 method: &str,
325 uri: &str,
326 cookie: Option<&str>,
327 content_type: Option<&str>,
328 body: Vec<u8>,
329) -> (StatusCode, HeaderMap, Vec<u8>) {
330 let mut builder = Request::builder().method(method).uri(uri);
331 if let Some(c) = cookie {
332 builder = builder.header("cookie", c);
333 }
334 if let Some(ct) = content_type {
335 builder = builder.header("content-type", ct);
336 }
337 let response = app
338 .clone()
339 .oneshot(builder.body(Body::from(body)).unwrap())
340 .await
341 .unwrap();
342 let status = response.status();
343 let headers = response.headers().clone();
344 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
345 .await
346 .unwrap()
347 .to_vec();
348 (status, headers, bytes)
349}
350
351const MULTIPART_BOUNDARY: &str = "hezarfen-test-boundary";
352
353/// A `multipart/form-data` body with a single `file` part.
354pub fn multipart_file(filename: &str, content_type: &str, bytes: &[u8]) -> Vec<u8> {
355 let mut body = Vec::new();
356 body.extend_from_slice(format!("--{MULTIPART_BOUNDARY}\r\n").as_bytes());
357 body.extend_from_slice(
358 format!("Content-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\n")
359 .as_bytes(),
360 );
361 body.extend_from_slice(format!("Content-Type: {content_type}\r\n\r\n").as_bytes());
362 body.extend_from_slice(bytes);
363 body.extend_from_slice(format!("\r\n--{MULTIPART_BOUNDARY}--\r\n").as_bytes());
364 body
365}
366
367/// Upload `bytes` as a multipart file to `uri` (no assertion). Parses the
368/// JSON body like `send`.
369pub async fn upload_file_at(
370 app: &Router,
371 cookie: &str,
372 uri: &str,
373 filename: &str,
374 content_type: &str,
375 bytes: &[u8],
376) -> Res {
377 let (status, _, body) = send_raw(
378 app,
379 "POST",
380 uri,
381 Some(cookie),
382 Some(&format!(
383 "multipart/form-data; boundary={MULTIPART_BOUNDARY}"
384 )),
385 multipart_file(filename, content_type, bytes),
386 )
387 .await;
388 let body = if body.is_empty() {
389 Value::Null
390 } else {
391 serde_json::from_slice(&body).unwrap_or(Value::Null)
392 };
393 Res {
394 status,
395 body,
396 cookie: None,
397 }
398}
399
400/// Upload `bytes` as a file onto a personal `note` (no assertion).
401pub async fn upload_file(
402 app: &Router,
403 cookie: &str,
404 note: &str,
405 filename: &str,
406 content_type: &str,
407 bytes: &[u8],
408) -> Res {
409 upload_file_at(
410 app,
411 cookie,
412 &format!("/notes/{note}/files"),
413 filename,
414 content_type,
415 bytes,
416 )
417 .await
418}
419
420/// Upload `bytes` as a file onto a course `note` (no assertion).
421pub async fn upload_course_note_file(
422 app: &Router,
423 cookie: &str,
424 note: &str,
425 filename: &str,
426 content_type: &str,
427 bytes: &[u8],
428) -> Res {
429 upload_file_at(
430 app,
431 cookie,
432 &format!("/course-notes/{note}/files"),
433 filename,
434 content_type,
435 bytes,
436 )
437 .await
438}
439
440/// Register (password `secret1`) then log in; returns the session `Cookie` value.
441pub async fn login(app: &Router, username: &str) -> String {
442 let reg = send(
443 app,
444 "POST",
445 "/auth/register",
446 None,
447 Some(json!({ "school": DEMO_SCHOOL_ID, "username": username, "password": "secret1" })),
448 )
449 .await;
450 assert_eq!(reg.status, StatusCode::CREATED, "register {username}");
451 let res = send(
452 app,
453 "POST",
454 "/auth/login",
455 None,
456 Some(json!({ "username": username, "password": "secret1" })),
457 )
458 .await;
459 assert_eq!(res.status, StatusCode::OK, "login {username}");
460 res.cookie.expect("session cookie set on login")
461}
462
463pub fn id_of(v: &Value) -> String {
464 v["id"].as_str().expect("id field").to_string()
465}
466
467/// The `items` array of a paginated list envelope (`{items, total, limit,
468/// offset}`) — the shape every `GET` list endpoint returns. Panics if `v`
469/// isn't such an envelope, so a test that points it at the wrong body fails
470/// loudly.
471pub fn items(v: &Value) -> &Vec<Value> {
472 v["items"]
473 .as_array()
474 .unwrap_or_else(|| panic!("expected a paginated list envelope with items[], got {v}"))
475}
476
477/// The `total` count from a paginated list envelope.
478pub fn total(v: &Value) -> i64 {
479 v["total"].as_i64().expect("paginated envelope total")
480}
481
482/// The caller's own user id via `GET /auth/me`.
483pub async fn me_id(app: &Router, cookie: &str) -> String {
484 let res = send(app, "GET", "/auth/me", Some(cookie), None).await;
485 assert_eq!(res.status, StatusCode::OK, "GET /auth/me");
486 id_of(&res.body)
487}
488
489/// Create a **catalog** course as `cookie` (asserts 201); returns its id.
490///
491/// The catalog is the title and the subjects hung off it. What one şube teaches
492/// is an *instance* (`POST /classes/{class}/instances`), and enrollment, exams,
493/// sessions and homework key on that instance, never on this row —
494/// [`taught`] is the fixture that mints the whole stack.
495pub async fn create_course(app: &Router, cookie: &str, title: &str) -> String {
496 let res = send(
497 app,
498 "POST",
499 "/courses",
500 Some(cookie),
501 Some(json!({ "title": title })),
502 )
503 .await;
504 assert_eq!(res.status, StatusCode::CREATED, "create course {title}");
505 id_of(&res.body)
506}
507
508/// Create a subject inside `course` as `cookie` (asserts 201); returns its id.
509/// Every exam question must be tagged with one of its course's subjects.
510pub async fn create_subject(app: &Router, cookie: &str, course: &str, name: &str) -> String {
511 let res = send(
512 app,
513 "POST",
514 &format!("/courses/{course}/subjects"),
515 Some(cookie),
516 Some(json!({ "name": name })),
517 )
518 .await;
519 assert_eq!(res.status, StatusCode::CREATED, "create subject {name}");
520 let subject = id_of(&res.body);
521
522 // The subject-tag gates (homework, exam questions) read the section's
523 // resolved syllabus, so a topic a suite creates is only usable once the
524 // offering selects it. When the course has been attached somewhere, the
525 // offering exists — select the fresh topic there (idempotent; a
526 // non-manager cookie cannot curate the offering and skips this, which
527 // the tag gates then surface as their own 400).
528 let res = send(
529 app,
530 "GET",
531 &format!("/offerings?course={course}"),
532 Some(cookie),
533 None,
534 )
535 .await;
536 if res.status == StatusCode::OK
537 && let Some(offering) = res.body["items"][0]["id"].as_str()
538 {
539 let res = send(
540 app,
541 "POST",
542 &format!("/offerings/{offering}/subjects"),
543 Some(cookie),
544 Some(json!({ "subject": subject })),
545 )
546 .await;
547 // A non-manager cookie cannot curate the offering; the tag gates
548 // then answer their own 400 and the caller selects another way
549 // (see `create_homework`'s instance-door retry).
550 assert!(
551 matches!(res.status, StatusCode::CREATED | StatusCode::OK | StatusCode::FORBIDDEN),
552 "select subject {name} on offering {offering}: {}",
553 res.body
554 );
555 }
556 subject
557}
558
559// ---- the academic fixture ---------------------------------------------------
560//
561// The K12 remodel made the class×course **instance** the academic anchor: a
562// şube (class) teaches a catalog course, and that pair is one `class_course` row
563// every exam, session, homework, roster and karne keys on. A suite that needs a
564// roster to exist therefore mints three rows, not one — and the şube is school
565// structure, so whoever creates it holds manager+ (the course itself stays the
566// teacher's: the catalog is teacher-owned).
567
568/// The bounds every fixture calendar uses: one year-wide span, fixed so two
569/// tests cannot race a clock.
570pub const FIXTURE_YEAR_STARTS_AT: i64 = 1_750_000_000_000;
571pub const FIXTURE_YEAR_ENDS_AT: i64 = 1_800_000_000_000;
572
573/// Create an academic year as `staff` (asserts 201); returns its id. `staff`
574/// must hold manager+.
575pub async fn create_year(app: &Router, staff: &str, name: &str) -> String {
576 let res = send(
577 app,
578 "POST",
579 "/academic-years",
580 Some(staff),
581 Some(json!({
582 "name": name,
583 "starts_at": FIXTURE_YEAR_STARTS_AT,
584 "ends_at": FIXTURE_YEAR_ENDS_AT,
585 })),
586 )
587 .await;
588 assert_eq!(
589 res.status,
590 StatusCode::CREATED,
591 "create academic year {name}: {}",
592 res.body
593 );
594 id_of(&res.body)
595}
596
597/// The school's newest academic year, minted when it has none yet — a fixture
598/// needs a calendar without the test having to name one.
599pub async fn ensure_year(app: &Router, staff: &str) -> String {
600 let res = send(app, "GET", "/academic-years?limit=1", Some(staff), None).await;
601 assert_eq!(res.status, StatusCode::OK, "list academic years");
602 match items(&res.body).first() {
603 Some(year) => id_of(year),
604 None => create_year(app, staff, "2026-2027").await,
605 }
606}
607
608/// Create a dönem inside `year` as `staff` (asserts 201); returns its id.
609/// Dönem names repeat freely, so a fixture may mint one per call.
610pub async fn create_term(app: &Router, staff: &str, year: &str, name: &str) -> String {
611 let res = send(
612 app,
613 "POST",
614 "/terms",
615 Some(staff),
616 Some(json!({
617 "name": name,
618 "year": year,
619 "starts_at": FIXTURE_YEAR_STARTS_AT,
620 "ends_at": FIXTURE_YEAR_ENDS_AT,
621 })),
622 )
623 .await;
624 assert_eq!(
625 res.status,
626 StatusCode::CREATED,
627 "create term {name}: {}",
628 res.body
629 );
630 id_of(&res.body)
631}
632
633/// Create a class (şube) as `staff` (asserts 201); returns its id. `body`
634/// carries everything but the name: `year`, `teacher_id`, `grade_level`
635/// (defaulting to rung 9 when the caller does not name one).
636pub async fn create_class(app: &Router, staff: &str, name: &str, body: Value) -> String {
637 let mut body = body;
638 body["name"] = json!(name);
639 if body.get("grade_level").is_none() {
640 body["grade_level"] = json!(9);
641 }
642 let res = send(app, "POST", "/classes", Some(staff), Some(body)).await;
643 assert_eq!(
644 res.status,
645 StatusCode::CREATED,
646 "create class {name}: {}",
647 res.body
648 );
649 res.body["class"]["id"]
650 .as_str()
651 .unwrap_or_else(|| panic!("class envelope with a class id: {}", res.body))
652 .to_string()
653}
654
655/// Put `user_id` in `class` as `staff` (asserts 201). The pump enrolls them into
656/// every instance the şube already carries, so a pumped roster row names the
657/// şube as its `source` — [`enroll`] is the hand-placed row that does not.
658pub async fn add_member(app: &Router, staff: &str, class: &str, user_id: &str) {
659 let res = send(
660 app,
661 "POST",
662 &format!("/classes/{class}/members"),
663 Some(staff),
664 Some(json!({ "user_id": user_id })),
665 )
666 .await;
667 assert_eq!(
668 res.status,
669 StatusCode::CREATED,
670 "add member {user_id}: {}",
671 res.body
672 );
673}
674
675/// Attach `course` to `class` as `staff` (asserts 201); returns the **instance
676/// id** — the anchor every exam, session, homework and enrollment keys on.
677/// `staff` needs catalog rights on the course (its creator, or manager+).
678pub async fn attach_instance(app: &Router, staff: &str, class: &str, course: &str) -> String {
679 let res = send(
680 app,
681 "POST",
682 &format!("/classes/{class}/instances"),
683 Some(staff),
684 Some(json!({ "course_id": course })),
685 )
686 .await;
687 assert_eq!(
688 res.status,
689 StatusCode::CREATED,
690 "attach course {course} to class {class}: {}",
691 res.body
692 );
693 id_of(&res.body)
694}
695
696/// A catalog course as one şube teaches it: the stack a suite needs before
697/// anyone can be enrolled, examined or marked.
698pub struct Taught {
699 /// The academic year the şube sits in — what a karne counts into.
700 pub year: String,
701 /// The dönem exams written against this fixture are filed under.
702 pub term: String,
703 /// The catalog course: `GET|PATCH /courses/{id}`, `/courses/{id}/subjects`.
704 pub course: String,
705 /// The şube itself: `GET|POST|DELETE /classes/{id}/members`, `/instances`.
706 pub class: String,
707 /// The `class_course` anchor: `/instances/{id}/…` — enrollments, exams,
708 /// sessions, homework, roll call, marks.
709 pub instance: String,
710}
711
712/// [`taught_under`] with the caller as the şube's homeroom teacher too — for a
713/// suite whose actor is one manager/admin account.
714pub async fn taught(app: &Router, staff: &str, title: &str) -> Taught {
715 taught_under(app, staff, staff, title).await
716}
717
718/// Mint a whole academic stack for `title`: a year (reused when the school has
719/// one), a dönem, the catalog course — created by `homeroom`, so a
720/// creator-gated catalog route stays theirs — a şube naming `homeroom` as its
721/// sınıf öğretmeni, and the instance the pair forms.
722///
723/// `staff` must hold manager+ (a şube is school structure) and `homeroom`
724/// teacher+; passing the same cookie twice is the one-account fixture. Naming
725/// the homeroom teacher is what lets a plain `teacher` cookie act on the
726/// instance, because `ensure_instance_teacher` passes for the şube's own
727/// öğretmen as well as for manager+.
728pub async fn taught_under(app: &Router, staff: &str, homeroom: &str, title: &str) -> Taught {
729 let year = ensure_year(app, staff).await;
730 let term = create_term(app, staff, &year, "1. Dönem").await;
731 let course = create_course(app, homeroom, title).await;
732 let homeroom_id = me_id(app, homeroom).await;
733 let class = create_class(
734 app,
735 staff,
736 &format!("{title} şubesi"),
737 json!({ "year": year, "teacher_id": homeroom_id }),
738 )
739 .await;
740 let instance = attach_instance(app, staff, &class, &course).await;
741 Taught {
742 year,
743 term,
744 course,
745 class,
746 instance,
747 }
748}
749
750/// Create an exam inside `instance` as `cookie` (asserts 201); returns its id.
751/// `term` is the dönem the marks count into (`GET /terms`); the exam's weight in
752/// the instance's average comes from its kind (settings).
753pub async fn create_exam(
754 app: &Router,
755 cookie: &str,
756 instance: &str,
757 term: &str,
758 title: &str,
759 kind: &str,
760) -> String {
761 let res = send(
762 app,
763 "POST",
764 &format!("/instances/{instance}/exams"),
765 Some(cookie),
766 Some(json!({ "title": title, "kind": kind, "term": term })),
767 )
768 .await;
769 assert_eq!(
770 res.status,
771 StatusCode::CREATED,
772 "create exam {title}: {}",
773 res.body
774 );
775 id_of(&res.body)
776}
777
778/// Create an exam inside `instance` from a full JSON body (no assertion) — for
779/// exercising the scheduling fields and their validation. The body must carry
780/// its own `term`.
781pub async fn create_exam_with(app: &Router, cookie: &str, instance: &str, body: Value) -> Res {
782 send(
783 app,
784 "POST",
785 &format!("/instances/{instance}/exams"),
786 Some(cookie),
787 Some(body),
788 )
789 .await
790}
791
792/// One homework-create send with the subject-gate retry: a `subject_id` the
793/// section's resolved syllabus does not carry is refused, and the writer —
794/// who holds a right over the instance (the very gate the homework write
795/// passed) — takes the topic onto the section's own set through the instance
796/// door and retries once. Every other refusal comes back untouched.
797async fn send_homework_create(
798 app: &Router,
799 cookie: &str,
800 instance: &str,
801 body: Value,
802) -> Res {
803 let res = send(
804 app,
805 "POST",
806 &format!("/instances/{instance}/homework"),
807 Some(cookie),
808 Some(body.clone()),
809 )
810 .await;
811 if res.status == StatusCode::BAD_REQUEST
812 && res.body["error"]
813 .as_str()
814 .is_some_and(|e| e.contains("subject is not in this section's subject set"))
815 {
816 let subject = body["subject_id"].as_str().expect("subject_id").to_string();
817 let res = send(
818 app,
819 "POST",
820 &format!("/instances/{instance}/subjects"),
821 Some(cookie),
822 Some(json!({ "subject": subject })),
823 )
824 .await;
825 assert!(
826 matches!(res.status, StatusCode::CREATED | StatusCode::OK),
827 "select subject {subject} on instance {instance}: {}",
828 res.body
829 );
830 return send(
831 app,
832 "POST",
833 &format!("/instances/{instance}/homework"),
834 Some(cookie),
835 Some(body),
836 )
837 .await;
838 }
839 res
840}
841
842/// Take `subject` onto the section's own syllabus through the instance door —
843/// the D10 gate, the same right the question and homework writers hold.
844/// Idempotent: a subject already in the set re-answers 200.
845pub async fn select_instance_subject(app: &Router, cookie: &str, instance: &str, subject: &str) {
846 let res = send(
847 app,
848 "POST",
849 &format!("/instances/{instance}/subjects"),
850 Some(cookie),
851 Some(json!({ "subject": subject })),
852 )
853 .await;
854 assert!(
855 matches!(res.status, StatusCode::CREATED | StatusCode::OK),
856 "select subject {subject} on instance {instance}: {}",
857 res.body
858 );
859}
860
861/// Create a homework inside `instance` as `cookie` (asserts 201); returns its
862/// id. Tagged with `subject` (required — every homework carries one of its
863/// course's subjects) and due at `due_at` (unix-millis; must not lie past the
864/// 60s grace). Whole-instance audience; use [`create_homework_with`] for an
865/// `assigned` subset.
866pub async fn create_homework(
867 app: &Router,
868 cookie: &str,
869 instance: &str,
870 subject: &str,
871 title: &str,
872 due_at: i64,
873) -> String {
874 let res = send_homework_create(
875 app,
876 cookie,
877 instance,
878 json!({ "title": title, "subject_id": subject, "due_at": due_at }),
879 )
880 .await;
881 assert_eq!(
882 res.status,
883 StatusCode::CREATED,
884 "create homework {title}: {}",
885 res.body
886 );
887 id_of(&res.body)
888}
889
890/// Create a homework inside `instance` from a full JSON body (no assertion) —
891/// for exercising the `assigned` subset and the validation rejects. The
892/// subject-gate retry applies here too; every other refusal comes back as
893/// the server answered it.
894pub async fn create_homework_with(app: &Router, cookie: &str, instance: &str, body: Value) -> Res {
895 send_homework_create(app, cookie, instance, body).await
896}
897
898/// Create a lesson session inside `instance` as `cookie` (asserts 201); returns
899/// its id. The session's teacher defaults to the caller.
900pub async fn create_session(app: &Router, cookie: &str, instance: &str, starts_at: i64) -> String {
901 let res = send(
902 app,
903 "POST",
904 &format!("/instances/{instance}/sessions"),
905 Some(cookie),
906 Some(json!({ "starts_at": starts_at })),
907 )
908 .await;
909 assert_eq!(
910 res.status,
911 StatusCode::CREATED,
912 "create session: {}",
913 res.body
914 );
915 id_of(&res.body)
916}
917
918/// Drop `user_id` from `instance`'s roster as `cookie` (asserts 204). Deleting a
919/// catalog course is refused while instances still teach it, so cascade tests
920/// detach instances and empty rosters first.
921pub async fn unenroll(app: &Router, cookie: &str, instance: &str, user_id: &str) {
922 let res = send(
923 app,
924 "DELETE",
925 &format!("/instances/{instance}/enrollments/{user_id}"),
926 Some(cookie),
927 None,
928 )
929 .await;
930 assert_eq!(
931 res.status,
932 StatusCode::NO_CONTENT,
933 "unenroll {user_id}: {}",
934 res.body
935 );
936}
937
938/// Enroll `user_id` into `instance` as `cookie` (asserts 200) — the roster row a
939/// human placed, carrying no şube, so no şube sweep may take it back.
940pub async fn enroll(app: &Router, cookie: &str, instance: &str, user_id: &str) {
941 let res = send(
942 app,
943 "POST",
944 &format!("/instances/{instance}/enrollments"),
945 Some(cookie),
946 Some(json!({ "user_id": user_id })),
947 )
948 .await;
949 assert_eq!(res.status, StatusCode::OK, "enroll {user_id}: {}", res.body);
950}
951
952// ---- multi-school deployments ---------------------------------------------
953//
954// The probes whose subject is tenancy itself — cross-school isolation,
955// suspension, school deletion — build a deployment with more schools than
956// the demo one. Under database-per-school tenancy there is no separate
957// "remote" mode to exercise: production *is* this shape, and a second
958// deployment is a second `database::init_test_tenants()` away. (The
959// `surreal start` remote lane this section used to hold died with the
960// embedded engine.)
961
962/// A deployment with its own blob directory: what the tenancy probes hold.
963pub struct TestDeployment {
964 pub app: Router,
965 pub tenants: Tenants,
966 /// `FILES_PATH` — this deployment's own directory, never the shared
967 /// [`files_dir`], so one deployment's uploads cannot be counted by
968 /// another's probes.
969 pub files: PathBuf,
970 _files: TempDir,
971}
972
973/// [`app_and_tenants`] with named schools created alongside the demo — where
974/// the former `remote_deployment` probes re-point. The named schools go
975/// through the real [`Tenants::create`], since the create path is part of
976/// what the tenancy probes examine.
977pub async fn deployment_with(schools: &[(&str, &str)]) -> TestDeployment {
978 let files = tempfile::tempdir().expect("files tempdir");
979 let tenants = database::init_test_tenants().await;
980 for (label, name) in schools {
981 let id = school_id(label);
982 tenants
983 .create(id, name, ModuleSet::all())
984 .await
985 .unwrap_or_else(|err| panic!("create school {label}: {err}"));
986 }
987 let app = build_router(AppState {
988 db: tenants.control().clone(),
989 tenants: tenants.clone(),
990 files_path: files.path().to_path_buf(),
991 cookie_secure: false,
992 rate_limit: RateLimitConfig::unlimited(),
993 chatbot_limit: Default::default(),
994 rag_limit: Default::default(),
995 exam_presence: Default::default(),
996 board_hub: Default::default(),
997 ai: None,
998 metrics: Metrics::noop(),
999 });
1000 TestDeployment {
1001 app,
1002 tenants,
1003 files: files.path().to_path_buf(),
1004 _files: files,
1005 }
1006}