use super::names::{STALE_AFTER, is_stale, name_at};
const NOW: u64 = 1_800_000_000;
#[test]
fn a_name_holds_the_time_it_was_made_and_its_random_part() {
assert_eq!(
name_at(0x6b49_d200, &[0xab, 0xcd]),
"vcon_t_6b49d200_abcd",
"the prefix, the seconds in hexadecimal, the random bytes"
);
}
#[test]
fn a_database_just_made_is_not_stale() {
assert!(!is_stale(&name_at(NOW, &[1]), NOW), "made this second");
assert!(
!is_stale(&name_at(NOW - 60, &[1]), NOW),
"a test a minute old may still run"
);
}
#[test]
fn a_database_older_than_the_limit_is_stale() {
assert!(
is_stale(&name_at(NOW - STALE_AFTER - 1, &[1]), NOW),
"one second past the limit"
);
assert!(is_stale(&name_at(1, &[1]), NOW), "from long ago");
}
#[test]
fn a_database_exactly_at_the_limit_is_kept() {
assert!(
!is_stale(&name_at(NOW - STALE_AFTER, &[1]), NOW),
"the limit itself is not past it"
);
}
#[test]
fn a_database_from_a_clock_ahead_of_this_one_is_kept() {
assert!(
!is_stale(&name_at(NOW + 3600, &[1]), NOW),
"a time in the future is not an age"
);
}
#[test]
fn a_database_that_is_not_a_tests_is_never_stale() {
for name in [
"vcon",
"postgres",
"template1",
"vcon_t",
"vcon_t_",
"vcon_test_1_ab",
"other_t_1_ab",
] {
assert!(!is_stale(name, NOW), "{name} is not swept");
}
}
#[test]
fn a_test_name_whose_time_does_not_parse_is_never_stale() {
for name in [
"vcon_t_zz_ab",
"vcon_t__ab",
"vcon_t_0123456789abcdef",
"vcon_t_ffffffffffffffffff_ab",
"vcon_t_-1_ab",
] {
assert!(!is_stale(name, NOW), "{name} is left alone");
}
}
#[test]
fn the_limit_is_longer_than_any_test_may_run() {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.config/nextest.toml");
let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
let line = text
.lines()
.find(|l| l.starts_with("slow-timeout = "))
.expect("the runner's deadline is set");
let number_after = |key: &str| -> u64 {
let rest = line.split(key).nth(1).expect("the key is there");
rest.trim_start_matches([' ', '=', '"'])
.chars()
.take_while(char::is_ascii_digit)
.collect::<String>()
.parse()
.unwrap_or_else(|e| panic!("{key} in {line}: {e}"))
};
let deadline = number_after("period") * number_after("terminate-after");
assert!(
STALE_AFTER >= 2 * deadline,
"the sweep's limit of {STALE_AFTER} s against a test's deadline of {deadline} s"
);
}
#[cfg(feature = "backend-tests")]
mod on_a_server {
use std::time::{SystemTime, UNIX_EPOCH};
use super::super::super::super::connect::Purpose;
use super::super::super::live::{as_user, value};
use super::super::live::{Db, connect, waiters};
use super::super::names::{STALE_AFTER, name_at};
async fn tester() -> tokio_postgres::Client {
let (_dir, settings) = as_user("vcon_tester");
connect(&settings, Purpose::Connect)
.await
.expect("the tester connects")
.client
}
async fn exists(client: &tokio_postgres::Client, name: &str) -> bool {
value(
client,
&format!("SELECT count(*) FROM pg_database WHERE datname = '{name}'"),
)
.await
== "1"
}
fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("after 1970")
.as_secs()
}
#[tokio::test]
async fn a_tests_database_is_there_while_the_test_runs_and_gone_when_it_ends() {
let tester = tester().await;
let db = Db::migrated().await;
let name = db.name.clone();
assert!(
exists(&tester, &name).await,
"there while the test holds it"
);
drop(db);
assert!(
!exists(&tester, &name).await,
"dropped with the test's guard"
);
}
#[test]
fn a_tests_database_is_gone_when_the_test_panics() {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("a runtime");
let named = std::sync::Mutex::new(String::new());
let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let db = runtime.block_on(Db::fresh());
named.lock().expect("the name").clone_from(&db.name);
assert!(
db.name.is_empty(),
"a test that fails while it holds a database"
);
}));
assert!(failed.is_err(), "the test inside failed");
let name = named.lock().expect("the name").clone();
assert!(
name.starts_with("vcon_t_"),
"it had made a database: {name}"
);
let gone = runtime.block_on(async { !exists(&tester().await, &name).await });
assert!(gone, "the guard dropped it while the panic unwound");
}
#[tokio::test]
async fn a_database_with_open_connections_is_dropped_all_the_same() {
let tester = tester().await;
let db = Db::migrated().await;
let name = db.name.clone();
let held = db.app().await;
drop(db);
assert!(
!exists(&tester, &name).await,
"dropped though a connection was open"
);
assert!(
held.simple_query("SELECT 1").await.is_err(),
"the connection that was open was ended by the drop"
);
}
#[tokio::test]
async fn a_new_database_sweeps_one_a_killed_test_left_and_keeps_a_running_tests() {
let tester = tester().await;
let random: [u8; 6] = aws_lc_rs::rand::generate(&aws_lc_rs::rand::SystemRandom::new())
.expect("random")
.expose();
let left = name_at(now() - STALE_AFTER - 60, &random);
let running = name_at(now(), &random);
for name in [&left, &running] {
tester
.batch_execute(&format!("CREATE DATABASE {name} OWNER vcon_owner"))
.await
.expect("a database made around the guard");
}
let db = Db::fresh().await;
assert!(
!exists(&tester, &left).await,
"the one older than the limit was swept"
);
assert!(
exists(&tester, &running).await,
"the one another test could be running on was kept"
);
tester
.batch_execute(&format!("DROP DATABASE {running} WITH (FORCE)"))
.await
.expect("this test removes what it made");
drop(db);
}
#[tokio::test]
async fn a_run_of_databases_leaves_none_behind() {
let tester = tester().await;
let mut names = Vec::new();
for _ in 0..4 {
let db = Db::fresh().await;
names.push(db.name.clone());
}
let listed = names
.iter()
.map(|n| format!("'{n}'"))
.collect::<Vec<_>>()
.join(", ");
assert_eq!(
value(
&tester,
&format!("SELECT count(*) FROM pg_database WHERE datname IN ({listed})")
)
.await,
"0",
"each was dropped when its guard went out of scope"
);
assert_eq!(
names
.iter()
.collect::<std::collections::BTreeSet<_>>()
.len(),
4,
"and each had a name of its own"
);
}
async fn within_five_seconds_of(
client: &tokio_postgres::Client,
sql: &str,
want: &str,
) -> bool {
for _ in 0..50 {
if value(client, sql).await == want {
return true;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
false
}
#[tokio::test]
async fn a_session_that_begins_to_wait_is_counted_by_a_transaction_already_open() {
let db = Db::fresh().await;
let holder = db.admin().await;
holder
.batch_execute("BEGIN; SELECT pg_advisory_xact_lock(7)")
.await
.expect("holds the lock in a transaction");
assert_eq!(
value(&holder, &waiters(Some("advisory"))).await,
"0",
"no session waits yet"
);
let waiter = db.admin().await;
let waiting = tokio::spawn(async move {
waiter
.batch_execute("BEGIN; SELECT pg_advisory_xact_lock(7); COMMIT")
.await
});
assert!(
within_five_seconds_of(&holder, &waiters(Some("advisory")), "1").await,
"the session that came after the transaction's first count"
);
holder.batch_execute("COMMIT").await.expect("commits");
waiting
.await
.expect("the task ends")
.expect("the waiter got the lock");
}
#[tokio::test]
async fn a_session_waiting_for_a_row_is_counted_and_is_not_an_advisory_wait() {
let (here, other) = (Db::fresh().await, Db::fresh().await);
let holder = here.admin().await;
holder
.batch_execute("CREATE TABLE held (n int); INSERT INTO held VALUES (1)")
.await
.expect("a table with a row");
holder
.batch_execute("BEGIN; SELECT n FROM held FOR UPDATE")
.await
.expect("holds the row");
let waiter = here.admin().await;
let waiting =
tokio::spawn(
async move { waiter.batch_execute("SELECT n FROM held FOR UPDATE").await },
);
let counting = here.admin().await;
assert!(
within_five_seconds_of(&counting, &waiters(None), "1").await,
"the session that waits for the row"
);
assert_eq!(
value(&counting, &waiters(Some("advisory"))).await,
"0",
"it waits for no advisory lock"
);
assert_eq!(
value(&other.admin().await, &waiters(None)).await,
"0",
"and another database counts none"
);
holder.batch_execute("COMMIT").await.expect("commits");
waiting
.await
.expect("the task ends")
.expect("the waiter got the row");
}
#[tokio::test]
async fn a_session_waiting_in_this_database_is_counted() {
let db = Db::fresh().await;
let holder = db.admin().await;
holder
.batch_execute("SELECT pg_advisory_lock(7)")
.await
.expect("holds the lock");
let waiter = db.admin().await;
let waiting =
tokio::spawn(async move { waiter.batch_execute("SELECT pg_advisory_lock(7)").await });
for kind in [Some("advisory"), None] {
assert!(
within_five_seconds_of(&holder, &waiters(kind), "1").await,
"the one session that waits, by {kind:?}"
);
}
assert_eq!(
value(&holder, &waiters(Some("tuple"))).await,
"0",
"no session waits for a lock of another kind"
);
holder
.batch_execute("SELECT pg_advisory_unlock(7)")
.await
.expect("gives the lock up");
waiting
.await
.expect("the task ends")
.expect("the waiter got the lock");
assert_eq!(
value(&holder, &waiters(None)).await,
"0",
"no session waits now"
);
}
#[tokio::test]
async fn a_session_waiting_in_another_database_is_not_counted() {
let (here, other) = (Db::fresh().await, Db::fresh().await);
let holder = other.admin().await;
holder
.batch_execute("SELECT pg_advisory_lock(7)")
.await
.expect("holds the lock");
let waiter = other.admin().await;
let waiting =
tokio::spawn(async move { waiter.batch_execute("SELECT pg_advisory_lock(7)").await });
assert!(
within_five_seconds_of(&holder, &waiters(Some("advisory")), "1").await,
"the other database has its one waiting session"
);
let mine = here.admin().await;
for kind in [Some("advisory"), None] {
assert_eq!(
value(&mine, &waiters(kind)).await,
"0",
"this database has none, by {kind:?}"
);
}
holder
.batch_execute("SELECT pg_advisory_unlock(7)")
.await
.expect("gives the lock up");
waiting
.await
.expect("the task ends")
.expect("the waiter got the lock");
}
}