-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
updated the tests to create logical db for unit tests
- Loading branch information
1 parent
201c412
commit 89a8257
Showing
9 changed files
with
121 additions
and
50 deletions.
There are no files selected for viewing
This file contains 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 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 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 |
---|---|---|
@@ -1,3 +1,3 @@ | ||
pub mod configuration; | ||
pub mod routes; | ||
pub mod startup; | ||
pub mod startup; |
This file contains 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 |
---|---|---|
@@ -1,12 +1,16 @@ | ||
use std::net::TcpListener; | ||
use newsletter::startup::run; | ||
use newsletter::configuration::get_configuration; | ||
use newsletter::startup::run; | ||
use sqlx::PgPool; | ||
use std::net::TcpListener; | ||
|
||
#[tokio::main] | ||
async fn main() -> std::io::Result<()> { | ||
// Panic if we can't read configuration | ||
let configuration = get_configuration().expect("Failed to read configuration."); | ||
let connection_pool = PgPool::connect(&configuration.database.connection_string()) | ||
.await | ||
.expect("Failed to connect to Postgres!"); | ||
let address = format!("127.0.0.1:{}", configuration.application_port); | ||
let listener = TcpListener::bind(address)?; | ||
run(listener)?.await | ||
} | ||
run(listener, connection_pool)?.await | ||
} |
This file contains 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 |
---|---|---|
@@ -1,5 +1,5 @@ | ||
use actix_web::HttpResponse; | ||
|
||
pub async fn health_check() -> HttpResponse { | ||
HttpResponse::Ok().finish() | ||
} | ||
HttpResponse::Ok().finish() | ||
} |
This file contains 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 |
---|---|---|
|
@@ -2,4 +2,4 @@ mod health_check; | |
mod subscriptions; | ||
|
||
pub use health_check::*; | ||
pub use subscriptions::*; | ||
pub use subscriptions::*; |
This file contains 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 |
---|---|---|
@@ -1,11 +1,32 @@ | ||
use actix_web::{web, HttpResponse}; | ||
use chrono::Utc; | ||
use sqlx::PgPool; | ||
use uuid::Uuid; | ||
|
||
#[derive(serde::Deserialize)] | ||
pub struct FormData { | ||
email: String, | ||
name: String | ||
name: String, | ||
} | ||
|
||
pub async fn subscribe(_form: web::Form<FormData>) -> HttpResponse { | ||
HttpResponse::Ok().finish() | ||
} | ||
pub async fn subscribe(form: web::Form<FormData>, pool: web::Data<PgPool>) -> HttpResponse { | ||
match 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(pool.get_ref()) | ||
.await | ||
{ | ||
Ok(_) => HttpResponse::Ok().finish(), | ||
Err(e) => { | ||
println!("Failed to execute the query: {}", e); | ||
HttpResponse::InternalServerError().finish() | ||
} | ||
} | ||
} |
This file contains 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 |
---|---|---|
@@ -1,16 +1,19 @@ | ||
use actix_web::dev::Server; | ||
use actix_web::{web, App, HttpServer}; | ||
use sqlx::PgPool; | ||
use std::net::TcpListener; | ||
|
||
use crate::routes::{health_check, subscribe}; | ||
|
||
pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> { | ||
let server = HttpServer::new(|| { | ||
App::new() | ||
.route("/health_check", web::get().to(health_check)) | ||
.route("/subscriptions", web::post().to(subscribe)) | ||
}) | ||
.listen(listener)? | ||
.run(); | ||
Ok(server) | ||
} | ||
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("/subscriptions", web::post().to(subscribe)) | ||
.app_data(db_pool.clone()) | ||
}) | ||
.listen(listener)? | ||
.run(); | ||
Ok(server) | ||
} |
This file contains 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 |
---|---|---|
@@ -1,28 +1,67 @@ | ||
use std::net::TcpListener; | ||
use newsletter::configuration::{get_configuration, DatabaseSettings}; | ||
use newsletter::startup::run; | ||
use sqlx::{PgConnection, Connection}; | ||
use newsletter::configuration::get_configuration; | ||
use sqlx::{PgPool, Connection, Executor, PgConnection}; | ||
use std::net::TcpListener; | ||
use uuid::Uuid; | ||
|
||
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 random port"); | ||
let port = listener.local_addr().unwrap().port(); | ||
let server = run(listener).expect("Failed to bind address"); | ||
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); | ||
format!("http://127.0.0.1:{}", port) | ||
|
||
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).as_str()) | ||
.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 | ||
} | ||
|
||
#[tokio::test] | ||
async fn health_check_works() { | ||
// Arrange | ||
let address = spawn_app(); | ||
// to perform HTTP requests against our application. | ||
let app = spawn_app().await; | ||
// to perform HTTP requests against our application. | ||
let client = reqwest::Client::new(); | ||
|
||
// Act | ||
let response = client | ||
.get(&format!("{}/health_check", address)) | ||
.get(&format!("{}/health_check", app.address)) | ||
.send() | ||
.await | ||
.expect("Failed to execute request."); | ||
|
@@ -34,17 +73,12 @@ async fn health_check_works() { | |
|
||
#[tokio::test] | ||
async fn subscribe_returns_200_for_valid_form_data() { | ||
let app_address = spawn_app(); | ||
let configuration = get_configuration().expect("Failed to read configuration"); | ||
let connection_string = configuration.database.connection_string(); | ||
let mut connection = PgConnection::connect(&connection_string) | ||
.await | ||
.expect("Failed to connect to Postgres"); | ||
let app = spawn_app().await; | ||
let client = reqwest::Client::new(); | ||
|
||
let body = "name=dibakar%20dhar&email=where_is_dibakar%40gmail.com"; | ||
let response = client | ||
.post(&format!("{}/subscriptions", &app_address)) | ||
.post(&format!("{}/subscriptions", &app.address)) | ||
.header("Content-Type", "application/x-www-form-urlencoded") | ||
.body(body) | ||
.send() | ||
|
@@ -54,28 +88,27 @@ async fn subscribe_returns_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 saved subscription"); | ||
|
||
assert_eq!(saved.email, "[email protected]"); | ||
assert_eq!(saved.name, "dibakar dhar"); | ||
|
||
} | ||
|
||
#[tokio::test] | ||
async fn subscribe_returns_400_when_data_is_missing() { | ||
let app_address = spawn_app(); | ||
let app = spawn_app().await; | ||
let client = reqwest::Client::new(); | ||
let test_cases = vec![ | ||
("name=le%20guin", "missing the email"), | ||
("email=uresela_le_guin%40gmail.com", "missing the name"), | ||
("", "missing both name and email") | ||
("", "missing both name and email"), | ||
]; | ||
|
||
for (invalid_body, error_message) in test_cases { | ||
let response = client | ||
.post(&format!("{}/subscriptions", app_address)) | ||
.post(&format!("{}/subscriptions", app.address)) | ||
.header("Content-Type", "application/x-www-form-urlencoded") | ||
.body(invalid_body) | ||
.send() | ||
|
@@ -85,7 +118,8 @@ async fn subscribe_returns_400_when_data_is_missing() { | |
assert_eq!( | ||
400, | ||
response.status().as_u16(), | ||
"The API did not fail with 400 Bad Request when the payload was {}.", error_message | ||
"The API did not fail with 400 Bad Request when the payload was {}.", | ||
error_message | ||
); | ||
} | ||
} | ||
} |