Red test.

This commit is contained in:
LukeMathWalker 2021-03-08 21:10:59 +00:00
parent 0ad3b4429a
commit f4b066b487
2 changed files with 30 additions and 0 deletions

View file

@ -1,5 +1,6 @@
use sqlx::{Connection, Executor, PgConnection, PgPool};
use uuid::Uuid;
use wiremock::MockServer;
use zero2prod::configuration::{get_configuration, DatabaseSettings};
use zero2prod::startup::{get_connection_pool, Application};
use zero2prod::telemetry::{get_subscriber, init_subscriber};
@ -16,6 +17,7 @@ lazy_static::lazy_static! {
pub struct TestApp {
pub address: String,
pub db_pool: PgPool,
pub email_server: MockServer,
}
impl TestApp {
@ -31,6 +33,9 @@ impl TestApp {
}
pub async fn spawn_app() -> TestApp {
// Launch a mock server to stand in for Postmark's API
let email_server = MockServer::start().await;
// Randomise configuration to ensure test isolation
let configuration = {
let mut c = get_configuration().expect("Failed to read configuration.");
@ -38,6 +43,8 @@ pub async fn spawn_app() -> TestApp {
c.database.database_name = Uuid::new_v4().to_string();
// Use a random OS port
c.application.port = 0;
// Use the mock server as email API
c.email_client.base_url = email_server.uri();
c
};
@ -56,6 +63,7 @@ pub async fn spawn_app() -> TestApp {
db_pool: get_connection_pool(&configuration.database)
.await
.expect("Failed to connect to the database"),
email_server,
}
}

View file

@ -1,4 +1,6 @@
use crate::helpers::spawn_app;
use wiremock::matchers::{method, path};
use wiremock::{Mock, ResponseTemplate};
#[actix_rt::test]
async fn subscribe_returns_a_200_for_valid_form_data() {
@ -21,6 +23,26 @@ async fn subscribe_returns_a_200_for_valid_form_data() {
assert_eq!(saved.name, "le guin");
}
#[actix_rt::test]
async fn subscribe_sends_a_confirmation_email_for_valid_data() {
// Arrange
let app = spawn_app().await;
let body = "name=le%20guin&email=ursula_le_guin%40gmail.com";
Mock::given(path("/email"))
.and(method("POST"))
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&app.email_server)
.await;
// Act
app.post_subscriptions(body.into()).await;
// Assert
// Mock asserts on drop
}
#[actix_rt::test]
async fn subscribe_returns_a_400_when_data_is_missing() {
// Arrange