mithril_common/test_utils/
apispec.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
//! Tools to helps validate conformity to an OpenAPI specification

use glob::glob;
use jsonschema::Validator;
use reqwest::Url;
use serde::Serialize;
use serde_json::{json, Value, Value::Null};

use warp::http::Response;
use warp::http::StatusCode;
use warp::hyper::body::Bytes;

use crate::era::SupportedEra;

/// APISpec helps validate conformity to an OpenAPI specification
pub struct APISpec<'a> {
    openapi: Value,
    path: Option<&'a str>,
    method: Option<&'a str>,
    content_type: Option<&'a str>,
}

impl<'a> APISpec<'a> {
    /// Verify conformity helper of API Specs
    pub fn verify_conformity(
        spec_files: Vec<String>,
        method: &str,
        path: &str,
        content_type: &str,
        request_body: &impl Serialize,
        response: &Response<Bytes>,
        status_code: &StatusCode,
    ) -> Result<(), String> {
        if spec_files.is_empty() {
            return Err(
                "OpenAPI need a spec file to validate conformity. None were given.".to_string(),
            );
        }

        for spec_file in spec_files {
            if let Err(e) = APISpec::from_file(&spec_file)
                .method(method)
                .path(path)
                .content_type(content_type)
                .validate_request(request_body)
                .and_then(|api| api.validate_response(response))
                .and_then(|api| api.validate_status(response, status_code))
            {
                return Err(format!(
                    "OpenAPI invalid response in {spec_file} on route {path}, reason: {e}\nresponse: {response:#?}"
                ));
            }
        }
        Ok(())
    }

    /// APISpec factory from spec
    pub fn from_file(path: &str) -> APISpec<'a> {
        let yaml_spec = std::fs::read_to_string(path).unwrap();
        let openapi: serde_json::Value = serde_yaml::from_str(&yaml_spec).unwrap();
        APISpec {
            openapi,
            path: None,
            method: None,
            content_type: Some("application/json"),
        }
    }

    /// Sets the path to specify/check.
    pub fn path(&'a mut self, path: &'a str) -> &'a mut APISpec<'a> {
        self.path = Some(path);
        self
    }

    /// Sets the method to specify/check.
    pub fn method(&'a mut self, method: &'a str) -> &'a mut APISpec<'a> {
        self.method = Some(method);
        self
    }

    /// Sets the content type to specify/check, note that it defaults to "application/json".
    pub fn content_type(&'a mut self, content_type: &'a str) -> &'a mut APISpec<'a> {
        self.content_type = Some(content_type);
        self
    }

    /// Validates if a request is valid
    fn validate_request(
        &'a self,
        request_body: &impl Serialize,
    ) -> Result<&'a APISpec<'a>, String> {
        let path = self.path.unwrap();
        let method = self.method.unwrap().to_lowercase();
        let content_type = self.content_type.unwrap();

        let openapi_path_entry = path.split('?').next().unwrap();
        let operation_object = &self.openapi["paths"][openapi_path_entry][method];

        self.validate_query_parameters(path, operation_object)?;

        let request_schema = &operation_object["requestBody"]["content"][content_type]["schema"];
        let value = &json!(&request_body);
        self.validate_conformity(value, request_schema)
    }

    fn validate_query_parameters(
        &'a self,
        path: &str,
        operation_object: &Value,
    ) -> Result<&'a APISpec<'a>, String> {
        let fake_base_url = "http://0.0.0.1";
        let url = Url::parse(&format!("{}{}", fake_base_url, path)).unwrap();

        check_query_parameter_limitations(&url, operation_object);

        let mut query_pairs = url.query_pairs();
        if let Some(parameter) = query_pairs.next() {
            let spec_parameter = &operation_object["parameters"][0];
            let spec_parameter_name = &spec_parameter["name"].as_str().unwrap();
            let spec_parameter_in = &spec_parameter["in"].as_str().unwrap();
            if spec_parameter_in.eq(&"query") && spec_parameter_name.eq(&parameter.0) {
                Ok(self)
            } else {
                Err(format!("Unexpected query parameter '{}'", parameter.0))
            }
        } else {
            Ok(self)
        }
    }

    /// Validates if the status is the expected one
    fn validate_status(
        &'a self,
        response: &Response<Bytes>,
        expected_status_code: &StatusCode,
    ) -> Result<&'a APISpec<'a>, String> {
        if expected_status_code.as_u16() != response.status().as_u16() {
            return Err(format!(
                "expected status code {} but was {}",
                expected_status_code.as_u16(),
                response.status().as_u16(),
            ));
        }

        Ok(self)
    }

    /// Validates if a response is valid
    fn validate_response(&'a self, response: &Response<Bytes>) -> Result<&'a APISpec<'a>, String> {
        let body = response.body();
        let status = response.status();

        let path = self.path.unwrap();
        let path = path.split('?').next().unwrap();
        let method = self.method.unwrap().to_lowercase();
        let content_type = self.content_type.unwrap();
        let mut openapi = self.openapi.clone();

        let response_spec = {
            match &mut openapi["paths"][path][&method]["responses"] {
                Null => None,
                responses_spec => {
                    let status_code = status.as_str();
                    if responses_spec
                        .as_object()
                        .unwrap()
                        .contains_key(status_code)
                    {
                        Some(&responses_spec[status_code])
                    } else {
                        Some(&responses_spec["default"])
                    }
                }
            }
        };
        match response_spec {
            Some(response_spec) => {
                let response_schema = match &response_spec["content"] {
                    Null => &Null,
                    content => {
                        if content[content_type] == Null {
                            return Err(format!(
                                "Expected content type '{}' but spec is '{}'",
                                content_type, response_spec["content"],
                            ));
                        }
                        &content[content_type]["schema"]
                    }
                };
                if body.is_empty() {
                    match response_schema.as_object() {
                        Some(_) => Err("Non empty body expected".to_string()),
                        None => Ok(self),
                    }
                } else {
                    match response_schema.as_object() {
                        Some(_) => match &serde_json::from_slice(body) {
                            Ok(value) => self.validate_conformity(value, response_schema),
                            Err(_) => Err(format!("Expected a valid json but got: {body:?}")),
                        },
                        None => Err(format!("Expected empty body but got: {body:?}")),
                    }
                }
            }
            None => Err(format!(
                "Unmatched path and method: {path} {}",
                method.to_uppercase()
            )),
        }
    }

    /// Validates conformity of a value against a schema
    fn validate_conformity(
        &'a self,
        value: &Value,
        schema: &Value,
    ) -> Result<&'a APISpec<'a>, String> {
        match schema {
            Null => match value {
                Null => Ok(self),
                _ => Err(format!("Expected nothing but got: {value:?}")),
            },
            _ => {
                let mut schema = schema.as_object().unwrap().clone();
                let components = self.openapi["components"].clone();
                schema.insert(String::from("components"), components);

                let validator = Validator::new(&json!(schema)).unwrap();
                let errors = validator
                    .iter_errors(value)
                    .map(|e| e.to_string())
                    .collect::<Vec<String>>();
                if errors.is_empty() {
                    Ok(self)
                } else {
                    Err(errors.join(", "))
                }
            }
        }
    }

    /// Get default spec file
    pub fn get_default_spec_file() -> String {
        "../openapi.yaml".to_string()
    }

    /// Get spec file for era
    pub fn get_era_spec_file(era: SupportedEra) -> String {
        format!("../openapi-{}", era)
    }

    /// Get all spec files
    pub fn get_all_spec_files() -> Vec<String> {
        APISpec::get_all_spec_files_from("..")
    }

    /// Get all spec files in the directory
    pub fn get_all_spec_files_from(root_path: &str) -> Vec<String> {
        let mut open_api_spec_files = Vec::new();
        for entry in glob(&format!("{}/openapi*.yaml", root_path)).unwrap() {
            let entry_path = entry.unwrap().to_str().unwrap().to_string();
            open_api_spec_files.push(entry_path.clone());
            open_api_spec_files.push(entry_path);
        }

        open_api_spec_files
    }

    /// Verify that examples are conform to the type definition.
    pub fn verify_examples(&self) -> Vec<String> {
        self.verify_examples_value("", &self.openapi)
    }

    fn verify_examples_value(&self, path_to_value: &str, root_value: &Value) -> Vec<String> {
        let mut errors: Vec<String> = vec![];

        errors.append(&mut self.verify_example_conformity(path_to_value, root_value));

        if let Some(object) = root_value.as_object() {
            for (value_key, value) in object {
                errors.append(
                    &mut self.verify_examples_value(&format!("{path_to_value} {value_key}"), value),
                );
            }
        }

        if let Some(array) = root_value.as_array() {
            for value in array {
                errors
                    .append(&mut self.verify_examples_value(&format!("{path_to_value}[?]"), value));
            }
        }

        errors
    }

    fn verify_example_conformity(&self, name: &str, component: &Value) -> Vec<String> {
        if let Some(example) = component.get("example") {
            // The type definition is at the same level as the example (components) unless there is a schema property (paths).
            let component_definition = component.get("schema").unwrap_or(component);

            let result = self.validate_conformity(example, component_definition);
            if let Err(e) = result {
                return vec![format!(
                    "- {}: Error\n    {}\n    Example: {}\n",
                    name, e, example
                )];
            }
        }

        vec![]
    }
}

// TODO: For now, it verifies only one parameter,
// should verify with multiple query parameters using an openapi.yaml file for test.
fn check_query_parameter_limitations(url: &Url, operation_object: &Value) {
    if url.query_pairs().count() >= 2 {
        panic!("This method does not work with multiple parameters");
    }

    if let Some(parameters) = operation_object["parameters"].as_array() {
        let len = parameters
            .iter()
            .filter(|p| p["in"].eq("query"))
            .collect::<Vec<_>>()
            .len();
        if len >= 2 {
            panic!("This method does not work with multiple parameters");
        }
    }
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::path::{Path, PathBuf};
    use warp::http::Method;
    use warp::http::StatusCode;

    use super::*;
    use crate::entities;
    use crate::messages::{AggregatorFeaturesMessage, SignerMessagePart};
    use crate::test_utils::{fake_data, TempDir};

    fn build_empty_response(status_code: u16) -> Response<Bytes> {
        Response::builder()
            .status(status_code)
            .body(Bytes::new())
            .unwrap()
    }

    fn build_json_response<T: Serialize>(status_code: u16, value: T) -> Response<Bytes> {
        Response::builder()
            .status(status_code)
            .body(Bytes::from(json!(value).to_string().into_bytes()))
            .unwrap()
    }

    fn build_response(status_code: u16, content: &'static [u8]) -> Response<Bytes> {
        Response::builder()
            .status(status_code)
            .body(Bytes::from_static(content))
            .unwrap()
    }

    fn get_temp_dir(dir_name: &str) -> PathBuf {
        TempDir::create("apispec", dir_name)
    }

    fn get_temp_openapi_filename(name: &str, id: u32) -> PathBuf {
        get_temp_dir(&format!("{name}-{id}")).join("openapi.yaml")
    }

    fn write_minimal_open_api_file(
        version: &str,
        path: &Path,
        openapi_paths: &str,
        openapi_components: &str,
    ) {
        fs::write(
            path,
            format!(
                r#"openapi: "3.0.0"
info:
  version: {version}
  title: Minimal Open Api File

paths:
{openapi_paths}

components:
  schemas:
{openapi_components}
"#
            ),
        )
        .unwrap()
    }

    /// To check that the example is verified,
    /// we create an openapi.yaml with an invalid example.
    /// If the example is verified, we should have an error message.
    /// A simple invalid example is one with a wrong type (string instead of integer)
    fn check_example_error_is_detected(
        id: u32,
        paths: &str,
        components: &str,
        expected_error_message: &str,
    ) {
        let file = get_temp_openapi_filename("example", id);

        write_minimal_open_api_file("1.0.0", &file, paths, components);

        let api_spec = APISpec::from_file(file.to_str().unwrap());
        let errors: Vec<String> = api_spec.verify_examples();

        assert_eq!(1, errors.len());
        let error_message = errors.first().unwrap();
        assert!(
            error_message.contains(expected_error_message),
            "Error message: {:?}\nshould contains: {}\n",
            errors,
            expected_error_message
        );
    }

    #[test]
    fn test_validate_a_response_without_body() {
        let file = get_temp_openapi_filename("validate_a_response_without_body", line!());
        let paths = r#"
        /empty-route:
            get:
                responses:
                    "204":
                        description: no pending certificate available
        "#;
        write_minimal_open_api_file("1.0.0", &file, paths, "");

        APISpec::from_file(file.to_str().unwrap())
            .method(Method::GET.as_str())
            .path("/empty-route")
            .validate_request(&Null)
            .unwrap()
            .validate_response(&build_empty_response(204))
            .unwrap();
    }

    #[test]
    fn test_validate_ok_when_request_without_body_and_expects_response() {
        APISpec::from_file(&APISpec::get_default_spec_file())
            .method(Method::GET.as_str())
            .path("/")
            .validate_request(&Null)
            .unwrap()
            .validate_response(&build_json_response(
                200,
                AggregatorFeaturesMessage::dummy(),
            ))
            .unwrap();
    }

    #[test]
    fn test_validate_ok_when_request_with_body_and_expects_no_response() {
        assert!(APISpec::from_file(&APISpec::get_default_spec_file())
            .method(Method::POST.as_str())
            .path("/register-signer")
            .validate_request(&SignerMessagePart::dummy())
            .unwrap()
            .validate_response(&Response::<Bytes>::new(Bytes::new()))
            .is_err());
    }

    #[test]
    fn test_validate_ok_when_response_match_default_status_code() {
        // INTERNAL_SERVER_ERROR(500) is not one of the defined status code
        // for this route, so it's the default response spec that is used.
        let response = build_json_response(
            StatusCode::INTERNAL_SERVER_ERROR.into(),
            entities::ServerError::new("an error occurred".to_string()),
        );

        APISpec::from_file(&APISpec::get_default_spec_file())
            .method(Method::POST.as_str())
            .path("/register-signer")
            .validate_response(&response)
            .unwrap();
    }

    #[test]
    fn test_should_fail_when_the_status_code_is_not_the_expected_one() {
        let response = build_json_response(
            StatusCode::INTERNAL_SERVER_ERROR.into(),
            entities::ServerError::new("an error occurred".to_string()),
        );

        let mut api_spec = APISpec::from_file(&APISpec::get_default_spec_file());
        let result = api_spec
            .method(Method::GET.as_str())
            .path("/")
            .validate_request(&Null)
            .unwrap()
            .validate_status(&response, &StatusCode::OK);

        assert!(result.is_err());
        assert_eq!(
            result.err().unwrap().to_string(),
            format!(
                "expected status code {} but was {}",
                StatusCode::OK.as_u16(),
                StatusCode::INTERNAL_SERVER_ERROR.as_u16()
            )
        );
    }

    #[test]
    fn test_should_be_ok_when_the_status_code_is_the_right_one() {
        let response = build_json_response(
            StatusCode::INTERNAL_SERVER_ERROR.into(),
            entities::ServerError::new("an error occurred".to_string()),
        );

        APISpec::from_file(&APISpec::get_default_spec_file())
            .method(Method::GET.as_str())
            .path("/")
            .validate_request(&Null)
            .unwrap()
            .validate_status(&response, &StatusCode::INTERNAL_SERVER_ERROR)
            .unwrap();
    }

    #[test]
    fn test_validate_returns_error_when_route_does_not_exist() {
        let mut api_spec = APISpec::from_file(&APISpec::get_default_spec_file());
        let result = api_spec
            .method(Method::GET.as_str())
            .path("/route-not-existing-in-openapi-spec")
            .validate_response(&build_response(200, b"abcdefgh"));

        assert!(result.is_err());
        assert_eq!(
            result.err(),
            Some("Unmatched path and method: /route-not-existing-in-openapi-spec GET".to_string())
        );
    }

    #[test]
    fn test_validate_returns_error_when_route_exists_but_method_does_not() {
        let mut api_spec = APISpec::from_file(&APISpec::get_default_spec_file());
        let result = api_spec
            .method(Method::OPTIONS.as_str())
            .path("/certificates")
            .validate_response(&build_response(200, b"abcdefgh"));

        assert!(result.is_err());
        assert_eq!(
            result.err(),
            Some("Unmatched path and method: /certificates OPTIONS".to_string())
        );
    }
    #[test]
    fn test_validate_returns_error_when_route_exists_but_expects_non_empty_response() {
        let mut api_spec = APISpec::from_file(&APISpec::get_default_spec_file());
        let result = api_spec
            .method(Method::GET.as_str())
            .path("/certificates")
            .validate_response(&build_empty_response(200));

        assert!(result.is_err());
        assert_eq!(result.err(), Some("Non empty body expected".to_string()));
    }

    #[test]
    fn test_validate_returns_error_when_route_exists_but_expects_empty_response() {
        {
            let mut api_spec = APISpec::from_file(&APISpec::get_default_spec_file());
            let result = api_spec
                .method(Method::POST.as_str())
                .path("/register-signer")
                .validate_response(&build_response(201, b"abcdefgh"));

            assert!(result.is_err());
            assert_eq!(
                result.err(),
                Some("Expected empty body but got: b\"abcdefgh\"".to_string())
            );
        }
        {
            let mut api_spec = APISpec::from_file(&APISpec::get_default_spec_file());
            let result = api_spec
                .method(Method::POST.as_str())
                .path("/register-signer")
                .validate_response(&build_json_response(201, "something"));

            assert!(result.is_err());
            assert_eq!(
                result.err(),
                Some("Expected empty body but got: b\"\\\"something\\\"\"".to_string())
            );
        }
    }

    #[test]
    fn test_validate_returns_error_when_json_is_not_valid() {
        let mut api_spec = APISpec::from_file(&APISpec::get_default_spec_file());
        let result = api_spec
            .method(Method::GET.as_str())
            .path("/certificates")
            .validate_request(&Null)
            .unwrap()
            .validate_response(&build_response(200, b"not a json"));
        assert_eq!(
            result.err(),
            Some("Expected a valid json but got: b\"not a json\"".to_string())
        );
    }

    #[test]
    fn test_validate_returns_errors_when_route_exists_but_does_not_expect_request_body() {
        assert!(APISpec::from_file(&APISpec::get_default_spec_file())
            .method(Method::GET.as_str())
            .path("/certificates")
            .validate_request(&fake_data::beacon())
            .is_err());
    }
    #[test]
    fn test_validate_returns_error_when_route_exists_but_expects_non_empty_request_body() {
        assert!(APISpec::from_file(&APISpec::get_default_spec_file())
            .method(Method::POST.as_str())
            .path("/register-signer")
            .validate_request(&Null)
            .is_err());
    }

    #[test]
    fn test_validate_returns_error_when_content_type_does_not_exist() {
        let mut api_spec = APISpec::from_file(&APISpec::get_default_spec_file());
        let result = api_spec
            .method(Method::GET.as_str())
            .path("/certificates")
            .content_type("whatever")
            .validate_request(&Null)
            .unwrap()
            .validate_response(&build_empty_response(200));

        assert!(result.is_err());
        assert_eq!(
            result.err().unwrap().to_string(),
            "Expected content type 'whatever' but spec is '{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/CertificateListMessage\"}}}'",
        );
    }

    #[test]
    fn test_validate_a_response_with_query_parameters() {
        APISpec::from_file(&APISpec::get_default_spec_file())
            .method(Method::GET.as_str())
            .path("/proof/cardano-transaction?transaction_hashes={hash}")
            .validate_request(&Null)
            .unwrap()
            .validate_response(&build_empty_response(404))
            .map(|_apispec| ())
            .unwrap();
    }

    #[test]
    fn test_validate_a_request_with_wrong_query_parameter_name() {
        let mut api_spec = APISpec::from_file(&APISpec::get_default_spec_file());
        let result = api_spec
            .method(Method::GET.as_str())
            .path("/proof/cardano-transaction?whatever=123")
            .validate_request(&Null);

        assert!(result.is_err());
        assert_eq!(
            result.err().unwrap().to_string(),
            "Unexpected query parameter 'whatever'",
        );
    }

    #[test]
    fn test_validate_a_request_should_failed_when_query_parameter_is_in_path() {
        let mut api_spec = APISpec::from_file(&APISpec::get_default_spec_file());
        let result = api_spec
            .method(Method::GET.as_str())
            .path("/artifact/cardano-transaction/{hash}?hash=456")
            .validate_request(&Null);

        assert!(result.is_err());
        assert_eq!(
            result.err().unwrap().to_string(),
            "Unexpected query parameter 'hash'",
        );
    }

    #[test]
    fn test_validate_query_parameters_with_correct_parameter_name() {
        let api_spec = APISpec::from_file(&APISpec::get_default_spec_file());
        api_spec
            .validate_query_parameters(
                "/proof/cardano-transaction?transaction_hashes=a123,b456",
                &api_spec.openapi["paths"]["/proof/cardano-transaction"]["get"],
            )
            .map(|_apispec| ())
            .unwrap()
    }

    #[test]
    fn test_validate_query_parameters_with_wrong_query_parameter_name() {
        let api_spec = APISpec::from_file(&APISpec::get_default_spec_file());
        let result = api_spec.validate_query_parameters(
            "/proof/cardano-transaction?whatever=123",
            &api_spec.openapi["paths"]["/proof/cardano-transaction"]["get"],
        );

        assert!(result.is_err());
        assert_eq!(
            result.err().unwrap().to_string(),
            "Unexpected query parameter 'whatever'",
        );
    }

    #[test]
    fn test_verify_conformity_with_expected_status() {
        APISpec::verify_conformity(
            APISpec::get_all_spec_files(),
            Method::GET.as_str(),
            "/",
            "application/json",
            &Null,
            &build_json_response(200, AggregatorFeaturesMessage::dummy()),
            &StatusCode::OK,
        )
        .unwrap()
    }

    #[test]
    fn test_verify_conformity_with_non_expected_status_returns_error() {
        let response = build_json_response(200, AggregatorFeaturesMessage::dummy());

        let spec_file = APISpec::get_default_spec_file();
        let result = APISpec::verify_conformity(
            vec![spec_file.clone()],
            Method::GET.as_str(),
            "/",
            "application/json",
            &Null,
            &response,
            &StatusCode::BAD_REQUEST,
        );

        let error_reason = format!(
            "expected status code {} but was {}",
            StatusCode::BAD_REQUEST.as_u16(),
            StatusCode::OK.as_u16()
        );
        let error_message = format!(
            "OpenAPI invalid response in {spec_file} on route /, reason: {error_reason}\nresponse: {response:#?}"
        );
        assert!(result.is_err());
        assert_eq!(result.err().unwrap().to_string(), error_message);
    }

    #[test]
    fn test_verify_conformity_when_no_spec_file_returns_error() {
        let result = APISpec::verify_conformity(
            vec![],
            Method::GET.as_str(),
            "/",
            "application/json",
            &Null,
            &build_json_response(200, AggregatorFeaturesMessage::dummy()),
            &StatusCode::OK,
        );

        assert!(result.is_err());
        assert_eq!(
            result.err().unwrap().to_string(),
            "OpenAPI need a spec file to validate conformity. None were given."
        );
    }

    #[test]
    fn test_get_all_spec_files_not_empty() {
        let spec_files = APISpec::get_all_spec_files();
        assert!(!spec_files.is_empty());
        assert!(spec_files.contains(&APISpec::get_default_spec_file()))
    }

    #[test]
    fn test_example_is_verified_on_object() {
        let components = r#"
        MyComponent:
            type: object
            properties:
                id:
                    type: integer
            example:
                {
                    "id": "abc",
                }
        "#;
        check_example_error_is_detected(
            line!(),
            "",
            components,
            "\"abc\" is not of type \"integer\"",
        );
    }

    #[test]
    fn test_example_is_verified_on_array() {
        let components = r#"
        MyComponent:
            type: array
            items:
                type: integer
            example:
                [
                    "abc"
                ]
      "#;
        check_example_error_is_detected(
            line!(),
            "",
            components,
            "\"abc\" is not of type \"integer\"",
        );
    }

    #[test]
    fn test_example_is_verified_on_array_item() {
        let components = r#"
        MyComponent:
            type: array
            items:
                type: integer
                example: 
                    "abc"
        "#;
        check_example_error_is_detected(
            line!(),
            "",
            components,
            "\"abc\" is not of type \"integer\"",
        );
    }

    #[test]
    fn test_example_is_verified_on_parameter() {
        let paths = r#"
        /my_route:
            get:
                parameters:
                    -   name: id
                        in: path
                        schema:
                            type: integer
                        example: "abc"
        "#;
        check_example_error_is_detected(line!(), paths, "", "\"abc\" is not of type \"integer\"");
    }

    #[test]
    fn test_example_is_verified_on_array_parameter() {
        let paths = r#"
        /my_route:
            get:
                parameters:
                    -   name: id
                        in: path
                        schema:
                            type: array
                            items:
                                type: integer
                        example: 
                            [
                                "abc"
                            ]
        "#;
        check_example_error_is_detected(line!(), paths, "", "\"abc\" is not of type \"integer\"");
    }

    #[test]
    fn test_example_is_verified_on_array_parameter_schema() {
        let paths = r#"
        /my_route:
            get:
                parameters:
                    -   name: id
                        in: path
                        schema:
                            type: array
                            items:
                                type: integer
                            example: 
                                [
                                    "abc"
                                ]
        "#;
        check_example_error_is_detected(line!(), paths, "", "\"abc\" is not of type \"integer\"");
    }

    #[test]
    fn test_example_is_verified_on_array_parameter_item() {
        let paths = r#"
        /my_route:
            get:
                parameters:
                    -   name: id
                        in: path
                        schema:
                            type: array
                            items:
                                type: integer
                                example: 
                                    "abc"
        "#;
        check_example_error_is_detected(line!(), paths, "", "\"abc\" is not of type \"integer\"");
    }

    #[test]
    fn test_example_is_verified_on_referenced_component() {
        let paths = r#"
        /my_route:
            get:
                parameters:
                    -   name: id
                        in: path
                        schema:
                            $ref: '#/components/schemas/MyComponent'
                        example: "abc"
        "#;
        let components = r#"
        MyComponent:
            type: integer
        "#;

        check_example_error_is_detected(
            line!(),
            paths,
            components,
            "\"abc\" is not of type \"integer\"",
        );
    }
}