1

我已成功将 Web 应用程序从Rocket迁移到actix-web。通过使用邮递员,我已经验证了相同的请求会产生相同的响应。然而,事实证明迁移测试有点棘手。

我的 POST 请求在运行时超时cargo test,即使应用程序在运行时只是接受并返回预期的响应就好了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'
        }
    }
}

相比之下,这是使用 Rocket 的代码库中的 POST 测试。

#[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
}
4

1 回答 1

1

解决方案很简单。事实证明,请求确实超时了cargo test。一个潜在的解决方案是将方法放入链中,或者在我的情况下更简单,通过传入标志timeout来打开我在运行应用程序时使用的相同优化。--release

于 2018-06-21T23:09:38.677 回答