laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
use std::sync::{Arc, Mutex};

use laravel::Application;
use laravel::axum::body::Body;
use laravel::config::Env;
use laravel::container::Container;
use laravel::context::Context;
use laravel::foundation::ServiceProvider;
use laravel::testing::MakesHttpRequests;
use tower::ServiceExt;

type Contexts = Arc<Mutex<Vec<Option<bool>>>>;

fn app(contexts: &Contexts) -> Application {
    let contexts = Arc::clone(contexts);

    Application::configure()
        .replace_env(Env::default())
        .with_routing(|routing, _| {
            routing.health("/up").routes(|route| {
                route.get("/", || async { "Home" });
            });
        })
        .booted(move |_| async move {
            contexts
                .lock()
                .unwrap()
                .push(Context::current().as_ref().map(Context::is_request));
            drop(laravel::task::spawn(async {}));
        })
        .create()
}

async fn first_request(app: Application, uri: &str) -> http::StatusCode {
    let request = http::Request::get(uri)
        .header("host", "localhost")
        .body(Body::empty())
        .unwrap();

    app.into_router().oneshot(request).await.unwrap().status()
}

#[tokio::test]
async fn boot_hooks_run_in_an_application_context_of_their_own_whatever_boots_first() {
    for trigger in ["a page", "a health check", "the test client", "boot"] {
        let contexts = Contexts::default();
        let app = app(&contexts);

        match trigger {
            "a page" => assert_eq!(first_request(app, "/").await, 200),
            "a health check" => assert_eq!(first_request(app, "/up").await, 200),
            "the test client" => {
                app.get("/").await.assert_ok();
            }
            _ => app.boot().await.unwrap(),
        }

        assert_eq!(*contexts.lock().unwrap(), [Some(false)], "booted by {trigger}");
    }
}

pub struct Mailer;

struct NeedsMailer;

impl ServiceProvider for NeedsMailer {
    async fn boot(&self, app: &Container) -> laravel::Result<()> {
        app.resolve::<Mailer>().await?;
        Ok(())
    }
}

#[tokio::test]
async fn failing_boot_hooks_are_named() {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_providers(|providers| {
            providers.add(NeedsMailer);
        })
        .create();

    let error = app.boot().await.unwrap_err().to_string();

    assert!(
        error.starts_with(
            "booting `integration::boot::NeedsMailer` failed: there's no `integration::boot::Mailer` service"
        ),
        "{error}"
    );
}

#[tokio::test]
async fn boot_hooks_that_panic_are_named_with_where_they_panicked() {
    let app = Application::configure()
        .replace_env(Env::default())
        .booted(|_| async {
            if true {
                panic!("the mailer is missing");
            }
        })
        .create();

    let error = app.boot().await.unwrap_err().to_string();

    assert!(
        error.starts_with("booting the application failed: panic at tests/boot.rs:"),
        "{error}"
    );
    assert!(error.contains("the mailer is missing"), "{error}");
}

#[tokio::test]
async fn a_boot_that_stops_being_awaited_is_resumed() {
    let release = Arc::new(tokio::sync::Notify::new());
    let runs = Arc::new(Mutex::new(0));
    let app = Application::configure()
        .replace_env(Env::default())
        .booted({
            let (release, runs) = (Arc::clone(&release), Arc::clone(&runs));
            move |_| async move {
                *runs.lock().unwrap() += 1;
                release.notified().await;
            }
        })
        .create();

    let abandoned = tokio::time::timeout(std::time::Duration::from_millis(10), app.boot()).await;
    assert!(abandoned.is_err(), "the hook is still waiting");
    release.notify_one();

    app.boot().await.unwrap();
    assert_eq!(*runs.lock().unwrap(), 1);
}

#[test]
fn a_route_at_the_health_checks_path_stops_the_application() {
    let error = Application::configure()
        .replace_env(Env::default())
        .with_routing(|routing, _| {
            routing.health("/up").web(|route| {
                route.get("/up", || async { "status page" });
                route.post("/up", || async { "posted" });
            });
        })
        .try_create()
        .unwrap_err();

    assert_eq!(
        error,
        laravel::foundation::StartupError::Routes(vec![
            "`GET /up` can't be reached, since the health check answers `/up`: give one of them another path"
                .to_owned()
        ])
    );
}