finished logging chapter

This commit is contained in:
Andre Heber
2024-02-19 11:12:46 +01:00
parent a0aa12872d
commit 39b6e11885
9 changed files with 317 additions and 30 deletions

View File

@ -1,15 +1,31 @@
use sqlx::{postgres::PgPoolOptions, query, Executor, Pool, Postgres};
use once_cell::sync::Lazy;
use secrecy::ExposeSecret;
use sqlx::{postgres::PgPoolOptions, query, Connection, Executor, PgConnection, Pool, Postgres};
use uuid::Uuid;
use std::net::TcpListener;
use zero2prod::configuration::{get_configuration, DatabaseSettings};
use std:: net::TcpListener;
use zero2prod::{configuration::{get_configuration, DatabaseSettings}, telemetry::{get_subscriber, init_subscriber}};
pub struct TestApp {
pub address: String,
pub connection_pool: Pool<Postgres>,
}
static TRACING: Lazy<()> = Lazy::new(|| {
let default_filter_level = "info".to_string();
let subscriber_name = "test".to_string();
if std::env::var("TEST_LOG").is_ok() {
let subscriber = get_subscriber(subscriber_name, default_filter_level, std::io::stdout);
init_subscriber(subscriber);
} else {
let subscriber = get_subscriber(subscriber_name, default_filter_level, std::io::sink);
init_subscriber(subscriber);
}
});
async fn spawn_app() -> TestApp {
Lazy::force(&TRACING);
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind random port");
let port = listener.local_addr().unwrap().port();
let address = format!("http://127.0.0.1:{}", port);
@ -28,16 +44,20 @@ async fn spawn_app() -> TestApp {
}
pub async fn configure_database(config: &DatabaseSettings) -> Pool<Postgres> {
let connection_pool = PgPoolOptions::new()
.max_connections(10)
.connect(&config.connection_string_without_db())
let mut connection = PgConnection::connect(config.connection_string_without_db().expose_secret())
.await
.expect("Failed to connect to Postgres.");
connection_pool.execute(format!(r#"CREATE DATABASE "{}";"#, config.database_name).as_str())
connection.execute(format!(r#"CREATE DATABASE "{}";"#, config.database_name).as_str())
.await
.expect("Failed to create database.");
let connection_pool = PgPoolOptions::new()
.max_connections(10)
.connect(config.connection_string().expose_secret())
.await
.expect("Failed to connect to Postgres.");
sqlx::migrate!("./migrations")
.run(&connection_pool)
.await