|
| 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 | +} |
0 commit comments