mirror of
https://github.com/LukeMathWalker/zero-to-production.git
synced 2024-12-19 22:46:36 +00:00
24dccda00c
* Adjust content encoding. * Refactor assertion. * Add one more test case * Fix assertions. * Fix route. * Stricter assertions * Few fixes. * Formatting
52 lines
1.7 KiB
Rust
52 lines
1.7 KiB
Rust
use chapter03_1::configuration::{get_configuration, DatabaseSettings};
|
|
use chapter03_1::startup::run;
|
|
use sqlx::Executor;
|
|
use sqlx::{Connection, PgConnection, PgPool};
|
|
use std::net::TcpListener;
|
|
use uuid::Uuid;
|
|
|
|
pub struct TestApp {
|
|
pub address: String,
|
|
pub db_pool: PgPool,
|
|
}
|
|
|
|
pub async fn spawn_app() -> TestApp {
|
|
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind random port");
|
|
// We retrieve the port assigned to us by the OS
|
|
let port = listener.local_addr().unwrap().port();
|
|
let address = format!("http://127.0.0.1:{}", port);
|
|
|
|
let mut configuration = get_configuration().expect("Failed to read configuration.");
|
|
configuration.database.database_name = Uuid::new_v4().to_string();
|
|
|
|
let connection_pool = configure_database(&configuration.database).await;
|
|
|
|
let server = run(listener, connection_pool.clone()).expect("Failed to bind address");
|
|
let _ = tokio::spawn(server);
|
|
TestApp {
|
|
address,
|
|
db_pool: connection_pool,
|
|
}
|
|
}
|
|
|
|
pub async fn configure_database(config: &DatabaseSettings) -> PgPool {
|
|
// Create database
|
|
let mut connection = PgConnection::connect(&config.connection_string_without_db())
|
|
.await
|
|
.expect("Failed to connect to Postgres");
|
|
connection
|
|
.execute(&*format!(r#"CREATE DATABASE "{}";"#, config.database_name))
|
|
.await
|
|
.expect("Failed to create database.");
|
|
|
|
// Migrate database
|
|
let connection_pool = PgPool::connect(&config.connection_string())
|
|
.await
|
|
.expect("Failed to connect to Postgres.");
|
|
sqlx::migrate!("./migrations")
|
|
.run(&connection_pool)
|
|
.await
|
|
.expect("Failed to migrate the database");
|
|
|
|
connection_pool
|
|
}
|