feat(test): server setup and teardown for tests
- Application server will now be setup on EVERY test and closed after that test
This commit is contained in:
parent
8d90f9e8e6
commit
cd677039b1
17
src/lib.rs
17
src/lib.rs
@ -1,16 +1,17 @@
|
|||||||
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
|
use actix_web::{web, App, HttpResponse, HttpServer};
|
||||||
|
use actix_web::dev::Server;
|
||||||
|
|
||||||
async fn healthcheck_route() -> impl Responder{
|
async fn healthcheck_route() -> HttpResponse {
|
||||||
return HttpResponse::Ok().finish()
|
return HttpResponse::Ok().finish()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn run() -> Result<Server, std::io::Error>{
|
||||||
pub async fn run() -> Result<(), std::io::Error>{
|
let server = HttpServer::new(||{
|
||||||
HttpServer::new(||{
|
|
||||||
App::new()
|
App::new()
|
||||||
.route("/healthcheck", web::get().to(healthcheck_route))
|
.route("/health_check", web::get().to(healthcheck_route))
|
||||||
})
|
})
|
||||||
.bind("127.0.0.1:8000")?
|
.bind("127.0.0.1:8000")?
|
||||||
.run()
|
.run();
|
||||||
.await
|
|
||||||
|
Ok(server)
|
||||||
}
|
}
|
||||||
|
@ -2,5 +2,7 @@ use email_newsletter_api::run;
|
|||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<(), std::io::Error>{
|
async fn main() -> Result<(), std::io::Error>{
|
||||||
run().await
|
// Move the error up the call stack
|
||||||
|
// otherwise await for the HttpServer
|
||||||
|
run()?.await
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,10 @@
|
|||||||
|
// 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
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn health_check_works(){
|
async fn health_check_works(){
|
||||||
spawn_app().await.expect("Failed to spawn our app.");
|
spawn_app();
|
||||||
|
|
||||||
let client = reqwest::Client::new();
|
let client = reqwest::Client::new();
|
||||||
|
|
||||||
@ -10,6 +14,11 @@ async fn health_check_works(){
|
|||||||
assert_eq!(Some(0), response.content_length());
|
assert_eq!(Some(0), response.content_length());
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn spawn_app() -> Result<(), std::io::Error> {
|
fn spawn_app() {
|
||||||
email_newsletter_api::run().await
|
let server = email_newsletter_api::run().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);
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user