Reputation: 6251
I've successfully migrated a web application from Rocket to actix-web. By utilizing postman, I've verified that the same requests yield the same responses. Migrating the tests however has been proven to be a little bit more tricky.
My POST requests time out when running cargo test
, even though the application just accepts and returns the expected response just fine when running cargo run
.
#[cfg(test)]
mod test {
use actix_web::{client, http, test, App};
#[test]
fn main() {
let mut ts = TestSuite::new();
assert!(ts.get_request("/health").status().is_success()); // works
let filter_test_body =
r#"{"key_1":[{"id":"a string"},{"id":"another string"}],"int_1":100}"#;
assert!(
ts.post_request("/post_route", filter_test_body)
.status()
.is_success()
); // times out while actual app returns success with same payload within a few ms
}
fn create_app() -> App<project_name::AppState> {
// {...} some initialization and defining app_state
return App::with_state(&app_state)
.resource("/health", |r| {
r.method(http::Method::GET).f(project_name::health)
})
.resource("/post_route", |r| {
r.method(http::Method::POST)
.with(project_name::post_route_handler)
});
}
struct TestSuite {
server: test::TestServer,
}
impl TestSuite {
pub fn new() -> TestSuite {
TestSuite {
server: test::TestServer::with_factory(create_app),
}
}
pub fn get_request(&mut self, endpoint: &str) -> client::ClientResponse {
let request = self.server
.client(http::Method::GET, endpoint)
.finish()
.unwrap();
self.server.execute(request.send()).unwrap()
}
pub fn post_request(&mut self, endpoint: &str, body: &str) -> client::ClientResponse {
let request_payload: other_lib::request::RequestPayload =
serde_json::from_str(body).unwrap();
let request = self.server
.client(http::Method::POST, endpoint)
.header(http::header::CONTENT_TYPE, "application/json")
.json(request_payload)
//.body(body.to_string())
.unwrap();
self.server.execute(request.send()).unwrap() // thread 'test::main' panicked at 'called `Result::unwrap()` on an `Err` value: Timeout'
}
}
}
In contrast, here's the POST test from the codebase utilizing Rocket.
#[test]
fn test_filters() {
let client = mount_test_rocket(); // getting access to the test server (rocket::local::Client)
let mut response = client.post("/post_route").header(ContentType::JSON)
.body(r#"{"key_1":[{"id":"a string"},{"id":"another string"}],"int_1":100}"#).dispatch();
assert_eq!(response.status(), Status::Ok);
// + more assertions looking into the actual response body
}
Upvotes: 1
Views: 826
Reputation: 6251
The solution is a simple one. Turns out, the request does really time out on cargo test
. A potential solution would be to get in the timeout
method into the chain, or much simpler in my case, turn on the same optimization that I use when running the application by passing in the --release
flag.
Upvotes: 1