use std::io::Write;
fn migrations_dir() -> tempfile::TempDir {
let dir = tempfile::tempdir().unwrap();
let mut f = std::fs::File::create(dir.path().join("0001_create_widgets.sql")).unwrap();
write!(
f,
"CREATE TABLE widgets (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL UNIQUE);"
)
.unwrap();
dir
}
async fn widget_count(pool: &sqlx::AnyPool) -> i64 {
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM widgets")
.fetch_one(pool)
.await
.unwrap();
count
}
#[tokio::test]
async fn each_call_gets_its_own_isolated_database_even_reusing_the_same_unique_value() {
let dir = migrations_dir();
let seen_during = larust_testing::test_transaction(dir.path(), |pool| async move {
sqlx::query("INSERT INTO widgets (name) VALUES (?)")
.bind("gadget")
.execute(&pool)
.await
.unwrap();
widget_count(&pool).await
})
.await;
assert_eq!(seen_during, 1);
let seen_in_second_call = larust_testing::test_transaction(dir.path(), |pool| async move {
sqlx::query("INSERT INTO widgets (name) VALUES (?)")
.bind("gadget")
.execute(&pool)
.await
.unwrap();
widget_count(&pool).await
})
.await;
assert_eq!(
seen_in_second_call, 1,
"the second call's own insert should be the only row it ever sees - \
a UNIQUE-constraint error here would mean it shared the first call's database"
);
}
#[tokio::test]
async fn a_second_independent_test_in_the_same_file_is_unaffected_by_the_other() {
let dir = migrations_dir();
let count = larust_testing::test_transaction(dir.path(), |pool| async move {
sqlx::query("INSERT INTO widgets (name) VALUES (?)")
.bind("widget-from-a-different-test-fn")
.execute(&pool)
.await
.unwrap();
widget_count(&pool).await
})
.await;
assert_eq!(count, 1);
}