use std::time::Duration;
use laravel::Application;
use laravel::config::Env;
use laravel::container::Container;
use laravel::foundation::ServiceProvider;
use laravel::testing::MakesHttpRequests;
use tower::ServiceExt;
struct Broken;
impl ServiceProvider for Broken {
async fn boot(&self, _app: &Container) -> laravel::Result<()> {
Err(laravel::abort_with(500, "the database is unreachable"))
}
}
fn app(providers: impl FnOnce(&mut laravel::foundation::Providers)) -> Application {
Application::configure()
.replace_env(Env::from_iter([
("APP_ENV", "production"),
("APP_URL", "https://example.com"),
]))
.with_providers(providers)
.with_routing(|routing, _| {
routing.health("/up");
})
.create()
}
#[tokio::test]
async fn health_checks_are_answered_once_the_app_is_up() {
let app = app(|_| {});
app.get("/up").await.assert_ok().assert_see("Application up");
app.request(http::Method::HEAD, "/up").await.assert_ok();
app.get("/up").header("host", "10.0.0.5:8000").await.assert_ok();
}
#[tokio::test]
async fn an_app_that_cant_boot_is_down() {
let app = app(|providers| {
providers.add(Broken);
});
let request = http::Request::get("/up")
.header("host", "example.com")
.body(laravel::axum::body::Body::empty())
.unwrap();
let response = app.into_router().oneshot(request).await.unwrap();
assert_eq!(response.status(), 503);
}
#[test]
fn the_server_is_configured_from_the_environment() {
let env = Env::from_iter([
("SERVER_HOST", "0.0.0.0"),
("SERVER_PORT", "8080"),
("SERVER_SHUTDOWN_TIMEOUT", "5"),
]);
let server = laravel::config::server::Server::from_env(&env);
assert_eq!(server.host, "0.0.0.0");
assert_eq!(server.port, 8080);
assert_eq!(server.shutdown_timeout, Duration::from_secs(5));
}
#[test]
fn invalid_ports_stop_the_application() {
let error = Application::configure()
.replace_env(Env::from_iter([("SERVER_PORT", "eighty")]))
.try_create()
.expect_err("the port should be invalid");
assert!(
error.to_string().contains("`SERVER_PORT` is set to `eighty`"),
"{error}"
);
}
async fn client_ip(env: &[(&str, &str)]) -> String {
let app = Application::configure()
.replace_env(env.iter().copied().collect())
.with_routing(|routing, _| {
routing.api(|route: &mut laravel::routing::Router| {
route.get("/ip", |request: laravel::http::Request| async move {
request.ip().to_string()
});
});
})
.create();
app.get("/api/ip")
.with_ip([10, 0, 0, 1])
.header("x-forwarded-for", "203.0.113.7")
.await
.text()
}
#[tokio::test]
async fn load_balancers_are_trusted_on_laravel_cloud() {
assert_eq!(client_ip(&[("APP_ENV", "local")]).await, "10.0.0.1");
assert_eq!(
client_ip(&[("APP_ENV", "local"), ("LARAVEL_CLOUD", "1")]).await,
"203.0.113.7"
);
}