use std::sync::{Arc, Mutex};
use laravel::Application;
use laravel::config::{Env, session::Driver};
use laravel::crypt::{Cipher, Encrypter};
use laravel::http::{Json, Request};
use laravel::routing::Router;
use laravel::testing::MakesHttpRequests;
use laravel::validation::{
Field, InputValue, Rule, RuleError, Rules, Valid, Validate, ValidationError, ValidationRule,
};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::support::Invalid;
type Calls = Arc<Mutex<Vec<(String, Option<InputValue>)>>>;
struct Directory {
calls: Calls,
unavailable: bool,
}
impl Directory {
async fn available(&self, field: &Field<'_>) -> laravel::Result<bool> {
tokio::task::yield_now().await;
self.calls
.lock()
.unwrap()
.push((field.name.to_owned(), field.value.cloned()));
if self.unavailable {
return Err(
laravel::Error::new(503, std::io::Error::other("directory offline")).with_header("retry-after", "30")
);
}
Ok(field.value.and_then(InputValue::as_str) != Some("taken")
&& field.get("tenant").and_then(InputValue::as_str) == Some("laravel"))
}
}
struct Available;
impl ValidationRule for Available {
async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
if laravel::resolve::<Directory>().await.unwrap().available(field).await? {
Ok(())
} else {
Err(RuleError::invalid(format!("The {} is unavailable.", field.label())))
}
}
}
#[derive(Debug, Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct User {
tenant: String,
#[serde(alias = "handle")]
#[validate(required, max_length = 5, Available, label = "user name")]
name: String,
age: u32,
}
#[derive(Debug, Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct Batch {
#[validate]
owner: User,
#[serde(alias = "people")]
#[validate]
users: Vec<User>,
}
fn app(unavailable: bool) -> (Application, Calls) {
let calls = Calls::default();
let recorded = calls.clone();
let app = Application::configure()
.replace_env(Env::default())
.with_config(|config, _| {
config.app.key = Some(Encrypter::generate_key(Cipher::Aes256Cbc));
config.session.driver = Driver::Memory;
})
.with_services(move |app| {
app.instance(Directory {
calls: recorded,
unavailable,
});
})
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.post("/users", |Valid(user): Valid<User>| async move { Json(user) });
route.post("/manual", |request: Request| async move {
let user: User = request.validate().await?;
laravel::Result::<Json<User>>::Ok(Json(user))
});
route.post("/caught", |request: Request| async move {
let user = match request.validate::<User>().await {
Ok(user) => user,
Err(ValidationError::Invalid(errors)) => {
return Ok(laravel::http::Response::new((
laravel::http::StatusCode::UNPROCESSABLE_ENTITY,
Json(errors),
)));
}
Err(ValidationError::Failed(error)) if error.is::<std::io::Error>() => {
return Ok(laravel::http::Response::new((
laravel::http::StatusCode::SERVICE_UNAVAILABLE,
"Try again later.",
)));
}
Err(ValidationError::Failed(error)) => return Err(error),
};
Ok(laravel::http::Response::new(Json(user)))
});
route.post("/batch", |Valid(batch): Valid<Batch>| async move { Json(batch) });
route.post("/bail", |Valid(user): Valid<BailUser>| async move { Json(user) });
route.post("/lists", |Valid(_): Valid<BailLists>| async { "saved" });
});
routing.web(|route: &mut Router| {
route.post("/users", |Valid(user): Valid<User>| async move { Json(user) });
});
})
.create();
(app, calls)
}
#[tokio::test]
async fn async_rules_resolve_services_in_extractors_and_manual_validation() {
let (app, calls) = app(false);
for path in ["/api/users", "/api/manual"] {
app.post(path)
.json(json!({"tenant":"laravel", "name":"rust", "age":42}))
.await
.assert_ok()
.assert_nothing_reported()
.assert_json(json!({"name":"rust", "age":42}));
}
assert_eq!(calls.lock().unwrap().len(), 2);
}
#[tokio::test]
async fn handlers_can_match_field_errors_and_catch_operational_failures() {
let (available, _) = app(false);
available
.post("/api/caught")
.json(json!({"tenant":"laravel", "name":"rust", "age":42}))
.await
.assert_ok()
.assert_json(json!({"name":"rust", "age":42}));
available
.post("/api/caught")
.json(json!({"tenant":"laravel", "name":"taken", "age":42}))
.await
.assert_status(422)
.assert_json(json!({"name":["The user name is unavailable."]}))
.assert_nothing_reported();
let (unavailable, _) = app(true);
unavailable
.post("/api/caught")
.json(json!({"tenant":"laravel", "name":"too-long", "age":42}))
.await
.assert_status(503)
.assert_see("Try again later.")
.assert_nothing_reported();
}
#[tokio::test]
async fn async_messages_merge_with_decode_errors_and_keep_sparse_alias_paths() {
let (app, calls) = app(false);
app.post("/api/batch")
.form([
("owner[tenant]", "laravel"),
("owner[handle]", "rust"),
("owner[age]", "42"),
("people[7][tenant]", "laravel"),
("people[7][handle]", "taken"),
("people[7][age]", "many"),
("people[2][tenant]", "other"),
("people[2][name]", "rust"),
("people[2][age]", "42"),
])
.await
.assert_status(422)
.assert_nothing_reported()
.assert_json(json!({"errors": {
"people.7.handle": ["The user name is unavailable."],
"people.7.age": ["The people.7.age field must be an integer."],
"people.2.name": ["The user name is unavailable."]
}}));
assert_eq!(
*calls.lock().unwrap(),
vec![
("owner.handle".into(), Some(InputValue::from("rust"))),
("people.7.handle".into(), Some(InputValue::from("taken"))),
("people.2.name".into(), Some(InputValue::from("rust"))),
]
);
}
#[tokio::test]
async fn async_field_errors_redirect_and_flash_original_input() {
let (app, _) = app(false);
app.post("/users")
.header("referer", "/form")
.form([
("tenant", "laravel"),
("handle", "taken"),
("age", "42"),
("password", "secret"),
])
.await
.assert_redirect_to("/form")
.assert_nothing_reported()
.assert_invalid(&["handle"])
.assert_session_has("_old_input.handle", "taken")
.assert_session_missing("_old_input.password");
}
#[tokio::test]
async fn operational_failure_aborts_validation_and_keeps_the_service_error() {
let (app, calls) = app(true);
for path in ["/api/users", "/api/manual", "/users"] {
let response = app
.post(path)
.json(json!({"tenant":"laravel", "name":"too-long", "age":42}))
.await;
response
.assert_status(503)
.assert_header("retry-after", "30")
.assert_reported::<std::io::Error>()
.assert_dont_see("directory offline");
if path == "/users" {
response
.assert_session_missing("errors")
.assert_session_missing("_old_input");
}
}
assert_eq!(calls.lock().unwrap().len(), 3);
}
#[derive(Debug, Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct BailUser {
tenant: String,
#[validate(required, max_length = 5, Available, bail, messages(max_length = "Too long."))]
name: String,
#[validate(max_length = 5, Available, bail)]
optional: Option<String>,
#[validate(Available)]
other: String,
}
#[tokio::test]
async fn bail_applies_before_its_position_and_only_stops_its_own_field() {
let (app, calls) = app(false);
app.post("/api/bail")
.header("accept", "application/json")
.json(json!({"tenant":"laravel", "name":"too-long", "optional":null, "other":"taken"}))
.await
.assert_status(422)
.assert_nothing_reported()
.assert_json(json!({"errors": {
"name": ["Too long."], "other": ["The other is unavailable."]
}}));
assert_eq!(
*calls.lock().unwrap(),
vec![("other".into(), Some(InputValue::from("taken")))]
);
calls.lock().unwrap().clear();
app.post("/api/bail")
.header("accept", "application/json")
.json(json!({"tenant":"laravel", "other":"rust"}))
.await
.assert_status(422)
.assert_invalid(&["name"]);
assert_eq!(
*calls.lock().unwrap(),
vec![("other".into(), Some(InputValue::from("rust")))]
);
}
#[derive(Debug, Deserialize, Validate)]
#[validate(anyone)]
#[expect(dead_code, reason = "only validation is exercised")]
struct BailLists {
tenant: String,
#[validate(max_items = 1, bail)]
#[validate]
users: Vec<User>,
#[validate(each(max_length = 5, Available, bail))]
names: Vec<String>,
}
#[tokio::test]
async fn collection_bail_suppresses_children_while_entry_bail_keeps_other_entries() {
let (app, calls) = app(false);
app.post("/api/lists")
.header("accept", "application/json")
.json(json!({
"tenant":"laravel", "users":[{}, {}], "names":["too-long", "taken", "rust", 42]
}))
.await
.assert_status(422)
.assert_nothing_reported()
.assert_json(json!({"errors": {
"users": ["The users field must not have more than 1 items."],
"names.0": ["The names.0 field must not be greater than 5 characters."],
"names.1": ["The names.1 is unavailable."],
"names.3": ["The names.3 field must be a string."]
}}));
assert_eq!(
*calls.lock().unwrap(),
vec![
("names.1".into(), Some(InputValue::from("taken"))),
("names.2".into(), Some(InputValue::from("rust")))
]
);
}
struct Check {
calls: Calls,
implicit: bool,
}
impl ValidationRule for Check {
async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
tokio::task::yield_now().await;
self.calls
.lock()
.unwrap()
.push((field.name.to_owned(), field.value.cloned()));
Err(RuleError::invalid("Rejected."))
}
fn implicit(&self) -> bool {
self.implicit
}
}
#[tokio::test]
async fn implicit_async_rules_run_on_empty_input_and_bail_stops_later_implicit_rules() {
let calls = Calls::default();
let rules = Rules::new().nullable("name").field(
"name",
[
Rule::custom(Check {
calls: calls.clone(),
implicit: true,
}),
Rule::custom(Check {
calls: calls.clone(),
implicit: true,
}),
Rule::bail(),
],
);
for input in [json!({}), json!({"name":null}), json!({"name":""})] {
let error = rules.validate(input.as_object().unwrap()).await.unwrap_err();
assert_eq!(error.invalid().errors()["name"], ["Rejected."]);
}
assert_eq!(calls.lock().unwrap().len(), 3);
}
#[tokio::test]
async fn bail_semantics_match_classic_generated_cases() {
let fixtures: Vec<Value> = serde_json::from_str(include_str!("fixtures/validation-bail.json")).unwrap();
for fixture in fixtures {
let mut rules = Rules::new();
for (name, specification) in fixture["rules"].as_object().unwrap() {
let specification = specification.as_str().unwrap();
let entries: Vec<_> = specification
.split('|')
.filter_map(|rule| match rule {
"bail" => Some(Rule::bail()),
"required" => Some(Rule::required()),
"string" => Some(Rule::string()),
"max:2" => Some(Rule::max_length(2)),
"confirmed" => Some(Rule::confirmed()),
"nullable" | "array" => None,
_ => unreachable!("fixture rule"),
})
.collect();
rules = if name == "tags.*" {
rules.each_value("tags", entries)
} else {
rules.field(name, entries)
};
if specification.contains("nullable") {
rules = rules.nullable(name);
}
}
let error = rules.validate(fixture["input"].as_object().unwrap()).await.err();
let errors = error.as_ref().map(|error| error.invalid().clone()).unwrap_or_default();
assert_eq!(
serde_json::to_value(errors).unwrap(),
fixture["errors"],
"{}",
fixture["name"]
);
}
}
#[tokio::test]
async fn cancellation_drops_the_current_rule_and_never_starts_later_rules() {
use std::sync::atomic::{AtomicBool, Ordering};
use tokio::sync::Notify;
struct Waiting {
entered: Arc<Notify>,
dropped: Arc<AtomicBool>,
}
struct Guard(Arc<AtomicBool>);
impl Drop for Guard {
fn drop(&mut self) {
self.0.store(true, Ordering::SeqCst);
}
}
impl ValidationRule for Waiting {
async fn validate(&self, _: &Field<'_>) -> Result<(), RuleError> {
let _guard = Guard(self.dropped.clone());
self.entered.notify_one();
std::future::pending::<()>().await;
Ok(())
}
}
let entered = Arc::new(Notify::new());
let dropped = Arc::new(AtomicBool::new(false));
let calls = Calls::default();
let rules = Rules::new().field(
"name",
[
Rule::custom(Waiting {
entered: entered.clone(),
dropped: dropped.clone(),
}),
Rule::custom(Check {
calls: calls.clone(),
implicit: false,
}),
],
);
let input = json!({"name":"rust"});
tokio::time::timeout(std::time::Duration::from_secs(1), async {
tokio::select! {
_ = rules.validate(input.as_object().unwrap()) => panic!("the first rule should remain pending"),
_ = entered.notified() => {},
}
})
.await
.unwrap();
assert!(dropped.load(Ordering::SeqCst));
assert!(calls.lock().unwrap().is_empty());
}