use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use laravel::Application;
use laravel::auth::Authenticated;
use laravel::config::Env;
use laravel::db::{self, DatabaseManager};
use laravel::feature::{self, HasFeatures, ShareFeatures};
use laravel::foundation::ApplicationBuilder;
use laravel::http::Json;
use laravel::testing::{InteractsWithDatabase, MakesConsoleRequests, MakesHttpRequests};
use serde_json::json;
use crate::feature::{
ButtonColor, Customer, Member, configure, customer, new_api, purchase_button, resolutions, ticket,
};
fn app() -> Application {
app_on("sqlite::memory:")
}
fn app_on(url: &str) -> Application {
with_features_table(configure().with_envs([("FEATURE_STORE", "database"), ("DATABASE_URL", url)])).create()
}
fn with_features_table(app: ApplicationBuilder) -> ApplicationBuilder {
app.with_migrations(db::migrations!("tests/fixtures/migrations/features"))
.refresh_database()
}
async fn statement(app: &Application, sql: &'static str) -> laravel::Result<()> {
app.resolve::<DatabaseManager>()
.await
.default_connection()?
.query(sql)
.statement()
.await?;
Ok(())
}
#[tokio::test]
async fn values_are_rows_of_json_keyed_by_name_and_scope() -> laravel::Result<()> {
rows_contract(&app()).await
}
#[cfg(feature = "database-postgres")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database"]
async fn postgres_keeps_values_in_the_table() -> laravel::Result<()> {
let app = app_on(&std::env::var("LARAVEL_TEST_POSTGRES_URL")?);
rows_contract(&app).await?;
let checks = (1..=4).map(|_| app.scope(async || Member { id: 5 }.features().value(ticket).await));
let tickets = futures_util::future::try_join_all(checks).await?;
assert!(tickets.iter().all(|number| *number == tickets[0]), "{tickets:?}");
app.assert_database_count("features", 1).await;
Ok(())
}
async fn rows_contract(app: &Application) -> laravel::Result<()> {
let color = app
.scope(async || Member { id: 1 }.features().value(purchase_button).await)
.await?;
assert_eq!(color, Some(ButtonColor::SeafoamGreen));
app.assert_database_has(
"features",
json!({ "name": "purchase-button", "scope": "members|1", "value": "\"seafoam-green\"" }),
)
.await;
assert_eq!(
app.scope(async || Member { id: 1 }.features().value(purchase_button).await)
.await?,
color
);
assert_eq!(resolutions(app).await, 1);
app.scope(async || Member { id: 1 }.features().deactivate(purchase_button).await)
.await?;
app.assert_database_has("features", json!({ "scope": "members|1", "value": "false" }))
.await;
app.scope(async || {
Member { id: 1 }
.features()
.activate_with(purchase_button, ButtonColor::TartOrange)
.await
})
.await?;
app.assert_database_has("features", json!({ "scope": "members|1", "value": "\"tart-orange\"" }))
.await;
app.scope(async || Member { id: 1 }.features().forget(purchase_button).await)
.await?;
app.assert_database_empty("features").await;
Ok(())
}
#[tokio::test]
async fn a_stored_value_that_no_longer_decodes_is_resolved_again() -> laravel::Result<()> {
let app = app();
app.scope(async || Member { id: 1 }.features().value(purchase_button).await)
.await?;
statement(&app, "UPDATE features SET value = '\"magenta\"'").await?;
let color = app
.scope(async || Member { id: 1 }.features().value(purchase_button).await)
.await?;
assert_eq!(color, Some(ButtonColor::SeafoamGreen));
assert_eq!(resolutions(&app).await, 2);
app.assert_database_has(
"features",
json!({ "scope": "members|1", "value": "\"seafoam-green\"" }),
)
.await;
app.assert_database_count("features", 1).await;
Ok(())
}
#[tokio::test]
async fn everyone_updates_stored_rows_and_forget_deletes_them() -> laravel::Result<()> {
let app = app();
for id in [1, 2] {
app.scope(async || Member { id }.features().value(purchase_button).await)
.await?;
}
app.scope(async || {
feature::everyone()
.activate_with(purchase_button, ButtonColor::BlueSapphire)
.await
})
.await?;
for scope in ["members|1", "members|2"] {
app.assert_database_has("features", json!({ "scope": scope, "value": "\"blue-sapphire\"" }))
.await;
}
app.assert_database_count("features", 2).await;
assert_eq!(
app.scope(async || Member { id: 2 }.features().value(purchase_button).await)
.await?,
Some(ButtonColor::BlueSapphire)
);
app.scope(async || feature::everyone().forget(purchase_button).await)
.await?;
app.assert_database_empty("features").await;
Ok(())
}
#[tokio::test]
async fn purge_keeps_defined_features_with_except_defined() -> laravel::Result<()> {
let app = app();
app.scope(async || Member { id: 2 }.features().active(new_api).await)
.await?;
statement(
&app,
"INSERT INTO features (name, scope, value) VALUES ('retired', 'members|2', 'true')",
)
.await?;
statement(
&app,
"INSERT INTO features (name, scope, value) VALUES ('removed', 'members|2', 'true')",
)
.await?;
let purged = app.command("feature:purge removed").await;
purged
.assert_successful()
.assert_error_output_contains("Feature `removed` purged.");
assert!(
!purged.error_output().contains("isn't defined"),
"{}",
purged.error_output()
);
app.command("feature:purge --except-defined")
.await
.assert_successful()
.assert_error_output_contains("Feature `retired` purged.");
app.assert_database_missing("features", json!({ "name": "retired" }))
.await;
app.assert_database_has("features", json!({ "name": "new_api" })).await;
Ok(())
}
#[tokio::test]
async fn users_are_stored_under_their_type_name_and_id() {
let app = app();
app.get("/early-access")
.acting_as(&customer(1))
.await
.assert_see("true");
app.assert_database_has(
"features",
json!({ "name": "early_access", "scope": "Customer|1", "value": "true" }),
)
.await;
}
async fn shared_features(
Authenticated(customer): Authenticated<Customer>,
) -> laravel::Result<Json<serde_json::Map<String, serde_json::Value>>> {
Ok(Json(customer.features().all().await?))
}
#[tokio::test]
async fn share_features_reads_every_stored_value_with_one_query() -> laravel::Result<()> {
let app = with_features_table(
configure()
.with_envs([("FEATURE_STORE", "database"), ("DATABASE_URL", "sqlite::memory:")])
.with_middleware(|middleware, _| {
middleware.web(|web| {
web.append(ShareFeatures::<Customer>::new());
});
})
.with_routing(|routing, _| {
routing.web(|route| {
route.get("/shared-features", shared_features);
});
}),
)
.create();
let reads = Arc::new(AtomicUsize::new(0));
let counted = Arc::clone(&reads);
app.scope(async || {
db::listen(move |query| {
if query.sql.starts_with("select") && query.sql.contains("from `features`") {
counted.fetch_add(1, Ordering::SeqCst);
}
});
})
.await;
let expected = json!({ "checkout-color": "tart-orange", "early_access": true, "welcome_tour": false });
app.get("/shared-features")
.acting_as(&customer(1))
.await
.assert_exact_json(&expected);
assert_eq!(reads.load(Ordering::SeqCst), 1, "misses resolve after one read");
for (name, scope) in [
("checkout-color", "Customer|1"),
("early_access", "Customer|1"),
("welcome_tour", "Customer|1"),
("maintenance_banner", "__laravel_global"),
("read_only", "__laravel_global"),
] {
app.assert_database_has("features", json!({ "name": name, "scope": scope }))
.await;
}
let resolved = resolutions(&app).await;
app.get("/shared-features")
.acting_as(&customer(1))
.await
.assert_exact_json(&expected);
assert_eq!(reads.load(Ordering::SeqCst), 2, "stored values take one read");
assert_eq!(resolutions(&app).await, resolved, "stored values don't resolve again");
Ok(())
}
fn without_feature_store() -> Env {
Env::from_iter([
("APP_ENV", "testing"),
("APP_BASE_PATH", env!("CARGO_MANIFEST_DIR")),
("DATABASE_URL", "sqlite::memory:"),
])
}
#[tokio::test]
async fn the_database_store_is_the_default() -> laravel::Result<()> {
let app = with_features_table(configure().replace_env(without_feature_store())).create();
app.scope(async || Member { id: 2 }.features().active(new_api).await)
.await?;
app.assert_database_has("features", json!({ "name": "new_api", "scope": "members|2" }))
.await;
Ok(())
}
#[tokio::test]
async fn a_missing_features_table_fails_the_first_check_not_the_boot() -> laravel::Result<()> {
let app = configure().replace_env(without_feature_store()).create();
app.boot().await?;
let error = app
.scope(async || Member { id: 2 }.features().active(new_api).await)
.await
.unwrap_err();
assert!(format!("{error:?}").contains("no such table: features"), "{error:?}");
Ok(())
}
#[cfg(feature = "database-mysql")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_MYSQL_URL pointing to a disposable InnoDB database"]
async fn mysql_reads_a_value_stored_after_the_transaction_began() -> laravel::Result<()> {
let url = std::env::var("LARAVEL_TEST_MYSQL_URL")?;
let app = configure()
.with_envs([("FEATURE_STORE", "database"), ("DATABASE_URL", url.as_str())])
.create();
statement(&app, "DROP TABLE IF EXISTS features").await?;
statement(
&app,
"CREATE TABLE features (name VARCHAR(255), scope VARCHAR(255), value TEXT, created_at BIGINT, \
updated_at BIGINT, UNIQUE (name, scope)) ENGINE=InnoDB",
)
.await?;
let inside = app
.scope(async || {
db::transaction(async |_| {
db::table("features").count().await?;
let another_request = app.clone();
tokio::spawn(async move {
another_request
.scope(async || Member { id: 7 }.features().value(ticket).await)
.await
})
.await
.expect("the other request finishes")?;
Member { id: 7 }.features().value(ticket).await
})
.await
})
.await;
statement(&app, "DROP TABLE features").await?;
assert_eq!(inside?, Some(1));
Ok(())
}