glacier-web 0.1.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! In-process testing: drive an `App` without opening a socket.
//!
//! `TestClient` behaves like a browser: it keeps cookies between requests,
//! and once it has loaded a page containing a CSRF field it sends that token
//! with later form submissions. So, as in a browser, visit the form before
//! submitting it. Sessions, flash and CSRF protection all work for real.
//!
//! [`setup`] prepares the usual app test: `config/test.toml` plus a freshly
//! migrated database (in memory, with the default test config).
//!
//! ```
//! use glacier::prelude::*;
//! use glacier::testing::TestClient;
//!
//! # glacier::__private::tokio::runtime::Runtime::new().unwrap().block_on(async {
//! let app = App::new().routes(|r| {
//!     r.get("/", |_ctx| async { "hi" });
//! });
//! let res = TestClient::new(app).get("/").await;
//! assert_eq!(res.body_text(), "hi");
//! # });
//! ```

use std::collections::BTreeMap;
use std::sync::Mutex;

use bytes::Bytes;
use http::{Method, header};
use serde::Serialize;

use crate::app::{App, Service};
use crate::config::{Config, Env};
use crate::cookies::Cookie;
use crate::db::Repo;
use crate::db::migration::{Migration, Migrator};
use crate::response::Response;

mod ambient;

pub use ambient::{
    Form, FormValue, Harness, JsonBody, Status, TestResponse, assert_contains, assert_equal,
    assert_not_equal, assert_true, bearer, delete, errors_on, file, get, header, insert, patch,
    patch_json, perform_jobs, post, post_json, put, put_json, refute_contains, refute_true, run,
    sequence,
};

pub struct TestClient {
    service: Service,
    cookies: Mutex<BTreeMap<String, String>>,
    csrf_token: Mutex<Option<String>>,
    /// Headers sent with every later request, such as a bearer token.
    headers: Mutex<Vec<(header::HeaderName, header::HeaderValue)>>,
}

/// Loads `config/test.toml`, connects to its database and runs
/// `migrations`. With the default `sqlite::memory:` test database, every
/// call gets a fresh, isolated database.
///
/// ```ignore
/// async fn client() -> TestClient {
///     let (config, repo) = glacier::testing::setup(blog::migrations::all()).await;
///     TestClient::new(blog::app(config, repo).unwrap())
/// }
/// ```
///
/// # Panics
///
/// If the config, database or migrations fail; this is test setup.
pub async fn setup(migrations: Vec<Migration>) -> (Config, Repo) {
    let config = Config::load_from("config", Env::Test).expect("loading config/test.toml");
    let repo = Repo::from_config(&config)
        .await
        .expect("connecting to the test database (database.url in config/test.toml)");
    Migrator::new(&repo, migrations)
        .expect("invalid migrations")
        .migrate()
        .await
        .expect("migrating the test database");
    (config, repo)
}

impl TestClient {
    /// Builds the app, in the test environment unless it was set explicitly.
    pub fn new(mut app: App) -> Self {
        app.env.get_or_insert(Env::Test);
        Self {
            service: app.build(),
            cookies: Mutex::default(),
            csrf_token: Mutex::default(),
            headers: Mutex::default(),
        }
    }

    pub async fn get(&self, path: &str) -> Response {
        self.send(Method::GET, path, Bytes::new(), None).await
    }

    pub async fn delete(&self, path: &str) -> Response {
        self.send(Method::DELETE, path, Bytes::new(), None).await
    }

    pub async fn post_form<T: Serialize + ?Sized>(&self, path: &str, form: &T) -> Response {
        self.send_form(Method::POST, path, form).await
    }

    pub async fn patch_form<T: Serialize + ?Sized>(&self, path: &str, form: &T) -> Response {
        self.send_form(Method::PATCH, path, form).await
    }

    pub async fn post_json<T: Serialize + ?Sized>(&self, path: &str, json: &T) -> Response {
        self.send_json(Method::POST, path, json).await
    }

    pub async fn patch_json<T: Serialize + ?Sized>(&self, path: &str, json: &T) -> Response {
        self.send_json(Method::PATCH, path, json).await
    }

    pub async fn put_json<T: Serialize + ?Sized>(&self, path: &str, json: &T) -> Response {
        self.send_json(Method::PUT, path, json).await
    }

    async fn send_json<T: Serialize + ?Sized>(
        &self,
        method: Method,
        path: &str,
        json: &T,
    ) -> Response {
        let body = serde_json::to_vec(json).expect("failed to serialize test JSON");
        self.send(method, path, body.into(), Some("application/json"))
            .await
    }

    /// Runs the background jobs that are due (`App::jobs`), as Rails'
    /// `perform_enqueued_jobs`, returning how many ran.
    ///
    /// # Panics
    ///
    /// If the app has no jobs registered.
    pub async fn perform_jobs(&self) -> crate::Result<usize> {
        let jobs = self
            .service
            .state::<crate::jobs::Jobs>()
            .expect("perform_jobs needs App::jobs")
            .clone();
        jobs.perform_due().await
    }

    /// Sends `Authorization: Bearer <token>` with later requests, as an API
    /// client that has signed in does.
    pub fn bearer(&self, token: impl AsRef<str>) {
        self.header("authorization", format!("Bearer {}", token.as_ref()));
    }

    /// Sends `name: value` with later requests, replacing any earlier value.
    ///
    /// # Panics
    ///
    /// If the name or value isn't valid in a header.
    pub fn header(&self, name: &str, value: impl AsRef<str>) {
        let name = header::HeaderName::try_from(name).expect("invalid header name");
        let value = header::HeaderValue::try_from(value.as_ref()).expect("invalid header value");
        let mut headers = self.headers.lock().unwrap();
        headers.retain(|(existing, _)| *existing != name);
        headers.push((name, value));
    }

    /// Sends an arbitrary request, adding stored cookies unless it already
    /// has a `Cookie` header.
    pub async fn request(&self, mut req: http::Request<Bytes>) -> Response {
        for (name, value) in self.headers.lock().unwrap().iter() {
            if !req.headers().contains_key(name) {
                req.headers_mut().insert(name.clone(), value.clone());
            }
        }
        let unsafe_method = !matches!(*req.method(), Method::GET | Method::HEAD);
        let has_token = req.headers().contains_key(crate::csrf::HEADER)
            || req.body().windows(12).any(|w| w == b"_csrf_token=");
        if unsafe_method
            && !has_token
            && let Some(token) = self.csrf_token.lock().unwrap().clone()
        {
            req.headers_mut().insert(
                crate::csrf::HEADER,
                token.try_into().expect("invalid CSRF token"),
            );
        }
        if !req.headers().contains_key(header::COOKIE)
            && let Some(cookie) = self.cookie_header()
        {
            req.headers_mut().insert(
                header::COOKIE,
                cookie.try_into().expect("invalid cookie header"),
            );
        }
        let res = self.service.call(req).await;
        self.store_cookies(&res);
        self.remember_csrf_token(&res);
        res
    }

    /// Keeps the token from a CSRF field in an HTML page, as a browser
    /// would by holding the form.
    fn remember_csrf_token(&self, res: &Response) {
        let body = res.body();
        let marker = format!(r#"name="{}" value=""#, crate::csrf::FORM_FIELD);
        let Some(start) = body
            .windows(marker.len())
            .position(|w| w == marker.as_bytes())
            .map(|i| i + marker.len())
        else {
            return;
        };
        let token: String = body[start..]
            .iter()
            .take_while(|b| b.is_ascii_hexdigit())
            .map(|&b| b as char)
            .collect();
        if !token.is_empty() {
            *self.csrf_token.lock().unwrap() = Some(token);
        }
    }

    /// A cookie the client currently holds (raw, possibly encrypted value).
    pub fn cookie(&self, name: &str) -> Option<String> {
        self.cookies.lock().unwrap().get(name).cloned()
    }

    pub fn clear_cookies(&self) {
        self.cookies.lock().unwrap().clear();
    }

    fn cookie_header(&self) -> Option<String> {
        let cookies = self.cookies.lock().unwrap();
        (!cookies.is_empty()).then(|| {
            cookies
                .iter()
                .map(|(name, value)| format!("{name}={value}"))
                .collect::<Vec<_>>()
                .join("; ")
        })
    }

    fn store_cookies(&self, res: &Response) {
        let mut cookies = self.cookies.lock().unwrap();
        for value in res.headers().get_all(header::SET_COOKIE) {
            let Some(cookie) = value.to_str().ok().and_then(|v| Cookie::parse(v).ok()) else {
                continue;
            };
            let removed = cookie.max_age().is_some_and(|age| age.is_zero());
            if removed {
                cookies.remove(cookie.name());
            } else {
                cookies.insert(cookie.name().to_owned(), cookie.value().to_owned());
            }
        }
    }

    pub async fn put_form<T: Serialize + ?Sized>(&self, path: &str, form: &T) -> Response {
        self.send_form(Method::PUT, path, form).await
    }

    /// Sends `form` with any method.
    pub async fn send_form<T: Serialize + ?Sized>(
        &self,
        method: Method,
        path: &str,
        form: &T,
    ) -> Response {
        let body = serde_urlencoded::to_string(form).expect("failed to serialize test form");
        self.send(
            method,
            path,
            body.into(),
            Some("application/x-www-form-urlencoded"),
        )
        .await
    }

    async fn send(
        &self,
        method: Method,
        path: &str,
        body: Bytes,
        content_type: Option<&str>,
    ) -> Response {
        let mut req = http::Request::builder().method(method).uri(path);
        if let Some(content_type) = content_type {
            req = req.header(header::CONTENT_TYPE, content_type);
        }
        self.request(req.body(body).expect("invalid test request"))
            .await
    }
}