#![cfg(feature = "testing")]
use capy_framework::{
self as capy,
migration::{MigrationTrait, MigratorTrait, SchemaManager},
prelude::*,
sea_orm::{ConnectionTrait, Statement, TransactionTrait},
testing::{Factory, FactoryBuilder, TestApp, TestDatabase},
};
struct Migrator;
#[capy::migration::async_trait::async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![Box::new(Records)]
}
}
struct Records;
impl capy::migration::MigrationName for Records {
fn name(&self) -> &str {
"test_records"
}
}
#[capy::migration::async_trait::async_trait]
impl MigrationTrait for Records {
async fn up(&self, manager: &SchemaManager) -> std::result::Result<(), capy::sea_orm::DbErr> {
manager
.get_connection()
.execute_unprepared("CREATE TABLE records (id BIGINT PRIMARY KEY, title TEXT NOT NULL)")
.await?;
Ok(())
}
async fn down(&self, manager: &SchemaManager) -> std::result::Result<(), capy::sea_orm::DbErr> {
manager
.get_connection()
.execute_unprepared("DROP TABLE records")
.await?;
Ok(())
}
}
#[derive(Default)]
struct RecordFactory {
id: i64,
title: String,
}
impl Factory for RecordFactory {
type Model = i64;
async fn create<C: ConnectionTrait>(self, db: &C) -> Result<i64> {
db.execute(Statement::from_sql_and_values(
db.get_database_backend(),
"INSERT INTO records (id,title) VALUES ($1,$2)",
[self.id.into(), self.title.into()],
))
.await?;
Ok(self.id)
}
}
async fn count(Context(ctx): Context) -> Result<Json<Value>> {
let row = ctx
.db
.query_one(Statement::from_string(
ctx.db.get_database_backend(),
"SELECT COUNT(*) AS n FROM records",
))
.await?
.unwrap();
Ok(Json(json!({"count":row.try_get::<i64>("", "n")?})))
}
fn application() -> App<Migrator> {
App::new()
.config(AppConfig::default())
.api_routes(Routes::new().get("/records", count))
.migrations(Migrator)
}
#[tokio::test]
async fn boot_migrates_real_factory_and_isolates_concurrent_apps() -> Result<()> {
let (a, b) = tokio::try_join!(TestApp::boot(application()), TestApp::boot(application()))?;
a.factory::<RecordFactory>()
.with(|record| {
record.id = 1;
record.title = "First".into();
})
.create()
.await?;
a.get("/api/records")
.send()
.await
.assert_json(json!({"count":1}));
b.get("/api/records")
.send()
.await
.assert_json(json!({"count":0}));
assert_eq!(a.context().config.app.environment, "test");
let tx = a.db().begin().await?;
FactoryBuilder::new(
RecordFactory {
id: 2,
title: "Rolled back".into(),
},
&tx,
)
.create()
.await?;
tx.rollback().await?;
a.get("/api/records")
.send()
.await
.assert_json(json!({"count":1}));
let closed = a.db().clone();
a.cleanup().await?;
assert!(closed.ping().await.is_err());
b.cleanup().await?;
Ok(())
}
#[tokio::test]
async fn missing_migrations_remain_observable() -> Result<()> {
let app = TestApp::builder(application())
.without_migrations()
.boot()
.await?;
app.get("/api/records")
.send()
.await
.assert_status(axum::http::StatusCode::INTERNAL_SERVER_ERROR)
.assert_json(json!({"message":"Internal server error"}));
app.cleanup().await
}
#[tokio::test]
async fn seeds_are_explicit_atomic_and_reusable_in_application_tests() -> Result<()> {
let app = TestApp::boot(application().seeds(|ctx| {
Box::pin(async move {
ctx.transaction
.execute(Statement::from_sql_and_values(
ctx.transaction.get_database_backend(),
"INSERT INTO records (id,title) VALUES ($1,$2) ON CONFLICT (id) DO NOTHING",
[1_i64.into(), "Seeded".into()],
))
.await?;
Ok(())
})
}))
.await?;
app.get("/api/records")
.send()
.await
.assert_json(json!({"count":0}));
app.seed().await?;
app.seed().await?;
app.get("/api/records")
.send()
.await
.assert_json(json!({"count":1}));
app.cleanup().await?;
let app = TestApp::boot(application().seeds(|ctx| {
Box::pin(async move {
FactoryBuilder::new(RecordFactory::default(), ctx.transaction)
.create()
.await?;
Err(AppError::Conflict("deliberate seed failure".into()))
})
}))
.await?;
assert!(app.seed().await.is_err());
app.get("/api/records")
.send()
.await
.assert_json(json!({"count":0}));
app.cleanup().await
}
#[tokio::test]
async fn production_seed_command_rejects_before_connecting_or_running_callback() {
let mut config = AppConfig::default();
config.app.environment = "production".into();
config.database.url = "postgres://never-connect@127.0.0.1:1/production".into();
let error = App::new()
.config(config)
.seeds(|_| Box::pin(async { panic!("production seeds must not execute") }))
.run_command("db:seed")
.await
.unwrap_err();
assert!(error
.to_string()
.contains("disabled outside development/test"));
}
#[tokio::test]
async fn session_uses_configured_peer_and_rejects_cross_origin_paths() -> Result<()> {
async fn peer(
axum::extract::ConnectInfo(peer): axum::extract::ConnectInfo<std::net::SocketAddr>,
) -> Json<String> {
Json(peer.ip().to_string())
}
let app = TestApp::builder(
App::new()
.config(AppConfig::default())
.api_routes(Routes::new().get("/peer", peer)),
)
.peer_addr(([192, 0, 2, 10], 12345).into())
.boot()
.await?;
let mut session = app.session();
session
.get("/api/peer")
.send()
.await?
.assert_json(json!("192.0.2.10"));
assert!(session
.get("https://elsewhere.example/api/peer")
.send()
.await
.is_err());
assert!(session
.get("//elsewhere.example/api/peer")
.send()
.await
.is_err());
app.cleanup().await
}
#[tokio::test]
#[ignore = "requires CAPY_TEST_ADMIN_POSTGRES_URL with CREATEDB permission"]
async fn postgres_harness_provisions_and_removes_only_its_unique_database() -> Result<()> {
let url =
std::env::var("CAPY_TEST_ADMIN_POSTGRES_URL").expect("disposable PostgreSQL admin URL");
let mut config = AppConfig::default();
config.database.url = url.clone();
let admin = capy::db::connect(&config.database).await?;
let admin_name: String = admin
.query_one(Statement::from_string(
admin.get_database_backend(),
"SELECT current_database() AS name",
))
.await?
.unwrap()
.try_get("", "name")?;
let separator = if url.contains('?') { '&' } else { '?' };
let override_url =
format!("{url}{separator}dbname={admin_name}&application_name=capy-isolation-test");
let (a, b) = tokio::try_join!(
TestApp::builder(application())
.database(TestDatabase::Postgres(override_url))
.boot(),
TestApp::builder(application())
.database(TestDatabase::Postgres(url.clone()))
.boot()
)?;
let db_a: String = a
.db()
.query_one(Statement::from_string(
a.db().get_database_backend(),
"SELECT current_database() AS name",
))
.await?
.unwrap()
.try_get("", "name")?;
assert_ne!(db_a, admin_name);
assert!(db_a.starts_with("capy_test_"));
assert!(a
.context()
.config
.database
.url
.contains("application_name=capy-isolation-test"));
assert_ne!(
a.context().config.database.url,
b.context().config.database.url
);
a.factory::<RecordFactory>().create().await?;
b.get("/api/records")
.send()
.await
.assert_json(json!({"count":0}));
a.cleanup().await?;
b.cleanup().await?;
let row = admin
.query_one(Statement::from_sql_and_values(
admin.get_database_backend(),
"SELECT datname FROM pg_database WHERE datname=$1",
[db_a.into()],
))
.await?;
assert!(row.is_none(), "cleanup must drop its disposable database");
admin.close().await?;
Ok(())
}
#[cfg(all(feature = "auth", feature = "jobs", feature = "mail"))]
mod authenticated {
use super::*;
use capy::{
auth::{AuthUser, MemoryResetDelivery},
mail::{Mail, MailContext, MailResult, Mailable, QueueableMail},
};
struct AuthMigrator;
#[capy::migration::async_trait::async_trait]
impl MigratorTrait for AuthMigrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![
Box::new(capy::auth::migration::IdentityMigration),
Box::new(capy::jobs::migration::JobsMigration),
]
}
}
struct Welcome;
impl Mailable for Welcome {
const NAME: &'static str = "test.welcome";
fn render(&self) -> MailResult<Mail> {
Ok(Mail::new("Welcome").text("Ready to read"))
}
}
impl QueueableMail for Welcome {}
async fn protected(AuthUser(user): AuthUser) -> Result<Json<Value>> {
if user.email.starts_with("blocked") {
return Err(AppError::Forbidden);
}
Ok(Json(json!({"email": user.email})))
}
async fn send_mail(
AuthUser(user): AuthUser,
Context(ctx): Context,
MailContext(mail): MailContext,
) -> Result<NoContent> {
mail.queue(&ctx, Welcome.to(&user.email)?).await?;
Ok(NoContent)
}
fn factory(reset: MemoryResetDelivery) -> App<AuthMigrator> {
App::new()
.config(AppConfig::default())
.auth(reset)
.mail()
.api_routes(
Routes::new()
.post("/protected", protected)
.post("/welcome", send_mail),
)
.migrations(AuthMigrator)
}
#[tokio::test]
async fn sessions_rotate_csrf_login_logout_and_preserve_authorization() -> Result<()> {
let app = TestApp::boot(factory(MemoryResetDelivery::default())).await?;
let mut guest = app.session();
guest
.post("/api/protected")
.send()
.await?
.assert_status(axum::http::StatusCode::UNAUTHORIZED);
guest.post("/api/auth/register").without_csrf().json(json!({"name":"Reader", "email":"reader@example.test", "password":"correct horse battery staple"})).send().await?.assert_status(axum::http::StatusCode::FORBIDDEN);
guest.post("/api/auth/register").json(json!({"name":"Reader", "email":"reader@example.test", "password":"correct horse battery staple"})).send().await?.assert_created();
guest
.post("/api/protected")
.send()
.await?
.assert_ok()
.assert_json(json!({"email":"reader@example.test"}));
guest.logout().await?.assert_no_content();
guest
.get("/api/auth/me")
.send()
.await?
.assert_status(axum::http::StatusCode::UNAUTHORIZED);
guest
.login("reader@example.test", "wrong password")
.await?
.assert_status(axum::http::StatusCode::UNAUTHORIZED);
guest
.login("reader@example.test", "correct horse battery staple")
.await?
.assert_ok();
guest.post("/api/protected").send().await?.assert_ok();
let mut other = app.session();
other.post("/api/auth/register").json(json!({"name":"Blocked", "email":"blocked@example.test", "password":"correct horse battery staple"})).send().await?.assert_created();
other
.post("/api/protected")
.send()
.await?
.assert_status(axum::http::StatusCode::FORBIDDEN);
app.cleanup().await
}
#[tokio::test]
async fn reset_revokes_sessions_and_helpers_never_bypass_password_verification() -> Result<()> {
let reset = MemoryResetDelivery::default();
let app = TestApp::boot(factory(reset.clone())).await?;
let mut user = app.session();
user.post("/api/auth/register").json(json!({"name":"Reader", "email":"reader@example.test", "password":"correct horse battery staple"})).send().await?.assert_created();
let mut second = app
.login("reader@example.test", "correct horse battery staple")
.await?;
assert!(app
.login("reader@example.test", "wrong password")
.await
.is_err());
let mut anonymous = app.session();
anonymous
.post("/api/auth/forgot-password")
.json(json!({"email":"reader@example.test"}))
.send()
.await?
.assert_ok();
let token = reset.take().remove(0).token;
anonymous
.post("/api/auth/reset-password")
.json(json!({"token":token.expose(), "password":"a different long password"}))
.send()
.await?
.assert_no_content();
user.get("/api/auth/me")
.send()
.await?
.assert_status(axum::http::StatusCode::UNAUTHORIZED);
second
.get("/api/auth/me")
.send()
.await?
.assert_status(axum::http::StatusCode::UNAUTHORIZED);
app.login("reader@example.test", "a different long password")
.await?
.get("/api/auth/me")
.send()
.await?
.assert_ok();
app.cleanup().await
}
#[tokio::test]
async fn jobs_use_the_real_mail_handler_and_explicit_capture() -> Result<()> {
let app = TestApp::builder(factory(MemoryResetDelivery::default()))
.capture_mail()
.boot()
.await?;
let mut user = app.session();
user.post("/api/auth/register").json(json!({"name":"Reader", "email":"reader@example.test", "password":"correct horse battery staple"})).send().await?.assert_created();
user.post("/api/welcome").send().await?.assert_no_content();
assert!(app.mail().sent().is_empty());
assert_eq!(app.jobs().clone().on_queue("mail")?.drain(10).await?, 1);
app.mail().assert_sent_to("reader@example.test");
app.mail().assert_subject("Welcome");
assert_eq!(app.mail().sent().len(), 1);
app.cleanup().await
}
}