Skip to content

Commit df04f2b

Browse files
Ian Oberstclaude
andcommitted
test(buzz-db): cover scratch role cleanup and finish every cleanup step
Address review on the scratch schema guard: - The panic regression test now also creates a `{name}_reader` role with a schema grant and asserts no `{name}_*` role survives, so role cleanup is covered now that the per-test DROP ROLE is gone. - drop_scratch_objects runs every step and returns all failures joined, instead of returning at the first `?` and skipping remaining sibling schemas and roles. - Document that the guard must be bound to a named variable, since `let (pool, _) = scratch_pool().await` drops it immediately. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Ian Oberst <[email protected]>
1 parent b5e29a1 commit df04f2b

1 file changed

Lines changed: 76 additions & 21 deletions

File tree

‎crates/buzz-db/src/store/partition.rs‎

Lines changed: 76 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1802,6 +1802,10 @@ mod tests {
18021802
///
18031803
/// Cleanup also drops every schema and role named `{name}_*`, so a test
18041804
/// that needs extra schemas or roles derives their names from `name`.
1805+
///
1806+
/// Bind the guard to a named variable such as `_scratch` for the whole
1807+
/// test: `let (pool, _) = scratch_pool().await` drops it, and the
1808+
/// schema with it, immediately.
18051809
pub(in crate::store::partition) struct ScratchSchema {
18061810
pub(in crate::store::partition) admin: PgPool,
18071811
pub(in crate::store::partition) name: String,
@@ -1828,7 +1832,6 @@ mod tests {
18281832
.build()
18291833
.map_err(|error| error.to_string())?
18301834
.block_on(drop_scratch_objects(&url, &name, &backends))
1831-
.map_err(|error| error.to_string())
18321835
})
18331836
.join();
18341837
let error = match cleanup {
@@ -1843,50 +1846,85 @@ mod tests {
18431846
}
18441847
}
18451848

1846-
async fn drop_scratch_objects(url: &str, name: &str, backends: &[i32]) -> sqlx::Result<()> {
1847-
let mut connection = PgConnection::connect(url).await?;
1848-
sqlx::query("SET lock_timeout = '10s'")
1849+
async fn drop_scratch_objects(
1850+
url: &str,
1851+
name: &str,
1852+
backends: &[i32],
1853+
) -> std::result::Result<(), String> {
1854+
let mut connection = PgConnection::connect(url)
1855+
.await
1856+
.map_err(|error| error.to_string())?;
1857+
// Every step is idempotent, so keep going after a failure and
1858+
// report all of them rather than skipping the remaining objects.
1859+
let mut errors = Vec::new();
1860+
let mut record = |step: &str, result: sqlx::Result<()>| {
1861+
if let Err(error) = result {
1862+
errors.push(format!("{step}: {error}"));
1863+
}
1864+
};
1865+
let result = sqlx::query("SET lock_timeout = '10s'")
18491866
.execute(&mut connection)
1850-
.await?;
1867+
.await
1868+
.map(drop);
1869+
record("set lock_timeout", result);
18511870
// A panicking test can leave a transaction holding locks in the
18521871
// schema; its rollback would only run on the blocked test runtime.
1853-
sqlx::query(
1872+
let result = sqlx::query(
18541873
"SELECT pg_terminate_backend(pid, 5000) FROM pg_stat_activity \
18551874
WHERE pid = ANY($1) AND datname = current_database()",
18561875
)
18571876
.bind(backends)
18581877
.execute(&mut connection)
1859-
.await?;
1878+
.await
1879+
.map(drop);
1880+
record("terminate test backends", result);
18601881
let schemas: Vec<String> = sqlx::query_scalar(
18611882
"SELECT nspname::text FROM pg_namespace \
18621883
WHERE nspname = $1 OR starts_with(nspname, $1 || '_')",
18631884
)
18641885
.bind(name)
18651886
.fetch_all(&mut connection)
1866-
.await?;
1887+
.await
1888+
.unwrap_or_else(|error| {
1889+
record("list schemas", Err(error));
1890+
Vec::new()
1891+
});
18671892
for schema in schemas {
1868-
sqlx::query(sqlx::AssertSqlSafe(format!(
1893+
let result = sqlx::query(sqlx::AssertSqlSafe(format!(
18691894
"DROP SCHEMA IF EXISTS {} CASCADE",
18701895
quote_identifier(&schema)
18711896
)))
18721897
.execute(&mut connection)
1873-
.await?;
1898+
.await
1899+
.map(drop);
1900+
record(&format!("drop schema {schema}"), result);
18741901
}
18751902
let roles: Vec<String> = sqlx::query_scalar(
18761903
"SELECT rolname::text FROM pg_roles WHERE starts_with(rolname, $1 || '_')",
18771904
)
18781905
.bind(name)
18791906
.fetch_all(&mut connection)
1880-
.await?;
1907+
.await
1908+
.unwrap_or_else(|error| {
1909+
record("list roles", Err(error));
1910+
Vec::new()
1911+
});
18811912
for role in roles {
1882-
sqlx::query(sqlx::AssertSqlSafe(format!(
1913+
let result = sqlx::query(sqlx::AssertSqlSafe(format!(
18831914
"DROP ROLE IF EXISTS {}",
18841915
quote_identifier(&role)
18851916
)))
18861917
.execute(&mut connection)
1887-
.await?;
1918+
.await
1919+
.map(drop);
1920+
record(&format!("drop role {role}"), result);
1921+
}
1922+
record("close connection", connection.close().await);
1923+
if errors.is_empty() {
1924+
Ok(())
1925+
} else {
1926+
Err(errors.join("; "))
18881927
}
1889-
connection.close().await
18901928
}
18911929

18921930
/// Pool options that record each connection's backend pid in `backends`
@@ -1916,6 +1954,8 @@ mod tests {
19161954
})
19171955
}
19181956

1957+
/// A pool whose `search_path` is a fresh scratch schema, plus the guard
1958+
/// that drops it. Bind the guard to a named variable, never `_`.
19191959
pub(in crate::store::partition) async fn scratch_pool() -> (PgPool, ScratchSchema) {
19201960
scratch_pool_with_max_connections(4).await
19211961
}
@@ -2139,6 +2179,15 @@ mod tests {
21392179
.execute(&scratch.admin)
21402180
.await
21412181
.expect("create sibling schema");
2182+
for statement in [
2183+
format!("CREATE ROLE {}_reader NOLOGIN", scratch.name),
2184+
format!("GRANT USAGE ON SCHEMA {0} TO {0}_reader", scratch.name),
2185+
] {
2186+
sqlx::query(sqlx::AssertSqlSafe(statement))
2187+
.execute(&scratch.admin)
2188+
.await
2189+
.expect("create scratch role");
2190+
}
21422191
let mut holder = pool.begin().await.expect("begin lock holder");
21432192
sqlx::query("LOCK TABLE events IN ACCESS EXCLUSIVE MODE")
21442193
.execute(&mut *holder)
@@ -2154,23 +2203,29 @@ mod tests {
21542203
assert!(outcome.is_err(), "the scratch test body must panic");
21552204
let name = name_receiver.recv().expect("scratch schema name");
21562205

2157-
let leftovers: Vec<String> = runtime().block_on(async {
2206+
let (schemas, roles): (Vec<String>, Vec<String>) = runtime().block_on(async {
21582207
let mut connection = PgConnection::connect(&crate::test_support::database_url())
21592208
.await
21602209
.expect("connect leftover check");
2161-
sqlx::query_scalar(
2210+
let schemas = sqlx::query_scalar(
21622211
"SELECT nspname::text FROM pg_namespace \
21632212
WHERE nspname = $1 OR starts_with(nspname, $1 || '_')",
21642213
)
21652214
.bind(&name)
21662215
.fetch_all(&mut connection)
21672216
.await
2168-
.expect("list leftover schemas")
2217+
.expect("list leftover schemas");
2218+
let roles = sqlx::query_scalar(
2219+
"SELECT rolname::text FROM pg_roles WHERE starts_with(rolname, $1 || '_')",
2220+
)
2221+
.bind(&name)
2222+
.fetch_all(&mut connection)
2223+
.await
2224+
.expect("list leftover roles");
2225+
(schemas, roles)
21692226
});
2170-
assert!(
2171-
leftovers.is_empty(),
2172-
"leaked scratch schemas: {leftovers:?}"
2173-
);
2227+
assert!(schemas.is_empty(), "leaked scratch schemas: {schemas:?}");
2228+
assert!(roles.is_empty(), "leaked scratch roles: {roles:?}");
21742229
}
21752230

21762231
#[tokio::test]

0 commit comments

Comments
 (0)