Skip to content

Commit

Permalink
fix test case
Browse files Browse the repository at this point in the history
  • Loading branch information
codebyshubham committed Jan 3, 2024
1 parent 131588a commit a3ec731
Show file tree
Hide file tree
Showing 6 changed files with 91 additions and 24 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ config = "0.13.4"
# The feature is not enabled by default to avoid pulling in
# unnecessary dependencies for projects that do not need it.
serde = { version = "1", features = ["derive"]}
uuid = { version = "0.8.1", features = ["v4"] }
chrono = "0.4.15"

# Using table-like toml syntax to avoid a super-long line!
[dependencies.sqlx]
Expand Down
7 changes: 7 additions & 0 deletions src/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ impl DatabaseSettings {
self.username, self.password, self.host, self.port, self.database_name
)
}

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

pub fn get_configuration() -> Result<Settings, config::ConfigError> {
Expand Down
9 changes: 8 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
use std::net::TcpListener;
use sqlx::{PgPool};
use newsletter_service::startup::run;
use newsletter_service::configuration;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
let configuration = configuration::get_configuration().expect("Failed to load configuration!");

let connection_string = configuration.database.connection_string();

let connection = PgPool::connect(&connection_string)
.await
.expect("Failed to connect to database");

let address = format!("127.0.0.1:{}", configuration.application_port);

let listener = TcpListener::bind(address)?;

println!("Server is running on 127.0.0.1:{}", listener.local_addr().unwrap().port());

run(listener)?.await
run(listener, connection)?.await
}
28 changes: 25 additions & 3 deletions src/routes/subscriptions.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,33 @@
use actix_web::{Responder, HttpResponse, web};
use actix_web::{HttpResponse, web};
use sqlx::PgPool;
use sqlx::types::chrono::Utc;
use uuid::Uuid;

#[derive(serde::Deserialize)]
pub struct FormData {
email: String,
name: String
}

pub async fn subscribe(_form: web::Form<FormData>) -> impl Responder {
HttpResponse::Ok().finish()
pub async fn subscribe(form: web::Form<FormData>, db_pool: web::Data<PgPool>) -> HttpResponse {
let result = sqlx::query!(
r#"
INSERT INTO subscriptions (id, email, name, subscribed_at)
VALUES ($1, $2, $3, $4)
"#,
Uuid::new_v4(),
form.email,
form.name,
Utc::now()
)
.execute(db_pool.get_ref())
.await;

match result {
Ok(_) => HttpResponse::Ok().finish(),
Err(e) => {
println!("Failed to execute query {}", e);
HttpResponse::InternalServerError().finish()
}
}
}
7 changes: 5 additions & 2 deletions src/startup.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
use actix_web::{web, App, HttpServer};
use actix_web::dev::Server;
use std::net::TcpListener;
use sqlx::PgPool;
use crate::routes::health_check;
use crate::routes::subscribe;


pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> {
let server = HttpServer::new(|| {
pub fn run(listener: TcpListener, db_pool: PgPool) -> Result<Server, std::io::Error> {
let db_pool = web::Data::new(db_pool);
let server = HttpServer::new(move || {
App::new()
.route("/health_check", web::get().to(health_check))
.route("/subscription", web::post().to(subscribe))
.app_data(db_pool.clone())
})
.listen(listener)?
.run();
Expand Down
62 changes: 44 additions & 18 deletions tests/health_check.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use std::net::TcpListener;
use sqlx::Connection;
use sqlx::PgConnection;
use newsletter_service::configuration::get_configuration;
use sqlx::{Executor, PgConnection, PgPool, Connection};
use uuid::Uuid;
use newsletter_service::configuration::{DatabaseSettings, get_configuration};

#[actix_rt::test]
async fn health_check_works() {
let address = spawn_app();
let app = spawn_app().await;
let client = reqwest::Client::new();

let response = client
.get(&format!("{}/health_check", &address))
.get(&format!("{}/health_check", &app.address))
.send()
.await
.expect("Failed to execute request!");
Expand All @@ -18,33 +18,59 @@ async fn health_check_works() {
assert_eq!(Some(0), response.content_length());
}

fn spawn_app() -> String {
pub struct TestApp {
pub address: String,
pub db_pool: PgPool
}

async fn spawn_app() -> TestApp {
let listener = TcpListener::bind("127.0.0.1:0")
.expect("Failed to bind at random port");
let port = listener.local_addr().unwrap().port();
let server = newsletter_service::startup::run(listener).expect("Failed to bind address");

let mut configuration = get_configuration().expect("Failed to load configuration!");
configuration.database.database_name = Uuid::new_v4().to_string();
let connection_pool = configure_database(&configuration.database).await;

let server = newsletter_service::startup::run(listener, connection_pool.clone()).expect("Failed to bind address");

let _ = tokio::spawn(server);

format!("http://127.0.0.1:{}", port)
TestApp {
address: format!("http://127.0.0.1:{}", port),
db_pool: connection_pool
}
}

#[actix_rt::test]
async fn subscribe_returns_a_200_for_valid_form_data() {
let address = spawn_app();
let configuration = get_configuration().expect("Failed to load configuration!");
pub async fn configure_database(config: &DatabaseSettings) -> PgPool {
let mut connection = PgConnection::connect(&config.connection_string_without_db())
.await
.expect("Failed to connect to postgress");

let connection_string = configuration.database.connection_string();
connection.execute(format!(r#"CREATE DATABASE "{}";"#, config.database_name).as_str())
.await
.expect("Failed to create database");

let mut connection = PgConnection::connect(&connection_string)
let connection_pool = PgPool::connect(&config.connection_string())
.await
.expect("Failed to connect to database");

sqlx::migrate!("./migrations")
.run(&connection_pool)
.await
.expect("Failed to run migration");

connection_pool
}

#[actix_rt::test]
async fn subscribe_returns_a_200_for_valid_form_data() {
let app = spawn_app().await;
let client = reqwest::Client::new();
let body = "name=shubham%20patel&email=shubhampatel%40example.com";

let response = client
.post(&format!("{}/subscription", &address))
.post(&format!("{}/subscription", &app.address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(body)
.send()
Expand All @@ -54,7 +80,7 @@ async fn subscribe_returns_a_200_for_valid_form_data() {
assert_eq!(200, response.status().as_u16());

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

Expand All @@ -64,7 +90,7 @@ async fn subscribe_returns_a_200_for_valid_form_data() {

#[actix_rt::test]
async fn subscribe_returns_a_400_when_data_is_missing() {
let address = spawn_app();
let app = spawn_app().await;
let client = reqwest::Client::new();
let test_cases = vec![
("name=shubham", "missing the email address!"),
Expand All @@ -74,7 +100,7 @@ async fn subscribe_returns_a_400_when_data_is_missing() {

for (invalid_body, error_message) in test_cases {
let response = client
.post(&format!("{}/subscription", address))
.post(&format!("{}/subscription", &app.address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(invalid_body)
.send()
Expand Down

0 comments on commit a3ec731

Please sign in to comment.