zero-to-axum/tests/subscriptions.rs
azdle ef3cc5a11b only confirmed users can login
Also uses a forked version of `maik` that supports getting mail bodies.
2025-07-25 12:20:02 -05:00

62 lines
1.6 KiB
Rust

pub mod fixture;
use fixture::TestServer;
use anyhow::Result;
use regex::Regex;
use test_log::test as traced;
#[traced(tokio::test)]
async fn subscribe_succeeds_with_valid_input() -> Result<()> {
let server = TestServer::spawn().await;
let client = reqwest::Client::builder().build()?;
// Subscribe
let resp = client
.post(server.url("/subscriptions"))
.header("Content-Type", "application/x-www-form-urlencoded")
.body("name=le%20guin&email=ursula_le_guin%40gmail.com")
.send()
.await?;
assert_eq!(resp.status(), 200, "subscribe succeeds");
let mail = server.mock_smtp_server.receive_mail().expect("recv mail");
let link_regex =
Regex::new(r"http\:\/\/localhost\/subscriptions/confirm/\?token\=[a-zA-Z0-9]+")?;
let link = link_regex
.find(&mail.body)
.expect("find link in body")
.as_str();
println!("link: {link}");
server.shutdown().await
}
#[traced(tokio::test)]
async fn subscribe_fails_with_missing_data() -> Result<()> {
let server = TestServer::spawn().await;
let client = reqwest::Client::new();
let test_cases = [
("", "missing both name and email"),
("name=le%20guin", "missing the email"),
];
for (body, msg) in test_cases {
let resp = client
.post(server.url("/subscriptions"))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(body)
.send()
.await?;
assert_eq!(
resp.status(),
422,
"subscribe fails with bad request when {msg}"
);
}
server.shutdown().await
}