-
Notifications
You must be signed in to change notification settings - Fork 153
Infra - wire up database for test #2119
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Kobzol
merged 7 commits into
rust-lang:master
from
Jamesbarford:infra/add-database-testing-capability
May 20, 2025
Merged
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
5918cc3
wiring up test database
Jamesbarford fa5fb61
fix pipeline - remove `make` as the test diver and add files to REUSE…
Jamesbarford 34c63bf
Handle window by cfg-gating the check for a host type
Jamesbarford 9eac5a4
pr feedback
Jamesbarford c0f241b
windows pipeline fix and more descriptive error message
Jamesbarford 998c309
Make concessions for Windows when running the testsuite (it does not …
Jamesbarford c01ac41
Update README for running tests
Jamesbarford File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
.PHONY: test start-postgres | ||
|
||
# Helper to spin up postgres | ||
start-postgres: | ||
docker compose up -d pg_test | ||
|
||
# Helper to stop postgres & destroy the volume (ensures a clean rebuild on `start`) | ||
stop-postgres: | ||
docker compose down -v | ||
|
||
# Run the tests with the database purring along in the background | ||
test: start-postgres | ||
TEST_DB_URL="postgres://postgres:testpass@localhost/postgres" cargo test |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
use std::future::Future; | ||
use tokio_postgres::config::Host; | ||
use tokio_postgres::Config; | ||
|
||
use crate::pool::postgres::make_client; | ||
use crate::Pool; | ||
|
||
/// Represents a connection to a Postgres database that can be | ||
/// used in integration tests to test logic that interacts with | ||
/// a database. | ||
pub(crate) struct TestContext { | ||
db_name: String, | ||
original_db_url: String, | ||
// Pre-cached client to avoid creating unnecessary connections in tests | ||
client: Pool, | ||
} | ||
|
||
impl TestContext { | ||
async fn new(db_url: &str) -> Self { | ||
let config: Config = db_url.parse().expect("Cannot parse connection string"); | ||
|
||
// Create a new database that will be used for this specific test | ||
let client = make_client(&db_url) | ||
.await | ||
.expect("Cannot connect to database"); | ||
let db_name = format!("db{}", uuid::Uuid::new_v4().to_string().replace("-", "")); | ||
client | ||
.execute(&format!("CREATE DATABASE {db_name}"), &[]) | ||
.await | ||
.expect("Cannot create database"); | ||
drop(client); | ||
|
||
let host = match &config | ||
.get_hosts() | ||
.first() | ||
.expect("connection string must contain at least one host") | ||
{ | ||
Host::Tcp(host) => host, | ||
|
||
// This variant only exists on Unix targets, so the arm itself is | ||
// cfg-gated to keep non-unix builds happy. | ||
#[cfg(unix)] | ||
Host::Unix(_) => panic!("Unix sockets in Postgres connection string are not supported"), | ||
|
||
// On non-unix targets the enum has no other variants. | ||
#[cfg(not(unix))] | ||
_ => unreachable!("non-TCP hosts cannot appear on this platform"), | ||
}; | ||
|
||
// We need to connect to the database against, because Postgres doesn't allow | ||
// changing the active database mid-connection. | ||
// There does not seem to be a way to turn the config back into a connection | ||
// string, so construct it manually. | ||
let test_db_url = format!( | ||
"postgresql://{}:{}@{}:{}/{}", | ||
config.get_user().unwrap(), | ||
String::from_utf8(config.get_password().unwrap().to_vec()).unwrap(), | ||
host, | ||
&config.get_ports()[0], | ||
db_name | ||
); | ||
let pool = Pool::open(test_db_url.as_str()); | ||
|
||
Self { | ||
db_name, | ||
original_db_url: db_url.to_string(), | ||
client: pool, | ||
} | ||
} | ||
|
||
pub(crate) fn db_client(&self) -> &Pool { | ||
&self.client | ||
} | ||
|
||
async fn finish(self) { | ||
// Cleanup the test database | ||
// First, we need to stop using the database | ||
drop(self.client); | ||
|
||
// Then we need to connect to the default database and drop our test DB | ||
let client = make_client(&self.original_db_url) | ||
.await | ||
.expect("Cannot connect to database"); | ||
client | ||
.execute(&format!("DROP DATABASE {}", self.db_name), &[]) | ||
.await | ||
.unwrap(); | ||
} | ||
} | ||
|
||
pub(crate) async fn run_db_test<F, Fut>(f: F) | ||
where | ||
F: FnOnce(TestContext) -> Fut, | ||
Fut: Future<Output = anyhow::Result<TestContext>>, | ||
{ | ||
if let Ok(db_url) = std::env::var("TEST_DB_URL") { | ||
Jamesbarford marked this conversation as resolved.
Show resolved
Hide resolved
|
||
let ctx = TestContext::new(&db_url).await; | ||
let ctx = f(ctx).await.expect("Test failed"); | ||
ctx.finish().await; | ||
} else { | ||
// The github CI does not yet support running containers on Windows, | ||
// meaning that the test suite would fail. | ||
if cfg!(unix) { | ||
panic!("Aborting; `TEST_DB_URL` was not passed"); | ||
} else { | ||
eprintln!( | ||
"Skipping database test on platform {} `TEST_DB_URL` was not passed", | ||
std::env::consts::OS | ||
); | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
services: | ||
pg_test: | ||
image: postgres:16-alpine | ||
environment: | ||
POSTGRES_USER: postgres | ||
POSTGRES_PASSWORD: testpass | ||
POSTGRES_DB: postgres | ||
ports: | ||
- "5432:5432" # expose to host for tests | ||
healthcheck: # wait until the DB is ready | ||
test: ["CMD-SHELL", "pg_isready -U postgres"] | ||
interval: 2s | ||
timeout: 2s | ||
retries: 15 | ||
tmpfs: | ||
- /var/lib/postgresql/data # store data in RAM | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.