zero-to-production/tests/api/helpers.rs

130 lines
4.6 KiB
Rust
Raw Normal View History

use once_cell::sync::Lazy;
2021-02-14 12:24:50 +00:00
use sqlx::{Connection, Executor, PgConnection, PgPool};
use uuid::Uuid;
2021-03-08 21:10:59 +00:00
use wiremock::MockServer;
2021-02-14 12:24:50 +00:00
use zero2prod::configuration::{get_configuration, DatabaseSettings};
2021-02-14 16:41:45 +00:00
use zero2prod::startup::{get_connection_pool, Application};
2021-02-14 12:24:50 +00:00
use zero2prod::telemetry::{get_subscriber, init_subscriber};
// Ensure that the `tracing` stack is only initialised once using `once_cell`
static TRACING: Lazy<()> = Lazy::new(|| {
let default_filter_level = "info".to_string();
let subscriber_name = "test".to_string();
if std::env::var("TEST_LOG").is_ok() {
let subscriber = get_subscriber(subscriber_name, default_filter_level, std::io::stdout);
init_subscriber(subscriber);
} else {
let subscriber = get_subscriber(subscriber_name, default_filter_level, std::io::sink);
2021-02-14 12:24:50 +00:00
init_subscriber(subscriber);
};
});
2021-02-14 12:24:50 +00:00
pub struct TestApp {
pub address: String,
2021-03-11 09:24:57 +00:00
pub port: u16,
2021-02-14 12:24:50 +00:00
pub db_pool: PgPool,
2021-03-08 21:10:59 +00:00
pub email_server: MockServer,
2021-02-14 12:24:50 +00:00
}
2021-03-11 21:14:29 +00:00
/// Confirmation links embedded in the request to the email API.
pub struct ConfirmationLinks {
pub html: reqwest::Url,
2021-04-02 10:50:59 +00:00
pub plain_text: reqwest::Url,
2021-03-11 21:14:29 +00:00
}
2021-02-14 17:07:31 +00:00
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.")
}
2021-03-11 21:14:29 +00:00
/// Extract the confirmation links embedded in the request to the email API.
pub fn get_confirmation_links(&self, email_request: &wiremock::Request) -> ConfirmationLinks {
let body: serde_json::Value = serde_json::from_slice(&email_request.body).unwrap();
// Extract the link from one of the request fields.
let get_link = |s: &str| {
let links: Vec<_> = linkify::LinkFinder::new()
.links(s)
.filter(|l| *l.kind() == linkify::LinkKind::Url)
.collect();
assert_eq!(links.len(), 1);
let raw_link = links[0].as_str().to_owned();
let mut confirmation_link = reqwest::Url::parse(&raw_link).unwrap();
// Let's make sure we don't call random APIs on the web
assert_eq!(confirmation_link.host_str().unwrap(), "127.0.0.1");
confirmation_link.set_port(Some(self.port)).unwrap();
confirmation_link
};
let html = get_link(&body["HtmlBody"].as_str().unwrap());
let plain_text = get_link(&body["TextBody"].as_str().unwrap());
2021-04-02 10:50:59 +00:00
ConfirmationLinks { html, plain_text }
2021-03-11 21:14:29 +00:00
}
2021-02-14 17:07:31 +00:00
}
2021-02-14 12:24:50 +00:00
pub async fn spawn_app() -> TestApp {
Lazy::force(&TRACING);
2021-03-09 22:40:14 +00:00
2021-03-08 21:10:59 +00:00
// Launch a mock server to stand in for Postmark's API
let email_server = MockServer::start().await;
2021-02-14 16:27:04 +00:00
// Randomise configuration to ensure test isolation
let configuration = {
let mut c = get_configuration().expect("Failed to read configuration.");
// Use a different database for each test case
c.database.database_name = Uuid::new_v4().to_string();
// Use a random OS port
c.application.port = 0;
2021-03-08 21:10:59 +00:00
// Use the mock server as email API
c.email_client.base_url = email_server.uri();
2021-02-14 16:27:04 +00:00
c
};
2021-02-14 12:24:50 +00:00
2021-02-14 16:27:04 +00:00
// Create and migrate the database
configure_database(&configuration.database).await;
2021-02-14 12:24:50 +00:00
2021-02-14 16:27:04 +00:00
// Launch the application as a background task
2021-02-14 16:41:45 +00:00
let application = Application::build(configuration.clone())
2021-02-14 16:27:04 +00:00
.await
.expect("Failed to build application.");
2021-03-11 09:24:57 +00:00
let application_port = application.port();
2021-02-14 16:41:45 +00:00
let _ = tokio::spawn(application.run_until_stopped());
2021-02-14 12:24:50 +00:00
TestApp {
2021-03-11 09:24:57 +00:00
address: format!("http://localhost:{}", application_port),
port: application_port,
2021-02-14 16:27:04 +00:00
db_pool: get_connection_pool(&configuration.database)
.await
.expect("Failed to connect to the database"),
2021-03-08 21:10:59 +00:00
email_server,
2021-02-14 12:24:50 +00:00
}
}
2021-02-14 15:26:43 +00:00
async fn configure_database(config: &DatabaseSettings) -> PgPool {
2021-02-14 12:24:50 +00:00
// Create database
let mut connection = PgConnection::connect_with(&config.without_db())
.await
.expect("Failed to connect to Postgres");
connection
.execute(&*format!(r#"CREATE DATABASE "{}";"#, config.database_name))
.await
.expect("Failed to create database.");
// Migrate database
let connection_pool = PgPool::connect_with(config.with_db())
.await
.expect("Failed to connect to Postgres.");
sqlx::migrate!("./migrations")
.run(&connection_pool)
.await
.expect("Failed to migrate the database");
connection_pool
}