added endpoint client

This commit is contained in:
Andre Heber
2024-02-26 15:09:54 +01:00
parent 2f4895928f
commit c4817e486c
2 changed files with 17 additions and 28 deletions

View File

@ -8,6 +8,18 @@ pub struct TestApp {
pub connection_pool: Pool<Postgres>,
}
impl TestApp {
pub async fn post_subscriptions(&self, body: String) -> reqwest::Response {
reqwest::Client::new()
.post(&format!("{}/subscriptions", &self.address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(body)
.send()
.await
.expect("Failed to execute request.")
}
}
static TRACING: Lazy<()> = Lazy::new(|| {
let default_filter_level = "info".to_string();
let subscriber_name = "test".to_string();

View File

@ -4,16 +4,7 @@ use sqlx::query;
#[tokio::test]
async fn subscribe_returns_a_200_for_valid_form_data() {
let app = spawn_app().await;
let client = reqwest::Client::new();
let body = "name=andre&email=andre.heber@gmx.net";
let response = client
.post(&format!("{}/subscriptions", &app.address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(body)
.send()
.await
.expect("Failed to execute request.");
let response = app.post_subscriptions("name=andre&email=andre.heber@gmx.net".to_string()).await;
assert_eq!(200, response.status().as_u16());
@ -28,22 +19,15 @@ async fn subscribe_returns_a_200_for_valid_form_data() {
#[tokio::test]
async fn subscribe_returns_a_400_when_data_is_missing() {
let app = spawn_app().await;
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"),
];
let app = spawn_app().await;
for (invalid_body, error_message) in test_cases {
let response = client
.post(&format!("{}/subscriptions", &app.address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(invalid_body)
.send()
.await
.expect("Failed to execute request.");
let response = app.post_subscriptions(invalid_body.to_string()).await;
assert_eq!(
400,
@ -56,8 +40,6 @@ async fn subscribe_returns_a_400_when_data_is_missing() {
#[tokio::test]
async fn subscribe_returns_a_400_when_fields_are_present_but_invalid() {
let app = spawn_app().await;
let client = reqwest::Client::new();
let test_cases = vec![
("name=&email=ursula_le_guin%40gmail.com", "name is empty"),
("name=le%20guin&email=", "email is empty"),
@ -65,14 +47,9 @@ async fn subscribe_returns_a_400_when_fields_are_present_but_invalid() {
("name=Ursula&email=definitely-not-an-email", "invalid email"),
];
let app = spawn_app().await;
for (invalid_body, error_message) in test_cases {
let response = client
.post(&format!("{}/subscriptions", &app.address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(invalid_body)
.send()
.await
.expect("Failed to execute request.");
let response = app.post_subscriptions(invalid_body.to_string()).await;
assert_eq!(
400,