Skip to content

Commit

Permalink
feat: postgresql database configuration + update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Yag000 committed Aug 27, 2023
1 parent eb93a7d commit 2cc5863
Show file tree
Hide file tree
Showing 8 changed files with 231 additions and 2 deletions.
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DATABASE_URL="postgres://postgres:password@localhost:5432/newsletter"
162 changes: 162 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ poath = "src/lib.rs"

[dependencies]
actix-web = "4.3.1"
config = "0.13.3"
reqwest = "0.11.20"
serde = { version = "1.0.188", features = ["derive"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
Expand Down
7 changes: 7 additions & 0 deletions configuration.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
application_port: 8000
database:
host: "127.0.0.1"
port: 5432
username: "postgres"
password: "password"
database_name: "newsletter"
34 changes: 34 additions & 0 deletions src/configurations.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,36 @@
#[derive(serde::Deserialize)]
pub struct Settings {
pub database: DatabaseSettings,
pub application_port: u16,
}

#[derive(serde::Deserialize)]
pub struct DatabaseSettings {
pub username: String,
pub password: String,
pub port: u16,
pub host: String,
pub database_name: String,
}

impl DatabaseSettings {
pub fn get_connnection_string(&self) -> String {
format!(
"postgres://{}:{}@{}:{}/{}",
self.username, self.password, self.host, self.port, self.database_name
)
}
}

pub fn get_configuration() -> Result<Settings, config::ConfigError> {
// Initialize the configuration reader
let settings = config::Config::builder()
// Config file name
.add_source(config::File::new(
"configuration.yml",
config::FileFormat::Yaml,
))
.build()?;

settings.try_deserialize::<Settings>()
}
8 changes: 6 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
use std::net::TcpListener;
use zero2prod::startup::run;
use zero2prod::{configurations::get_configuration, startup::run};

#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind random port");
// We want to panic if we cannot read the configuration
let configuration = get_configuration().expect("Failed to read configurations");
// Bind the TCP listener socket address with the configuration port
let address = format!("127.0.0.1:{}", configuration.application_port);
let listener = TcpListener::bind(address).expect("Failed to bind random port");
run(listener)?.await
}
1 change: 1 addition & 0 deletions src/routes/subscriptions.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use actix_web::{web, HttpResponse};

#[allow(dead_code)]
#[derive(serde::Deserialize)]
pub struct FormData {
email: String,
Expand Down
19 changes: 19 additions & 0 deletions tests/health_check.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use std::net::TcpListener;

use sqlx::Connection;
use zero2prod::configurations::get_configuration;

fn spawn_app() -> String {
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind random port");
let port = listener.local_addr().unwrap().port();
Expand Down Expand Up @@ -28,8 +31,15 @@ async fn health_check_works() {
async fn subscribe_returns_a_200_for_valid_form_data() {
// Arrange
let app_address = spawn_app();
let configuration = get_configuration().expect("Failed to read configurations");
let connection_string = configuration.database.get_connnection_string();
let mut connection = sqlx::PgConnection::connect(&connection_string)
.await
.expect("Failed to connect to Postgres.");

let client = reqwest::Client::new();
let body = "name=le%20guin&email=ursula_le_guin%40gmail.com";

// Act
let response = client
.post(format!("{}/subscriptions", app_address))
Expand All @@ -38,8 +48,17 @@ async fn subscribe_returns_a_200_for_valid_form_data() {
.send()
.await
.expect("Failed to execute request.");

// Assert
assert_eq!(200, response.status().as_u16());

let saved = sqlx::query!("SELECT email, name FROM subscriptions",)
.fetch_one(&mut connection)
.await
.expect("Failed to fetch saved subscription.");

assert_eq!(saved.email, "ursula_le_guin@gmail.com");
assert_eq!(saved.name, "le guin");
}

#[tokio::test]
Expand Down

0 comments on commit 2cc5863

Please sign in to comment.