normogen/backend/tests/medication_tests.rs
goose bd1b7c2925 fix(backend): P1 — handler unwrap cleanup + rewrite integration tests
P1 items #6 (JWT expiry) and #7 (refresh/logout routes) were already delivered
in the P0 pass. This commit covers the two remaining P1 items:

#9 — Replace dangerous handler-level .unwrap() calls (13 sites):
* handlers/users.rs: 5x ObjectId::parse_str(&claims.sub).unwrap() in
  get_profile/update_profile/delete_account/get_settings/update_settings now
  return 401 on a malformed subject instead of panicking (matches the guard
  already used in change_password).
* handlers/auth.rs: the login user.id.ok_or_else(..).unwrap() was a latent
  panic bug — the crafted 500 response was discarded. Now returns the clean
  500 via match.
* handlers/health_stats.rs: 6x state.health_stats_repo.as_ref().unwrap() now
  return 503 SERVICE_UNAVAILABLE if the feature is unconfigured, mirroring the
  interactions.rs pattern.
* Left untouched: 14 test/boot-time unwraps and 7 infallible ones (header
  literal parsing, infallible TryFrom). The 3 borderline model-layer
  inserted_id unwraps are flagged for later.

#8 — Rewrite the broken integration tests against a real test DB:
* Split the crate into bin+lib: new src/lib.rs + src/app.rs (build_app), with
  main.rs now a thin entrypoint. Tests build the exact production router
  in-process instead of hitting a live server on a hardcoded port.
* tests/common/mod.rs: helpers that connect to Mongo, build a fresh AppState
  against a unique per-process DB (normogen_test_<uuid>), and tear it down.
  A 1s connectivity probe makes tests skip gracefully when Mongo is absent, so
  'cargo test' stays green without Mongo — CI runs them for real.
* Rewrote tests/auth_tests.rs and tests/medication_tests.rs with the ACTUAL
  API contracts (POST /register {email,username,password}; response has token
  + refresh_token, not access_token; register returns 201). Covers register,
  login (right/wrong password), auth enforcement, refresh rotation + reuse
  detection, logout, and password-change invalidating old tokens.
* Added a 'test' CI job with a mongo:7 service container running
  cargo test --all-targets.
* Synced scripts/test-ci-locally.sh: fixed the stale -D warnings (CI is
  non-strict) and the reverted 'Docker Buildx' claims; added unit + integration
  test steps with a Mongo skip note.

Verified: cargo fmt --check clean, build + clippy --all-targets clean.
Full 'cargo test': 18 unit + 9 auth + 4 medication = 31 passed, 0 failed
(integration tests skip cleanly when MongoDB is unreachable).
2026-06-27 14:26:39 -03:00

122 lines
3.3 KiB
Rust

//! Medication-endpoint integration tests.
//!
//! In-process against an isolated MongoDB test DB (see `common`). When Mongo is
//! unreachable these skip gracefully. Verifies auth enforcement and an
//! authenticated create -> list flow with the actual API contract.
mod common;
use serde_json::json;
/// Skip when Mongo is unavailable (counts as a pass); CI provides Mongo.
macro_rules! require_app {
($app:expr) => {
match $app {
Some(x) => x,
None => {
eprintln!("[integration] skipped (MongoDB unavailable)");
return;
}
}
};
}
#[tokio::test]
async fn create_medication_requires_auth() {
let (app, db_name) = require_app!(common::app_for_test().await);
let (status, _) = common::send_json(
&app,
"POST",
"/api/medications",
Some(
json!({ "name": "Test Med", "dosage": "10mg", "frequency": "daily", "route": "oral" }),
),
None,
)
.await;
assert_eq!(status, 401);
common::drop_test_db(&db_name).await;
}
#[tokio::test]
async fn list_medications_requires_auth() {
let (app, db_name) = require_app!(common::app_for_test().await);
let (status, _) = common::send_json(&app, "GET", "/api/medications", None, None).await;
assert_eq!(status, 401);
common::drop_test_db(&db_name).await;
}
#[tokio::test]
async fn get_medication_requires_auth() {
let (app, db_name) = require_app!(common::app_for_test().await);
let (status, _) = common::send_json(
&app,
"GET",
"/api/medications/507f1f77bcf86cd799439011",
None,
None,
)
.await;
assert_eq!(status, 401);
common::drop_test_db(&db_name).await;
}
#[tokio::test]
async fn authenticated_user_can_create_and_list_medication() {
let (app, db_name) = require_app!(common::app_for_test().await);
let email = unique_email();
// Register and grab the access token.
let (status, body) = common::send_json(
&app,
"POST",
"/api/auth/register",
Some(json!({ "email": email, "username": "tester", "password": "supersecret" })),
None,
)
.await;
assert_eq!(status, 201);
let token = body["token"].as_str().unwrap().to_string();
// Create a medication (name/dosage/frequency/route are all required).
let (status, body) = common::send_json(
&app,
"POST",
"/api/medications",
Some(json!({
"name": "Ibuprofen",
"dosage": "200mg",
"frequency": "as needed",
"route": "oral"
})),
Some(&token),
)
.await;
assert!(
status == 200 || status == 201,
"create should succeed, body: {body}"
);
// List medications for the user — should include the one we just created.
let (status, body) =
common::send_json(&app, "GET", "/api/medications", None, Some(&token)).await;
assert_eq!(status, 200, "list should succeed, body: {body}");
let empty = Vec::new();
let arr = body.as_array().unwrap_or(&empty);
assert!(
!arr.is_empty(),
"list should contain the created medication"
);
common::drop_test_db(&db_name).await;
}
fn unique_email() -> String {
format!("test_{}@example.com", uuid::Uuid::new_v4())
}