openapi_mocker/
server.rs

1use crate::openapi::spec::Spec;
2use actix_web::{
3    web::{self, get},
4    HttpRequest, HttpResponse, Scope,
5};
6
7/// Application state for the Actix Web server.
8pub struct AppState {
9    pub spec: Spec,
10}
11
12/// Returns a new Actix Web scope with all the routes for the server.
13pub fn get_scope() -> Scope {
14    web::scope("").default_service(get().to(handle_all))
15}
16
17async fn handle_all(req: HttpRequest, data: web::Data<AppState>) -> HttpResponse {
18    let spec = &data.spec;
19    let example = spec.get_example(&req);
20
21    match example {
22        Some(example) => HttpResponse::Ok().json(example),
23        None => HttpResponse::NotFound().finish(),
24    }
25}
26
27#[cfg(test)]
28mod tests {
29    use super::*;
30    use actix_web::{test, App};
31
32    #[actix_rt::test]
33    async fn test_request_default() {
34        let spec = Spec::from_path("tests/testdata/petstore.yaml").expect("failed to load spec");
35        let data = web::Data::new(AppState { spec });
36        let app = App::new().app_data(data.clone()).service(get_scope());
37
38        let mut app = test::init_service(app).await;
39        let req = test::TestRequest::get().uri("/pets").to_request();
40        let resp = test::call_service(&mut app, req).await;
41        println!("{:?}", resp);
42        assert!(resp.status().is_success());
43
44        let expected_res = r#"[]"#;
45        let body = test::read_body(resp).await;
46        assert_eq!(body, expected_res);
47    }
48
49    #[actix_rt::test]
50    async fn test_request_query() {
51        let spec = Spec::from_path("tests/testdata/petstore.yaml").expect("failed to load spec");
52        let data = web::Data::new(AppState { spec });
53        let app = App::new().app_data(data.clone()).service(get_scope());
54
55        let mut app = test::init_service(app).await;
56        let req = test::TestRequest::get().uri("/pets?page=1").to_request();
57        let resp = test::call_service(&mut app, req).await;
58        println!("{:?}", resp);
59        assert!(resp.status().is_success());
60
61        let expected_res =
62            r#"[{"id":1,"name":"doggie","tag":"dog"},{"id":2,"name":"kitty","tag":"cat"}]"#;
63        let body = test::read_body(resp).await;
64        assert_eq!(body, expected_res);
65    }
66
67    #[actix_rt::test]
68    async fn test_request_not_found() {
69        let spec = Spec::from_path("tests/testdata/petstore.yaml").expect("failed to load spec");
70        let data = web::Data::new(AppState { spec });
71        let app = App::new().app_data(data.clone()).service(get_scope());
72
73        let mut app = test::init_service(app).await;
74        let req = test::TestRequest::get().uri("/notfound").to_request();
75        let resp = test::call_service(&mut app, req).await;
76        assert!(resp.status().is_client_error());
77    }
78}