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).
This commit is contained in:
parent
7ba78a31fb
commit
bd1b7c2925
13 changed files with 937 additions and 338 deletions
186
backend/tests/common/mod.rs
Normal file
186
backend/tests/common/mod.rs
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
//! Shared integration-test helpers.
|
||||
//!
|
||||
//! These tests need a live MongoDB. Each test process targets a unique database
|
||||
//! (`normogen_test_<random>`), so parallel `cargo test` runs don't collide, and
|
||||
//! drops it on completion. When Mongo is unreachable the tests skip gracefully
|
||||
//! (printing a note) so `cargo test` stays green on machines without Mongo — the
|
||||
//! CI job provides Mongo and runs them for real.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{body::Body, http::Request, Router};
|
||||
use mongodb::Client;
|
||||
use normogen_backend::{
|
||||
app::build_app,
|
||||
auth::{JwtService, TokenVersionCache},
|
||||
config::{
|
||||
Config, CorsConfig, DatabaseConfig, EncryptionConfig, Environment, JwtConfig, ServerConfig,
|
||||
},
|
||||
db::MongoDb,
|
||||
models::{health_stats::HealthStatisticsRepository, refresh_token::RefreshTokenRepository},
|
||||
security, services,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use tower::util::ServiceExt;
|
||||
|
||||
/// Unique test DB name per process. Suffixing with a UUID keeps concurrent test
|
||||
/// runs (local + CI) from stomping on each other.
|
||||
pub fn test_db_name() -> String {
|
||||
format!("normogen_test_{}", uuid::Uuid::new_v4())
|
||||
}
|
||||
|
||||
/// The Mongo URI to connect to during tests. Defaults to the local dev instance.
|
||||
pub fn mongo_uri() -> String {
|
||||
std::env::var("MONGODB_URI").unwrap_or_else(|_| "mongodb://localhost:27017".to_string())
|
||||
}
|
||||
|
||||
/// Quick (~1s) reachability check so tests skip fast when Mongo is absent.
|
||||
/// Builds a throwaway client with a short server-selection timeout and pings;
|
||||
/// we don't use the real client afterwards (that's `MongoDb::new`).
|
||||
pub async fn mongo_available() -> bool {
|
||||
let mut opts = match mongodb::options::ClientOptions::parse(&mongo_uri()).await {
|
||||
Ok(o) => o,
|
||||
Err(_) => return false,
|
||||
};
|
||||
opts.server_selection_timeout = Some(std::time::Duration::from_secs(1));
|
||||
opts.connect_timeout = Some(std::time::Duration::from_secs(1));
|
||||
let client = match Client::with_options(opts) {
|
||||
Ok(c) => c,
|
||||
Err(_) => return false,
|
||||
};
|
||||
client
|
||||
.database("admin")
|
||||
.run_command(mongodb::bson::doc! { "ping": 1 }, None)
|
||||
.await
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
/// A Config suitable for tests: development environment (so insecure-secret
|
||||
/// defaults are allowed), short JWT expiries, a test JWT secret.
|
||||
pub fn test_config(db_name: &str) -> Config {
|
||||
Config {
|
||||
server: ServerConfig {
|
||||
host: "127.0.0.1".to_string(),
|
||||
port: 0, // not bound in-process; tests use Router::oneshot
|
||||
},
|
||||
database: DatabaseConfig {
|
||||
uri: mongo_uri(),
|
||||
database: db_name.to_string(),
|
||||
},
|
||||
jwt: JwtConfig {
|
||||
secret: "test-secret-not-for-production".to_string(),
|
||||
access_token_expiry_minutes: 15,
|
||||
refresh_token_expiry_days: 7,
|
||||
},
|
||||
encryption: EncryptionConfig {
|
||||
key: "test-encryption-key".to_string(),
|
||||
},
|
||||
cors: CorsConfig {
|
||||
allowed_origins: vec!["http://localhost:3000".to_string()],
|
||||
},
|
||||
environment: Environment::Development,
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the full app against a fresh, isolated test database.
|
||||
///
|
||||
/// Returns `(router, db_name)` so callers can drop the database when done. The
|
||||
/// router is the exact same one served in production (all routes + middleware),
|
||||
/// just driven in-process via `oneshot`.
|
||||
pub async fn app_for_test() -> Option<(Router, String)> {
|
||||
let db_name = test_db_name();
|
||||
|
||||
// Fast, bounded connectivity probe: if Mongo isn't reachable, skip the test
|
||||
// in ~1s instead of waiting on `MongoDb::new`'s 10s server-selection
|
||||
// timeout (which would hang `cargo test` on machines without Mongo).
|
||||
if !mongo_available().await {
|
||||
eprintln!(
|
||||
"[integration] skipping: MongoDB unreachable at {}",
|
||||
mongo_uri()
|
||||
);
|
||||
return None;
|
||||
}
|
||||
|
||||
let db = match MongoDb::new(&mongo_uri(), &db_name).await {
|
||||
Ok(db) => db,
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"[integration] skipping: MongoDB connect failed at {}: {}",
|
||||
mongo_uri(),
|
||||
e
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let config = test_config(&db_name);
|
||||
let jwt_service = JwtService::new(config.jwt.clone());
|
||||
let database = db.get_database();
|
||||
|
||||
// Best-effort index creation (mirrors main.rs).
|
||||
let _ = normogen_backend::db::DatabaseInitializer::new(database.clone())
|
||||
.initialize()
|
||||
.await;
|
||||
|
||||
let token_version_cache = Arc::new(TokenVersionCache::with_default_ttl());
|
||||
let refresh_token_repo = Arc::new(RefreshTokenRepository::new(&database));
|
||||
let audit_logger = security::AuditLogger::new(&database);
|
||||
let session_manager = security::SessionManager::new(&database);
|
||||
let account_lockout = security::AccountLockout::new(database.collection("users"), 5, 15, 1440);
|
||||
let health_stats_repo = HealthStatisticsRepository::new(&database);
|
||||
let interaction_service = Arc::new(services::InteractionService::new());
|
||||
|
||||
let state = normogen_backend::config::AppState {
|
||||
db,
|
||||
jwt_service,
|
||||
config: config.clone(),
|
||||
audit_logger: Some(audit_logger),
|
||||
session_manager: Some(session_manager),
|
||||
account_lockout: Some(account_lockout),
|
||||
health_stats_repo: Some(health_stats_repo),
|
||||
mongo_client: None,
|
||||
interaction_service: Some(interaction_service),
|
||||
token_version_cache,
|
||||
refresh_token_repo: Some(refresh_token_repo),
|
||||
};
|
||||
|
||||
Some((build_app(state), db_name))
|
||||
}
|
||||
|
||||
/// Drop a test database (best-effort teardown).
|
||||
pub async fn drop_test_db(db_name: &str) {
|
||||
if let Ok(client) = Client::with_uri_str(&mongo_uri()).await {
|
||||
let _ = client.database(db_name).drop(None).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience: drive the router with a JSON request and return the status +
|
||||
/// parsed JSON body.
|
||||
pub async fn send_json(
|
||||
app: &Router,
|
||||
method: &str,
|
||||
uri: &str,
|
||||
body: Option<Value>,
|
||||
auth_token: Option<&str>,
|
||||
) -> (u16, Value) {
|
||||
let mut builder = Request::builder().method(method).uri(uri);
|
||||
if let Some(token) = auth_token {
|
||||
builder = builder.header("Authorization", format!("Bearer {}", token));
|
||||
}
|
||||
let request = if let Some(json) = body {
|
||||
builder
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(serde_json::to_vec(&json).unwrap()))
|
||||
.unwrap()
|
||||
} else {
|
||||
builder.body(Body::empty()).unwrap()
|
||||
};
|
||||
|
||||
let response = app.clone().oneshot(request).await.unwrap();
|
||||
let status = response.status().as_u16();
|
||||
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let json: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
|
||||
(status, json)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue