feat: subscribe API route skeleton

- Added `serde` crate for serialisation or deserialisation of data
- Added test cases for the `subscribe` API route
- Refactor the testing setup to another module `test_utils`
- use random TCP port for testing
This commit is contained in:
minhtrannhat 2024-04-22 17:00:55 -04:00
parent 4b4286ae43
commit 84fc74a0d1
Signed by: minhtrannhat
GPG Key ID: E13CFA85C53F8062
8 changed files with 115 additions and 29 deletions

1
Cargo.lock generated
View File

@ -438,6 +438,7 @@ version = "0.1.0"
dependencies = [
"actix-web",
"reqwest",
"serde",
"tokio",
]

View File

@ -7,12 +7,15 @@ edition = "2021"
[lib]
path = "src/lib.rs"
edition = "2021"
[[bin]]
path = "src/main.rs"
name = "email_newsletter_api"
edition = "2021"
[dependencies]
actix-web = "4.5.1"
reqwest = "0.12.2"
serde = { version = "1.0.197", features = ["derive"] }
tokio = { version = "1.36.0", features = ["full"] }

View File

@ -3,6 +3,7 @@
## Routes
- `health_check`: returns a HTTP code 200 if the server is up and running. Response body is empty.
- `subscribe` returns a HTTP code 200 if the user successfully subscribed to our email newsletter service. 400 if data is missing or invalid.
## The `tokio` Async Runtime
@ -20,3 +21,4 @@
## The Test Suite
- The OS will find an available port for the test suite to use.
- We use the same PostgreSQL database instance for both testing and production environment (might bite us in the ass later ?).

View File

@ -1,15 +1,26 @@
use actix_web::{web, App, HttpResponse, HttpServer};
use actix_web::dev::Server;
use actix_web::{web, App, HttpResponse, HttpServer};
use std::net::TcpListener;
async fn healthcheck_route() -> HttpResponse {
return HttpResponse::Ok().finish()
#[derive(serde::Deserialize)]
struct FormData {
email: String,
name: String,
}
pub fn run(listener: TcpListener) -> Result<Server, std::io::Error>{
let server = HttpServer::new(||{
async fn healthcheck_route() -> HttpResponse {
HttpResponse::Ok().finish()
}
async fn subscribe_route(_form: web::Form<FormData>) -> HttpResponse {
HttpResponse::Ok().finish()
}
pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> {
let server = HttpServer::new(|| {
App::new()
.route("/health_check", web::get().to(healthcheck_route))
.route("/health_check", web::get().to(healthcheck_route))
.route("/subscribe", web::post().to(subscribe_route))
})
.listen(listener)?
.run();

5
tests/README.md Normal file
View File

@ -0,0 +1,5 @@
# Tests
## Notes
`tokio` spins up a new async runtime every time at the beginning of each test case and shutdown at the end of each test case the `spawn_app()` function therefore only survives as long as the runtime.

View File

@ -1,32 +1,19 @@
use std::{fmt::format, net::TcpListener};
// tokio spins up a new async runtime every time
// at the beginning of each test case and shutdown at
// the end of each test case
// the spawn_app() function therefore only survives as long as the runtime
mod test_utils;
use test_utils::spawn_app;
#[tokio::test]
async fn health_check_works(){
async fn health_check_works() {
let server_address = spawn_app();
let client = reqwest::Client::new();
let response = client.get(&format!("{}/health_check", &server_address)).send().await.expect("Failed to execute health_check request.");
let response = client
.get(&format!("{}/health_check", &server_address))
.send()
.await
.expect("Failed to execute health_check request.");
assert!(response.status().is_success());
assert_eq!(Some(0), response.content_length());
}
fn spawn_app() -> String {
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind to a random port");
let port = listener.local_addr().unwrap().port();
let server = email_newsletter_api::run(listener).expect("Failed to bind address");
// run() returns an instance of HttpServer that will run forever.
// We don't want this behavior
// Therefore we want to spawn our server, run our test logic
// and then tear down the entire test suite
let _ = tokio::spawn(server);
format!("http://127.0.0.1:{}", port)
}

53
tests/subscribe.rs Normal file
View File

@ -0,0 +1,53 @@
mod test_utils;
use test_utils::spawn_app;
#[tokio::test]
async fn subscribe_returns_a_200_for_valid_form_data() {
let server_address = spawn_app();
let client = reqwest::Client::new();
let body = "name=le%20test&email=le_test%40gmail.com";
let response = client
.post(&format!("{}/subscribe", &server_address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(body)
.send()
.await
.expect("Failed to execute subscribe request.");
assert!(response.status().is_success());
assert_eq!(Some(0), response.content_length());
}
#[tokio::test]
async fn subscribe_returns_a_400_when_data_is_missing() {
let server_address = spawn_app();
let client = reqwest::Client::new();
let test_cases = vec![
("name=le%20guin", "missing the email"),
("email=ursula_le_guin%40gmail.com", "missing the name"),
("", "missing both name and email"),
];
for (invalid_body, error_message) in test_cases {
let response = client
.post(&format!("{}/subscribe", &server_address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(invalid_body)
.send()
.await
.expect("Failed to execute subscribe request.");
assert_eq!(
400,
response.status().as_u16(),
"The API failed with 400 Bad Request when the payload was {}.",
error_message
)
}
}

24
tests/test_utils.rs Normal file
View File

@ -0,0 +1,24 @@
use std::net::TcpListener;
#[allow(dead_code)]
#[allow(clippy::let_underscore_future)]
pub fn spawn_app() -> String {
/* Spawn a app server with a TcpListener bound to localhost:<random port>
*
* Returns a valid IPv4 string (i.e localhost:8080)
*/
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind to a random port");
let port = listener.local_addr().unwrap().port();
let server = email_newsletter_api::run(listener).expect("Failed to bind address");
/* `tokio::spawn(/*async task*/)` will spawn an async task to be run.
We can continue executing other code concurrently while `task` runs in the background.
If we need to wait for `task` to complete before proceeding,
we can use `task.await`
(which `#[tokio::test]` will take care for us in the mean time).*/
let _ = tokio::spawn(server);
format!("http://127.0.0.1:{}", port)
}