use poem::{http::StatusCode, test::TestClient, Error};
use poem_openapi::{
param::Query,
payload::{Json, Response},
ApiResponse, OpenApi, OpenApiService,
};
#[tokio::test]
async fn response_wrapper() {
#[derive(ApiResponse, Debug, Eq, PartialEq)]
#[oai(bad_request_handler = "bad_request_handler")]
#[allow(dead_code)]
pub enum CustomApiResponse {
#[oai(status = 200)]
Ok,
#[oai(status = 400)]
BadRequest(#[oai(header = "MY-HEADER1")] String),
}
fn bad_request_handler(_: Error) -> CustomApiResponse {
CustomApiResponse::BadRequest("def".to_string())
}
struct Api;
#[OpenApi]
impl Api {
#[oai(path = "/a", method = "get")]
async fn a(&self) -> Response<Json<i32>> {
Response::new(Json(100)).header("myheader", "abc")
}
#[oai(path = "/b", method = "get")]
async fn b(&self, p1: Query<String>) -> Response<CustomApiResponse> {
Response::new(CustomApiResponse::Ok).header("myheader", p1.0)
}
}
let ep = OpenApiService::new(Api, "test", "1.0");
let cli = TestClient::new(ep);
let resp = cli.get("/a").send().await;
resp.assert_status_is_ok();
resp.assert_header("myheader", "abc");
let resp = cli.get("/b").query("p1", &"qwe").send().await;
resp.assert_status_is_ok();
resp.assert_header("myheader", "qwe");
let resp = cli.get("/b").send().await;
resp.assert_status(StatusCode::BAD_REQUEST);
resp.assert_header("MY-HEADER1", "def");
}