laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
use laravel::Application;
use laravel::config::Env;
use laravel::http::Json;
use laravel::routing::Router;
use laravel::testing::MakesHttpRequests;
use laravel::time::{Timestamp, civil::Date};
use laravel::validation::{Rule, Rules, Valid, Validate};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::validation::errors;

#[derive(Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct Appointment {
    #[validate(required, timezone)]
    timezone: String,
    #[serde(alias = "start")]
    #[validate(datetime, label = "start time")]
    starts_at: Timestamp,
    #[validate(date_equals("starts_at"))]
    confirmed_at: Timestamp,
    #[validate(date_format("%d/%m/%Y", "%Y-%m-%d"), label = "birthday")]
    birthday: String,
    #[validate(date_format("%H:%M"))]
    reminder: Option<String>,
}

#[derive(Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct Schedule {
    #[validate]
    appointments: Vec<Appointment>,
    #[validate(each(timezone, messages(timezone = "Zone :position is invalid.")))]
    zones: Vec<String>,
    #[validate(each(date_format("%Y-%m-%d")))]
    dates: Vec<String>,
}

fn app() -> Application {
    Application::configure()
        .replace_env(Env::default())
        .with_routing(|routing, _| {
            routing.api(|route: &mut Router| {
                route.post("/appointments", |Valid(input): Valid<Appointment>| async {
                    let _date = Date::strptime("%d/%m/%Y", &input.birthday)
                        .or_else(|_| Date::strptime("%Y-%m-%d", &input.birthday))
                        .unwrap();
                    Json(input)
                });
                route.post("/schedules", |Valid(input): Valid<Schedule>| async { Json(input) });
            });
        })
        .create()
}

fn appointment() -> Value {
    json!({"timezone": "America/Chicago", "start": "2024-02-29T00:00:00.123456789Z",
        "confirmed_at": "2024-02-28T19:00:00.123456789-05:00", "birthday": "29/02/2024"})
}

#[tokio::test]
async fn json_and_forms_validate_before_typed_decoding() {
    let app = app();
    let response = app.post("/api/appointments").json(appointment()).await;
    response.assert_ok();
    assert_eq!(response.json()["birthday"], "29/02/2024");
    assert_eq!(response.json()["starts_at"], response.json()["confirmed_at"]);

    let response = app
        .post("/api/appointments")
        .form([
            ("timezone", "UTC"),
            ("start", "2024-02-29T00:00:00Z"),
            ("confirmed_at", "2024-02-29T01:00:00+01:00"),
            ("birthday", "2024-02-29"),
            ("reminder", "09:30"),
        ])
        .await;
    response.assert_ok();
    assert_eq!(response.json()["reminder"], "09:30");

    let mut input = appointment();
    input["timezone"] = json!("+05:30");
    input["confirmed_at"] = json!("2024-02-29T00:00:00.123456788Z");
    input["birthday"] = json!("29/02/2023");
    let response = app.post("/api/appointments").json(&input).await;
    response.assert_status(422);
    assert_eq!(
        response.json()["errors"],
        json!({
            "timezone": ["The timezone field must be a valid timezone."],
        "confirmed_at": ["The confirmed at field must be a date equal to start time."],
            "birthday": ["The birthday field must match the format %d/%m/%Y, %Y-%m-%d."]
        })
    );
}

#[tokio::test]
async fn nested_references_and_each_rules_keep_their_scopes() {
    let mut second = appointment();
    second["start"] = json!("2025-03-01T00:00:00Z");
    let response = app()
        .post("/api/schedules")
        .json(json!({
            "appointments": [appointment(), second], "zones": ["UTC", "Mars/Olympus"],
            "dates": ["2024-02-29", "2023-02-29"]
        }))
        .await;
    response.assert_status(422);
    assert_eq!(
        response.json()["errors"],
        json!({
        "appointments.1.confirmed_at": ["The appointments.1.confirmed_at field must be a date equal to start time."],
            "zones.1": ["Zone 2 is invalid."],
            "dates.1": ["The dates.1 field must match the format %Y-%m-%d."]
        })
    );
}

#[tokio::test]
async fn timezone_uses_the_iana_database_ignoring_case() {
    for (value, valid) in [
        (json!("UTC"), true),
        (json!("America/Chicago"), true),
        (json!("america/chicago"), true),
        (json!("Mars/Olympus"), false),
        (json!("+05:30"), false),
        (json!("EST5EDT,M3.2.0,M11.1.0"), false),
        (json!(123), false),
    ] {
        let actual = errors(Rules::new().field("zone", [Rule::timezone()]), json!({"zone": value})).await;
        assert_eq!(actual == json!({}), valid, "{value}: {actual}");
    }
}

#[tokio::test]
async fn equality_requires_matching_temporal_kinds_and_valid_references() {
    for (left, right, valid) in [
        ("2024-02-29", json!("2024-02-29"), true),
        ("2024-02-29", json!("2024-03-01"), false),
        ("2024-02-29", json!("2024-02-29T00:00:00Z"), false),
        ("2024-02-29", Value::Null, false),
        ("2024-02-29", json!("invalid"), false),
    ] {
        let actual = errors(
            Rules::new().field("date", [Rule::date_equals("other")]),
            json!({"date": left, "other": right}),
        )
        .await;
        assert_eq!(actual == json!({}), valid, "{left}, {right}: {actual}");
    }
    let rules = || Rules::new().field("date", [Rule::date_equals("other")]);
    assert_eq!(
        errors(rules(), json!({"date": "invalid"})).await,
        json!({"date": ["The date field must be a valid date."]})
    );
    assert_eq!(
        errors(rules(), json!({"date": "2024-02-29"})).await,
        json!({"date": ["The date field must be a date equal to other."]})
    );
}

#[tokio::test]
async fn formats_check_real_components_and_exact_submitted_text() {
    for (format, text, valid) in [
        ("%d/%m/%Y", "29/02/2024", true),
        ("%d/%m/%Y", "29/02/2023", false),
        ("%d/%m/%Y", "1/02/2024", false),
        ("%Y-%m-%d", "2024-02-29junk", false),
        ("%Y-%m-%d", "2024-02-29\n", false),
        ("%Y-%m-%dT%H:%M", "2024-02-29T23:59", true),
        ("%Y-%m-%dT%H:%M", "2024-04-31T23:59", false),
        ("%H:%M", "09:30", true),
        ("%H:%M", "24:00", false),
        ("%H:%M:%S", "23:59:60", false),
        ("%a %Y-%m-%d", "Thu 2024-02-29", true),
        ("%a %Y-%m-%d", "Fri 2024-02-29", false),
        ("%F %j", "2024-02-29 060", true),
        ("%F %j", "2024-02-29 061", false),
        ("%Y-%m-%dT%H:%M:%S%:z", "2024-02-29T09:30:00+05:30", true),
    ] {
        let rule = Rule::date_format([format]).unwrap();
        let actual = errors(Rules::new().field("date", [rule]), json!({"date": text})).await;
        assert_eq!(actual == json!({}), valid, "{format}: {text}: {actual}");
    }
    assert!(Rule::date_format(Vec::<String>::new()).is_err());
    for format in ["%", "%K", "%Y-%m", "%m %H", "%M", "literal", "%Z"] {
        assert!(Rule::date_format([format]).is_err(), "{format}");
    }
}