use laravel::Application;
use laravel::config::Env;
use laravel::http::Json;
use laravel::routing::Router;
use laravel::testing::MakesHttpRequests;
use laravel::time::Timestamp;
use laravel::validation::{Rule, Rules, Valid, Validate};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::validation::errors;
fn comparison(name: &str, other: &str) -> Rule {
match name {
"after" => Rule::after(other),
"after_or_equal" => Rule::after_or_equal(other),
"before" => Rule::before(other),
"before_or_equal" => Rule::before_or_equal(other),
_ => unreachable!(),
}
}
#[tokio::test]
async fn datetimes_match_classic_or_the_explicit_format_and_precision_policy() {
let fixtures: Vec<Value> = serde_json::from_str(include_str!("fixtures/validation-datetime.json")).unwrap();
let mut failures = Vec::new();
for fixture in fixtures {
let name = fixture["rule"].as_str().unwrap();
let mut field_rules = vec![Rule::bail(), Rule::datetime()];
if name != "datetime" {
field_rules.push(comparison(name, "starts_at"));
}
let mut rules = Rules::new()
.field("event_time", field_rules)
.label("event_time", "Event time")
.label("starts_at", "Start time");
if fixture["nullable"] == true {
rules = rules.nullable("event_time");
}
let actual = errors(rules, fixture["input"].clone()).await;
let expected = fixture.get("expected_errors").unwrap_or(&fixture["errors"]);
if actual != *expected {
failures.push(format!("{name} {}: {actual} != {expected}", fixture["input"]));
}
}
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
#[derive(Debug, Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct Appointment {
#[serde(alias = "start")]
#[validate(required, datetime, label = "start time")]
starts_at: Timestamp,
#[validate(bail, required, datetime, after_or_equal("starts_at"), label = "end time")]
ends_at: Timestamp,
#[validate(before("starts_at"))]
reminder_at: Option<Timestamp>,
#[serde(default)]
#[validate(each(
bail,
datetime,
after_or_equal("starts_at"),
messages(
datetime = "Slot :position needs an offset timestamp.",
after_or_equal = "Slot :position must be at or after :date (:other)."
)
))]
slots: Vec<Option<Timestamp>>,
}
#[derive(Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct Schedule {
starts_at: Timestamp,
#[validate]
primary: Appointment,
#[validate]
appointments: Vec<Appointment>,
}
#[derive(Deserialize, Serialize, Validate)]
struct Deadline {
#[validate(datetime, label = "booking deadline")]
at: Timestamp,
}
#[derive(Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct Offer {
#[serde(alias = "policy")]
#[validate]
limit: Deadline,
#[validate(before_or_equal("limit.at"))]
ends_at: Timestamp,
}
#[derive(Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct Raw {
#[validate(datetime)]
at: 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 {
Json(input)
});
route.post("/schedules", |Valid(input): Valid<Schedule>| async { Json(input) });
route.post("/offers", |Valid(input): Valid<Offer>| async { Json(input) });
route.post("/raw", |Valid(input): Valid<Raw>| async { Json(input) });
});
})
.create()
}
#[tokio::test]
async fn json_and_forms_decode_offsets_to_timestamps_and_serialize_in_utc() {
let app = app();
let response = app
.post("/api/appointments")
.json(json!({"starts_at": "2024-02-29T05:30:00.123456789+05:30",
"ends_at": "2024-02-28T19:00:00.123456789-05:00",
"reminder_at": "2024-02-29T00:00:00.123456788Z",
"slots": [null, "2024-02-29T00:00:00.123456789Z"]}))
.await;
response.assert_ok();
assert_eq!(response.json()["starts_at"], "2024-02-29T00:00:00.123456789Z");
assert_eq!(response.json()["ends_at"], response.json()["starts_at"]);
assert_eq!(response.json()["reminder_at"], "2024-02-29T00:00:00.123456788Z");
assert_eq!(
response.json()["slots"],
json!([null, "2024-02-29T00:00:00.123456789Z"])
);
let response = app
.post("/api/appointments")
.form([
("start", " 2024-02-29t00:00:00z "),
("ends_at", "2024-02-29T00:00:00-00:00"),
("reminder_at", " "),
("slots[7]", "2024-02-29T00:00:00.000000001Z"),
("slots[9]", ""),
])
.await;
response.assert_ok();
assert_eq!(response.json()["starts_at"], "2024-02-29T00:00:00Z");
assert_eq!(response.json()["ends_at"], "2024-02-29T00:00:00Z");
assert_eq!(response.json()["reminder_at"], Value::Null);
assert_eq!(
response.json()["slots"],
json!(["2024-02-29T00:00:00.000000001Z", null])
);
let response = app
.post("/api/raw")
.json(json!({"at": "2024-02-29t05:30:00.100+05:30"}))
.await;
response.assert_ok();
assert_eq!(response.json()["at"], "2024-02-29t05:30:00.100+05:30");
}
#[tokio::test]
async fn malformed_input_uses_rule_messages_before_decoding_and_required_still_applies() {
let app = app();
for value in [
json!("2024-02-29"),
json!("2024-02-29T00:00:00"),
json!("2023-02-29T00:00:00Z"),
json!("2016-12-31T23:59:60Z"),
json!("2024-02-29T00:00:00.1234567890Z"),
json!(false),
json!(1709164800),
json!(["2024-02-29T00:00:00Z"]),
json!({"at": "2024-02-29T00:00:00Z"}),
] {
let response = app
.post("/api/appointments")
.json(json!({"starts_at": "2024-02-29T00:00:00Z", "ends_at": value}))
.await;
response.assert_status(422);
response.assert_nothing_reported();
assert_eq!(
response.json()["errors"],
json!({"ends_at": ["The end time field must be a valid date."]})
);
}
for input in [json!({}), json!({"starts_at": null, "ends_at": null})] {
let response = app.post("/api/appointments").json(&input).await;
response.assert_status(422);
assert_eq!(
response.json()["errors"],
json!({
"starts_at": ["The start time field is required."], "ends_at": ["The end time field is required."]
})
);
}
}
#[tokio::test]
async fn comparisons_reject_mixed_kinds_and_missing_or_malformed_references() {
for name in ["after", "after_or_equal", "before", "before_or_equal"] {
for (value, other) in [
("2024-02-29", "2024-02-29T00:00:00Z"),
("2024-02-29T00:00:00Z", "2024-02-29"),
] {
let rules =
Rules::new()
.field("value", [comparison(name, "other")])
.message("value", name, "Same kind required.");
assert_eq!(
errors(rules, json!({"value": value, "other": other})).await,
json!({"value": ["Same kind required."]})
);
}
for reference in [
None,
Some(json!(null)),
Some(json!("")),
Some(json!([])),
Some(json!({})),
Some(json!(true)),
Some(json!(123)),
Some(json!("2024-02-30T00:00:00Z")),
Some(json!("2024-02-29T00:00:00Z[UTC]")),
Some(json!("2016-12-31T23:59:60Z")),
] {
let mut input = json!({"value": "2024-02-29T00:00:00Z"});
if let Some(reference) = reference {
input["other"] = reference;
}
let rules = Rules::new()
.field("value", [comparison(name, "other")])
.nullable("other")
.label("other", "reference time")
.message("value", name, "Compare with :date (:other).");
assert_eq!(
errors(rules, input).await,
json!({"value": ["Compare with reference time (reference time)."]})
);
}
let rules = Rules::new().field("value", [comparison(name, "2024-02-29T00:00:00Z")]);
assert_ne!(errors(rules, json!({"value": "2024-02-29T00:00:01Z"})).await, json!({}));
}
}
#[tokio::test]
async fn nested_and_sparse_entries_compare_local_instants_with_aliases_and_labels() {
let app = app();
let response = app
.post("/api/schedules")
.json(json!({"starts_at": "2025-01-01T00:00:00Z",
"primary": {"starts_at": "2024-02-29T00:00:00Z", "ends_at": "2024-02-29T01:00:00+01:00"},
"appointments": [{"start": "2024-02-29T00:00:00Z", "ends_at": "2024-02-29T00:00:01Z"}]}))
.await;
response.assert_ok();
let response = app
.post("/api/schedules")
.form([
("starts_at", "2025-01-01T00:00:00Z"),
("primary[start]", "2024-02-29T00:00:00Z"),
("primary[ends_at]", "2024-02-29T00:00:00Z"),
("appointments[7][start]", "2024-02-29T01:00:00.000000002+01:00"),
("appointments[7][ends_at]", "2024-02-29T00:00:00.000000001Z"),
("appointments[7][slots][3]", "2024-02-29T00:00:00.000000001Z"),
("appointments[7][slots][5]", "2024-02-29T00:00:00"),
])
.await;
response.assert_status(422);
assert_eq!(
response.json()["errors"],
json!({
"appointments.7.ends_at": ["The end time field must be a date after or equal to start time."],
"appointments.7.slots.3": ["Slot 8 must be at or after start time (start time)."],
"appointments.7.slots.5": ["Slot 8 needs an offset timestamp."]
})
);
let response = app
.post("/api/offers")
.form([
("policy[at]", "2024-02-29T00:00:00.000000001Z"),
("ends_at", "2024-02-29T01:00:00.000000002+01:00"),
])
.await;
response.assert_status(422);
assert_eq!(
response.json()["errors"],
json!({"ends_at": [
"The ends at field must be a date before or equal to booking deadline."
]})
);
assert_eq!(
errors(
Appointment::declared_rules(),
json!({"starts_at": "2024-02-29T00:00:00Z",
"start": "2025-01-01T00:00:00Z", "ends_at": "2024-02-29T00:00:01Z"})
)
.await,
json!({})
);
}
#[tokio::test]
async fn comparisons_alone_preserve_nanoseconds_and_validate_the_timestamp_range() {
for (name, value, other) in [
(
"after",
"2024-02-29T00:00:00.000000002Z",
"2024-02-29T01:00:00.000000001+01:00",
),
("before", "1969-12-31T23:59:59.999999999Z", "1970-01-01T00:00:00Z"),
(
"after_or_equal",
"2024-02-29T00:00:00.1Z",
"2024-02-28T19:00:00.100-05:00",
),
(
"before_or_equal",
"2024-02-29T00:00:00.1Z",
"2024-02-28T19:00:00.100-05:00",
),
] {
let rules = Rules::new().field("value", [comparison(name, "other")]);
assert_eq!(errors(rules, json!({"value": value, "other": other})).await, json!({}));
}
for name in ["after", "before"] {
let rules = Rules::new().field("value", [comparison(name, "other")]);
assert_ne!(
errors(
rules,
json!({"value": "2024-02-29T00:00:00.000000001Z",
"other": "2024-02-29T01:00:00.000000001+01:00"})
)
.await,
json!({})
);
}
let maximum = Timestamp::MAX.to_string();
assert_eq!(
errors(
Rules::new().field("value", [Rule::datetime()]),
json!({"value": maximum})
)
.await,
json!({})
);
let rules = Rules::new()
.field("value", [Rule::before("other")])
.message("value", "date", "Invalid instant.");
assert_eq!(
errors(rules, json!({"value": "9999-12-31T23:59:59Z", "other": maximum})).await,
json!({"value": ["Invalid instant."]})
);
}
#[tokio::test]
async fn datetime_has_its_own_message_key() {
let rules = Rules::new()
.field("value", [Rule::datetime()])
.label("value", "appointment time")
.message("value", "datetime", "The :attribute needs an offset.");
assert_eq!(
errors(rules, json!({"value": "2024-02-29T00:00:00"})).await,
json!({"value": ["The appointment time needs an offset."]})
);
let rules =
Rules::new()
.field("value", [Rule::after("other")])
.message("value", "date", "Enter a date or timestamp.");
assert_eq!(
errors(rules, json!({"value": "bad", "other": "2024-02-29T00:00:00Z"})).await,
json!({"value": ["Enter a date or timestamp."]})
);
}