Lines
70.97 %
Functions
66.67 %
Branches
100 %
use chrono::Utc;
use redis::Client;
use std::sync::{Arc, Once};
use uuid::Uuid;
use web::{AppState, Config, jwt_auth::JWTAuthMiddleware, model::User};
static TEST_ENV_INIT: Once = Once::new();
fn ensure_test_env() {
TEST_ENV_INIT.call_once(|| {
if std::env::var("DATABASE_URL").is_err()
&& let Ok(contents) = std::fs::read_to_string(".env")
&& let Some(db_url) = contents
.lines()
.map(str::trim)
.find_map(|line| line.strip_prefix("DATABASE_URL=").map(str::to_string))
&& !db_url.trim().is_empty()
{
unsafe {
std::env::set_var("DATABASE_URL", db_url);
}
if std::env::var("DATABASE_URL").is_err() {
// Used by server::db LazyLock during integration tests.
// Connection may still fail, but this avoids startup panic and lock poisoning.
std::env::set_var(
"DATABASE_URL",
"postgres://postgres:postgres@127.0.0.1:5432/postgres",
);
});
/// Create a test app state with mock configuration
pub async fn create_test_app_state() -> Arc<AppState> {
ensure_test_env();
let config = Config {
site_url: "http://localhost:3000".to_string(),
redis_url: "redis://localhost:6379".to_string(),
access_token_max_age: 15,
refresh_token_max_age: 60,
ssh: web::config::SshConnectInfo {
hostname: "ssh.example.invalid".to_string(),
port: 2222,
host_fingerprint: "(test)".to_string(),
},
};
let redis_client = Client::open("redis://localhost:6379").unwrap_or_else(|_| {
Client::open("redis://127.0.0.1:6379")
.unwrap_or_else(|_| panic!("Failed to connect to Redis for testing"))
AppState::new(config, redis_client)
/// Create a mock user for testing
pub fn create_mock_user() -> User {
User {
id: Uuid::new_v4(),
name: "Test User".to_string(),
email: "test@example.com".to_string(),
password: "hashed_password".to_string(),
role: "user".to_string(),
photo: "photo.jpg".to_string(),
verified: true,
database: "test_db".to_string(),
created_at: Some(Utc::now()),
updated_at: Some(Utc::now()),
/// Create mock JWT auth middleware for testing
pub fn create_mock_jwt_auth(user: User) -> JWTAuthMiddleware {
JWTAuthMiddleware {
user,
access_token_uuid: Uuid::new_v4(),