Skip to content

Commit 097598c

Browse files
committed
refactor(database): share the tests' connection, account and session fixtures
Database::test, UserRepository::insert_named, InsertSession::lasting and EventRepository::known_history join InsertUser::named in a test-util fixtures module, with a test_channels! macro for channels whose deliveries tests insert themselves. The crate's tests, integration tests included, use them instead of their own copies.
1 parent 467e813 commit 097598c

24 files changed

Lines changed: 306 additions & 352 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/database/Cargo.toml‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,12 @@ uuid.workspace = true
2525
[dev-dependencies]
2626
# The schema's skeleton test compares `handle_skeleton` with `Handle::skeleton`.
2727
sourceorigin-common = { workspace = true, features = ["similarity"] }
28+
# The integration tests under `tests/` start from the fixtures.
29+
sourceorigin-repository = { workspace = true, features = ["test-util"] }
2830

2931
[features]
30-
# Helpers that let other crates' tests observe stored state, and move a
31-
# recovery's clock.
32+
# Helpers that let other crates' tests observe stored state and move a
33+
# recovery's clock, and the fixtures tests start from.
3234
test-util = []
3335

3436
[lints]

‎crates/database/src/connection/mod.rs‎

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -390,16 +390,10 @@ impl Database {
390390

391391
#[cfg(test)]
392392
impl Database {
393-
/// Connects to `TEST_DATABASE_URL` and applies the schema. In-crate database
394-
/// tests get the raw pool so they can insert fixtures with plain SQL.
393+
/// [`Self::test`]'s pool. In-crate database tests get the raw pool so they
394+
/// can insert fixtures with plain SQL.
395395
pub(crate) async fn test_pool() -> PgPool {
396-
let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL");
397-
let pool = PgPool::connect(&url).await.expect("connect");
398-
Self { pool: pool.clone() }
399-
.run_migrations()
400-
.await
401-
.expect("migrate");
402-
pool
396+
Self::test().await.pool
403397
}
404398

405399
/// The server process of `connection`, to watch its lock waits with

‎crates/database/src/connection/tests.rs‎

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -284,9 +284,7 @@ fn runtime_roles_need_plain_names() {
284284
#[tokio::test]
285285
#[ignore = "requires a disposable TEST_DATABASE_URL"]
286286
async fn runtime_role_has_only_row_privileges() {
287-
let owner = Database {
288-
pool: Database::test_pool().await,
289-
};
287+
let owner = Database::test().await;
290288
let name = format!("sourceorigin_auth_{}", uuid::Uuid::now_v7().simple());
291289
let config = config_for(&name);
292290
let role = RuntimeRole::new(&config, "runtime password").expect("role");
@@ -404,9 +402,7 @@ fn config_for(user: &str) -> DatabaseConfig {
404402
#[tokio::test]
405403
#[ignore = "requires a disposable TEST_DATABASE_URL"]
406404
async fn provisioning_resets_what_it_does_not_grant() {
407-
let owner = Database {
408-
pool: Database::test_pool().await,
409-
};
405+
let owner = Database::test().await;
410406
let name = format!("sourceorigin_auth_{}", uuid::Uuid::now_v7().simple());
411407
let role = RuntimeRole::new(&config_for(&name), "password").expect("role");
412408
owner.provision(&role).await.expect("create");
@@ -449,9 +445,7 @@ async fn provisioning_resets_what_it_does_not_grant() {
449445
#[tokio::test]
450446
#[ignore = "requires a disposable TEST_DATABASE_URL"]
451447
async fn provisioning_refuses_roles_that_could_do_more() {
452-
let owner = Database {
453-
pool: Database::test_pool().await,
454-
};
448+
let owner = Database::test().await;
455449
let owner_name = sqlx::query_scalar::<_, String>("SELECT current_user::text")
456450
.fetch_one(&owner.pool)
457451
.await

‎crates/database/src/exclusive/tests.rs‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,7 @@ use std::time::Duration;
1010
#[tokio::test]
1111
#[ignore = "requires a disposable TEST_DATABASE_URL"]
1212
async fn locks_exclude_other_sessions_until_their_connection_ends() {
13-
let database = Database {
14-
pool: Database::test_pool().await,
15-
};
13+
let database = Database::test().await;
1614
let lock = || database.try_exclusive(LockKey::LockTest);
1715
let holder = lock().await.expect("lock").expect("a free lock");
1816
assert!(lock().await.expect("lock").is_none(), "the lock is held");
@@ -42,9 +40,7 @@ async fn locks_exclude_other_sessions_until_their_connection_ends() {
4240
#[tokio::test]
4341
#[ignore = "requires a disposable TEST_DATABASE_URL"]
4442
async fn locked_transactions_read_committed_data() {
45-
let database = Database {
46-
pool: Database::test_pool().await,
47-
};
43+
let database = Database::test().await;
4844
let mut holder = database
4945
.try_exclusive(LockKey::TransactionTest)
5046
.await

‎crates/database/src/fixtures.rs‎

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
//! What database tests start from: a connection, accounts, sessions and
2+
//! delivery channels. This crate's tests use them, and so do other crates' tests,
3+
//! behind the `test-util` feature.
4+
5+
use crate::{Database, EventRepository, InsertSession, InsertUser, UserRepository};
6+
use chrono::{TimeDelta, Utc};
7+
use sourceorigin_common::{
8+
Handle, SessionId, UserId,
9+
events::{Browser, DomainEvent, Platform, UserAgentFamily},
10+
};
11+
use std::net::IpAddr;
12+
13+
impl Database {
14+
/// Connects a default pool to `TEST_DATABASE_URL` and applies the schema.
15+
///
16+
/// # Panics
17+
///
18+
/// Panics if `TEST_DATABASE_URL` is unset, or connecting or migrating fails.
19+
#[expect(
20+
clippy::expect_used,
21+
reason = "test-only fixture; documented under `# Panics`"
22+
)]
23+
pub async fn test() -> Self {
24+
let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL");
25+
let database = Self {
26+
pool: sqlx::PgPool::connect(&url).await.expect("connect"),
27+
};
28+
database.run_migrations().await.expect("migrate");
29+
database
30+
}
31+
}
32+
33+
impl InsertUser {
34+
/// An account whose handle is `prefix` and a random suffix, for tests.
35+
///
36+
/// # Panics
37+
///
38+
/// Panics if `prefix` cannot start a handle.
39+
#[must_use]
40+
#[expect(
41+
clippy::expect_used,
42+
reason = "test-only constructor; documented under `# Panics`"
43+
)]
44+
pub fn named(prefix: &str) -> Self {
45+
let id = UserId::new();
46+
Self {
47+
id,
48+
handle: Handle::parse(&format!("{prefix}-{}", &id.to_string()[24..]))
49+
.expect("a handle prefix"),
50+
display_name: format!("{prefix} test"),
51+
}
52+
}
53+
}
54+
55+
impl UserRepository<'_> {
56+
/// Creates the account [`InsertUser::named`] names after `prefix`, and
57+
/// returns its ID.
58+
///
59+
/// # Panics
60+
///
61+
/// Panics if `prefix` cannot start a handle, or the insert fails.
62+
#[expect(
63+
clippy::expect_used,
64+
reason = "test-only fixture; documented under `# Panics`"
65+
)]
66+
pub async fn insert_named(&mut self, prefix: &str) -> UserId {
67+
self.insert(&InsertUser::named(prefix))
68+
.await
69+
.expect("user")
70+
.id
71+
}
72+
}
73+
74+
impl InsertSession {
75+
/// A new session of `user_id`, signed in now by no method from 192.0.2.1 in
76+
/// Firefox on Linux, unconfirmed, and ending after `lifetime`. Tests change the
77+
/// fields they test.
78+
#[must_use]
79+
pub fn lasting(user_id: UserId, lifetime: TimeDelta) -> Self {
80+
let now = Utc::now();
81+
Self {
82+
id: SessionId::new(),
83+
user_id,
84+
authentication_methods: Vec::new(),
85+
authenticated_at: now,
86+
expires_at: now + lifetime,
87+
user_agent_family: UserAgentFamily {
88+
browser: Browser::Firefox,
89+
platform: Platform::Linux,
90+
},
91+
ip: IpAddr::from([192, 0, 2, 1]),
92+
passkey_confirmed_at: None,
93+
passkey_id: None,
94+
}
95+
}
96+
}
97+
98+
impl EventRepository<'_> {
99+
/// The newest `limit` events concerning `user_id`, newest first.
100+
///
101+
/// # Panics
102+
///
103+
/// Panics if the query fails, or one of the events is unknown to this release.
104+
#[expect(
105+
clippy::expect_used,
106+
reason = "test-only fixture; documented under `# Panics`"
107+
)]
108+
pub async fn known_history(&mut self, user_id: UserId, limit: u32) -> Vec<DomainEvent> {
109+
self.history_for_user(user_id, limit)
110+
.await
111+
.expect("history")
112+
.into_iter()
113+
.map(|stored| stored.event.known().cloned().expect("a known event"))
114+
.collect()
115+
}
116+
}
117+
118+
/// Declares channels whose deliveries tests insert themselves, so no event causes
119+
/// one. Each entry reads `/// Doc comment` then
120+
/// `Name = "stored_name": Recipient => Payload;`. Tests run at once on one
121+
/// database, so each test that claims deliveries needs a stored name of its own.
122+
/// The calling crate must depend on `sourceorigin-common`.
123+
#[macro_export]
124+
macro_rules! test_channels {
125+
($($(#[doc = $doc:literal])* $name:ident = $value:literal: $recipient:ty => $payload:ty;)*) => {$(
126+
$(#[doc = $doc])*
127+
struct $name;
128+
129+
impl $crate::Channel for $name {
130+
const NAME: &'static str = $value;
131+
type Recipient = $recipient;
132+
type Payload = $payload;
133+
134+
/// Causes nothing: tests insert deliveries directly.
135+
fn deliveries(
136+
_: &::sourceorigin_common::events::DomainEvent,
137+
_: ::core::option::Option<::sourceorigin_common::UserId>,
138+
_: &[$crate::Notified],
139+
_: &mut $crate::DatabaseTransaction<'_>,
140+
) -> impl ::core::future::Future<
141+
Output = ::core::result::Result<
142+
::std::vec::Vec<$crate::NewDelivery<Self>>,
143+
$crate::DatabaseError,
144+
>,
145+
> + Send {
146+
::core::future::ready(Ok(::std::vec::Vec::new()))
147+
}
148+
}
149+
)*};
150+
}

‎crates/database/src/lib.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,17 @@
22
//!
33
//! Applications receive typed repositories and never a pool, executor, row, or
44
//! `SQLx` error. Repositories expose only the operations used by the service, plus
5-
//! read-only helpers behind the `test-util` feature for other crates' tests.
5+
//! read-only helpers and fixtures behind the `test-util` feature for other
6+
//! crates' tests.
67
/// Validated `PostgreSQL` transport and bounded connection pools.
78
mod connection;
89
/// Typed persistence and connection failures.
910
mod error;
1011
/// Advisory locks for jobs that run on one replica at a time.
1112
mod exclusive;
13+
/// What database tests start from.
14+
#[cfg(any(test, feature = "test-util"))]
15+
mod fixtures;
1216
/// What every table holds about the people behind accounts.
1317
mod inventory;
1418
/// Typed repository families with private SQL execution.

‎crates/database/src/repositories/announcements/tests.rs‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
44
use super::*;
55
use crate::{
6-
Database, DatabaseTransaction, EmailRepository, InsertUser, InsertVerifiedEmail,
7-
NotificationRepository, UserRepository,
6+
Database, DatabaseTransaction, EmailRepository, InsertVerifiedEmail, NotificationRepository,
7+
UserRepository,
88
};
99
use chrono::Utc;
1010
use sourceorigin_common::{
@@ -42,10 +42,8 @@ async fn received(
4242
/// Creates an account, with `address` as its primary verified one if given.
4343
async fn account(pool: &PgPool, address: Option<&str>) -> UserId {
4444
let user = UserRepository::from_pool(pool)
45-
.insert(&InsertUser::named("announce"))
46-
.await
47-
.expect("user")
48-
.id;
45+
.insert_named("announce")
46+
.await;
4947
if let Some(address) = address {
5048
EmailRepository::from_pool(pool)
5149
.insert_verified(&InsertVerifiedEmail {

‎crates/database/src/repositories/deletions/tests.rs‎

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,24 @@
11
//! Scheduling, restore tokens and the purge.
22
use super::*;
3-
use crate::{Database, DatabaseTransaction, EventRepository, InsertUser, RestoreToken};
3+
use crate::{Database, DatabaseTransaction, EventRepository, RestoreToken, UserRepository};
44
use chrono::Duration;
55
use sourceorigin_common::{
66
AccountStatus, PasskeyId, Personal, Provider, SessionId, TokenId,
77
events::{Actor, Browser, DomainEvent, EventContext, Platform, RequestOrigin, UserAgentFamily},
88
};
99
use sourceorigin_common::{AuthenticationMethod, events::SignInFailure};
10-
use sqlx::{Acquire, PgPool};
10+
use sqlx::Acquire;
1111
use std::net::IpAddr;
1212

13-
/// Inserts an active account whose handle is `prefix` and part of its ID.
14-
async fn insert_user(pool: &PgPool, prefix: &str) -> UserId {
15-
crate::UserRepository::from_pool(pool)
16-
.insert(&InsertUser::named(prefix))
17-
.await
18-
.expect("user")
19-
.id
20-
}
21-
2213
/// A restore token is found while unexpired and its passkey active, and a newer
2314
/// one replaces it. Cancelling the deletion ends both the schedule and the token.
2415
#[tokio::test]
2516
#[ignore = "requires a disposable TEST_DATABASE_URL"]
2617
async fn restore_tokens_expire_and_end_with_the_deletion() {
2718
let pool = Database::test_pool().await;
28-
let user = insert_user(&pool, "restore").await;
19+
let user = UserRepository::from_pool(&pool)
20+
.insert_named("restore")
21+
.await;
2922
let mut deletions = AccountDeletionRepository::from_pool(&pool);
3023
let purge_after = Utc::now() + Duration::days(30);
3124
let scheduled = deletions
@@ -139,8 +132,12 @@ async fn restore_tokens_expire_and_end_with_the_deletion() {
139132
)]
140133
async fn purge_leaves_nothing_that_references_or_identifies_the_account() {
141134
let pool = Database::test_pool().await;
142-
let user = insert_user(&pool, "purged").await;
143-
let bystander = insert_user(&pool, "bystander").await;
135+
let user = UserRepository::from_pool(&pool)
136+
.insert_named("purged")
137+
.await;
138+
let bystander = UserRepository::from_pool(&pool)
139+
.insert_named("bystander")
140+
.await;
144141
let client = format!("purge-{user}");
145142
let (session, code, family) = (SessionId::new(), TokenId::new(), TokenId::new());
146143
// Announcements to the account alone, to it and the bystander, and to everyone.
@@ -397,7 +394,9 @@ async fn purge_leaves_nothing_that_references_or_identifies_the_account() {
397394
#[ignore = "requires a disposable TEST_DATABASE_URL"]
398395
async fn personal_data_stored_during_a_purge_is_erased() {
399396
let pool = Database::test_pool().await;
400-
let user = insert_user(&pool, "racing").await;
397+
let user = UserRepository::from_pool(&pool)
398+
.insert_named("racing")
399+
.await;
401400
let failed = EventContext {
402401
actor: Actor::Anonymous,
403402
origin: RequestOrigin {
@@ -453,7 +452,9 @@ async fn an_alert_raised_during_a_purge_leaves_no_email() {
453452
events::JobName,
454453
};
455454
let pool = Database::test_pool().await;
456-
let user = insert_user(&pool, "alerted").await;
455+
let user = UserRepository::from_pool(&pool)
456+
.insert_named("alerted")
457+
.await;
457458
// Test-generated IDs only, so formatting them into the SQL is safe.
458459
sqlx::raw_sql(&format!(
459460
"INSERT INTO user_emails (id, user_id, normalized_email, verified_at, is_primary)
@@ -510,8 +511,10 @@ async fn an_alert_raised_during_a_purge_leaves_no_email() {
510511
#[ignore = "requires a disposable TEST_DATABASE_URL"]
511512
async fn failed_purges_back_off_behind_other_accounts() {
512513
let pool = Database::test_pool().await;
513-
let failing = insert_user(&pool, "failing").await;
514-
let other = insert_user(&pool, "other").await;
514+
let failing = UserRepository::from_pool(&pool)
515+
.insert_named("failing")
516+
.await;
517+
let other = UserRepository::from_pool(&pool).insert_named("other").await;
515518
let mut deletions = AccountDeletionRepository::from_pool(&pool);
516519
// Other tests' accounts may be due too, so only these two are compared.
517520
let order = async |deletions: &mut AccountDeletionRepository<'_>| {

0 commit comments

Comments
 (0)