intrepid_core/extract/
http_get.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
use crate::{Context, Frame, HttpFrameMeta};

use super::{Extractor, MessageFrameError, MessageMetaJson, MetaMismatchError};

/// Extract the URI of a message from a frame.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HttpGet;

impl<State> Extractor<State> for HttpGet {
    type Error = MessageFrameError;

    fn extract(frame: Frame, context: &Context<State>) -> Result<Self, Self::Error>
    where
        Self: Sized,
    {
        let MessageMetaJson(http_meta) = MessageMetaJson::<HttpFrameMeta>::extract(frame, context)?;

        if http_meta.method != "GET" {
            return Err(MetaMismatchError(http_meta.method))?;
        }

        Ok(Self)
    }
}

#[tokio::test]
async fn extracting_different_methods() -> Result<(), Box<dyn std::error::Error>> {
    use crate::HttpRequestFrame;
    use axum::http::Request;

    let request = HttpRequestFrame::from(Request::get("/test").body(axum::body::Body::default())?);

    let context = Context::<()>::default();
    let extraction = HttpGet::extract(request.into_frame().await, &context);

    assert!(extraction.is_ok());

    let failure_cases = [
        "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "CONNECT", "PATCH", "TRACE",
    ];

    for method in failure_cases {
        let request = HttpRequestFrame::from(
            Request::builder()
                .method(method)
                .uri("/test")
                .body(axum::body::Body::default())?,
        );

        let context = Context::<()>::default();
        let extraction = HttpGet::extract(request.into_frame().await, &context);

        assert!(matches!(
            extraction.unwrap_err(),
            MessageFrameError::MetaMismatch(MetaMismatchError(_))
        ));
    }

    Ok(())
}

#[test]
fn failure() -> Result<(), MessageFrameError> {
    use crate::{Error, ExtractorError};

    let context = Context::<()>::default();
    let result = HttpGet::extract_from_frame_and_state(Frame::default(), &context);

    assert!(matches!(
        result.unwrap_err(),
        Error::ExtractorError(ExtractorError::MessageFrameError(
            MessageFrameError::WrongFrame(_)
        ))
    ),);

    Ok(())
}