|
| 1 | +use std::future::Future; |
| 2 | +use tokio_postgres::config::Host; |
| 3 | +use tokio_postgres::Config; |
| 4 | + |
| 5 | +use crate::pool::postgres::make_client; |
| 6 | +use crate::Pool; |
| 7 | + |
| 8 | +/// Represents a connection to a Postgres database that can be |
| 9 | +/// used in integration tests to test logic that interacts with |
| 10 | +/// a database. |
| 11 | +pub(crate) struct TestContext { |
| 12 | + db_name: String, |
| 13 | + original_db_url: String, |
| 14 | + // Pre-cached client to avoid creating unnecessary connections in tests |
| 15 | + client: Pool, |
| 16 | +} |
| 17 | + |
| 18 | +impl TestContext { |
| 19 | + async fn new(db_url: &str) -> Self { |
| 20 | + let config: Config = db_url.parse().expect("Cannot parse connection string"); |
| 21 | + |
| 22 | + // Create a new database that will be used for this specific test |
| 23 | + let client = make_client(&db_url) |
| 24 | + .await |
| 25 | + .expect("Cannot connect to database"); |
| 26 | + let db_name = format!("db{}", uuid::Uuid::new_v4().to_string().replace("-", "")); |
| 27 | + client |
| 28 | + .execute(&format!("CREATE DATABASE {db_name}"), &[]) |
| 29 | + .await |
| 30 | + .expect("Cannot create database"); |
| 31 | + drop(client); |
| 32 | + |
| 33 | + let host = match &config |
| 34 | + .get_hosts() |
| 35 | + .first() |
| 36 | + .expect("connection string must contain at least one host") |
| 37 | + { |
| 38 | + Host::Tcp(host) => host, |
| 39 | + |
| 40 | + // This variant only exists on Unix targets, so the arm itself is |
| 41 | + // cfg-gated to keep non-unix builds happy. |
| 42 | + #[cfg(unix)] |
| 43 | + Host::Unix(_) => panic!("Unix sockets in Postgres connection string are not supported"), |
| 44 | + |
| 45 | + // On non-unix targets the enum has no other variants. |
| 46 | + #[cfg(not(unix))] |
| 47 | + _ => unreachable!("non-TCP hosts cannot appear on this platform"), |
| 48 | + }; |
| 49 | + |
| 50 | + // We need to connect to the database against, because Postgres doesn't allow |
| 51 | + // changing the active database mid-connection. |
| 52 | + // There does not seem to be a way to turn the config back into a connection |
| 53 | + // string, so construct it manually. |
| 54 | + let test_db_url = format!( |
| 55 | + "postgresql://{}:{}@{}:{}/{}", |
| 56 | + config.get_user().unwrap(), |
| 57 | + String::from_utf8(config.get_password().unwrap().to_vec()).unwrap(), |
| 58 | + host, |
| 59 | + &config.get_ports()[0], |
| 60 | + db_name |
| 61 | + ); |
| 62 | + let pool = Pool::open(test_db_url.as_str()); |
| 63 | + |
| 64 | + Self { |
| 65 | + db_name, |
| 66 | + original_db_url: db_url.to_string(), |
| 67 | + client: pool, |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + pub(crate) fn db_client(&self) -> &Pool { |
| 72 | + &self.client |
| 73 | + } |
| 74 | + |
| 75 | + async fn finish(self) { |
| 76 | + // Cleanup the test database |
| 77 | + // First, we need to stop using the database |
| 78 | + drop(self.client); |
| 79 | + |
| 80 | + // Then we need to connect to the default database and drop our test DB |
| 81 | + let client = make_client(&self.original_db_url) |
| 82 | + .await |
| 83 | + .expect("Cannot connect to database"); |
| 84 | + client |
| 85 | + .execute(&format!("DROP DATABASE {}", self.db_name), &[]) |
| 86 | + .await |
| 87 | + .unwrap(); |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +pub(crate) async fn run_db_test<F, Fut>(f: F) |
| 92 | +where |
| 93 | + F: FnOnce(TestContext) -> Fut, |
| 94 | + Fut: Future<Output = anyhow::Result<TestContext>>, |
| 95 | +{ |
| 96 | + if let Ok(db_url) = std::env::var("TEST_DB_URL") { |
| 97 | + let ctx = TestContext::new(&db_url).await; |
| 98 | + let ctx = f(ctx).await.expect("Test failed"); |
| 99 | + ctx.finish().await; |
| 100 | + } else { |
| 101 | + // The github CI does not yet support running containers on Windows, |
| 102 | + // meaning that the test suite would fail. |
| 103 | + if cfg!(unix) { |
| 104 | + panic!("Aborting; `TEST_DB_URL` was not passed"); |
| 105 | + } else { |
| 106 | + eprintln!( |
| 107 | + "Skipping database test on platform {} `TEST_DB_URL` was not passed", |
| 108 | + std::env::consts::OS |
| 109 | + ); |
| 110 | + } |
| 111 | + } |
| 112 | +} |
0 commit comments