rapina 0.8.0

A fast, type-safe web framework for Rust inspired by FastAPI
Documentation
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
//! Test client for integration testing Rapina applications.

use std::net::SocketAddr;
use std::sync::Arc;

use bytes::Bytes;
use http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode};
use http_body_util::{BodyExt, Full};
use hyper::Request;
use hyper::body::Incoming;
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper_util::client::legacy::Client;
use hyper_util::rt::TokioIo;
use serde::{Serialize, de::DeserializeOwned};
use tokio::net::TcpListener;
use tokio::sync::oneshot;

use crate::context::RequestContext;
use crate::middleware::MiddlewareStack;
use crate::router::Router;
use crate::state::AppState;

/// A test client for making HTTP requests to a Rapina application.
///
/// The test client spawns a lightweight HTTP server on a random port
/// and provides a convenient API for making requests and asserting responses.
///
/// # Examples
///
/// ```ignore
/// use rapina::prelude::*;
/// use rapina::testing::TestClient;
///
/// #[tokio::test]
/// async fn test_hello() {
///     let app = Rapina::new()
///         .router(Router::new().route(http::Method::GET, "/", |_, _, _| async { "Hello!" }));
///
///     let client = TestClient::new(app).await;
///     let response = client.get("/").send().await;
///
///     assert_eq!(response.status(), StatusCode::OK);
///     assert_eq!(response.text(), "Hello!");
/// }
/// ```
pub struct TestClient {
    addr: SocketAddr,
    client: Client<hyper_util::client::legacy::connect::HttpConnector, Full<Bytes>>,
    _shutdown: oneshot::Sender<()>,
}

impl TestClient {
    /// Creates a new test client from a Rapina application.
    ///
    /// This spawns a background server on a random available port.
    pub async fn new(app: crate::app::Rapina) -> Self {
        let app = app.prepare();
        Self::from_parts(app.router, app.state, app.middlewares).await
    }

    /// Creates a test client from router, state, and middlewares.
    pub async fn from_parts(router: Router, state: AppState, middlewares: MiddlewareStack) -> Self {
        let router = Arc::new(router);
        let state = Arc::new(state);
        let middlewares = Arc::new(middlewares);

        // Bind to a random available port
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();

        // Create shutdown channel
        let (shutdown_tx, mut shutdown_rx) = oneshot::channel();

        // Spawn the server
        tokio::spawn(async move {
            loop {
                tokio::select! {
                    result = listener.accept() => {
                        match result {
                            Ok((stream, _)) => {
                                let io = TokioIo::new(stream);
                                let router = router.clone();
                                let state = state.clone();
                                let middlewares = middlewares.clone();

                                tokio::spawn(async move {
                                    let service = service_fn(move |mut req: Request<Incoming>| {
                                        let router = router.clone();
                                        let state = state.clone();
                                        let middlewares = middlewares.clone();

                                        let ctx = RequestContext::new();
                                        req.extensions_mut().insert(ctx.clone());

                                        async move {
                                            let response = middlewares.execute(req, &router, &state, &ctx).await;
                                            Ok::<_, std::convert::Infallible>(response)
                                        }
                                    });

                                    let _ = http1::Builder::new()
                                        .serve_connection(io, service)
                                        .await;
                                });
                            }
                            Err(_) => break,
                        }
                    }
                    _ = &mut shutdown_rx => {
                        break;
                    }
                }
            }
        });

        let client = Client::builder(hyper_util::rt::TokioExecutor::new()).build_http();

        Self {
            addr,
            client,
            _shutdown: shutdown_tx,
        }
    }

    /// Creates a GET request builder.
    pub fn get(&self, path: &str) -> TestRequestBuilder<'_> {
        self.request(Method::GET, path)
    }

    /// Creates a POST request builder.
    pub fn post(&self, path: &str) -> TestRequestBuilder<'_> {
        self.request(Method::POST, path)
    }

    /// Creates a PUT request builder.
    pub fn put(&self, path: &str) -> TestRequestBuilder<'_> {
        self.request(Method::PUT, path)
    }

    /// Creates a DELETE request builder.
    pub fn delete(&self, path: &str) -> TestRequestBuilder<'_> {
        self.request(Method::DELETE, path)
    }

    /// Creates a PATCH request builder.
    pub fn patch(&self, path: &str) -> TestRequestBuilder<'_> {
        self.request(Method::PATCH, path)
    }

    /// Creates a request builder with the given method and path.
    pub fn request(&self, method: Method, path: &str) -> TestRequestBuilder<'_> {
        TestRequestBuilder::new(self, method, path)
    }

    /// Returns the address the test server is listening on.
    pub fn addr(&self) -> SocketAddr {
        self.addr
    }
}

/// Builder for constructing test requests.
pub struct TestRequestBuilder<'a> {
    client: &'a TestClient,
    method: Method,
    path: String,
    headers: HeaderMap,
    body: Bytes,
}

impl<'a> TestRequestBuilder<'a> {
    fn new(client: &'a TestClient, method: Method, path: &str) -> Self {
        Self {
            client,
            method,
            path: path.to_string(),
            headers: HeaderMap::new(),
            body: Bytes::new(),
        }
    }

    /// Adds a header to the request.
    pub fn header(mut self, key: &str, value: &str) -> Self {
        self.headers.insert(
            HeaderName::from_bytes(key.as_bytes()).unwrap(),
            HeaderValue::from_str(value).unwrap(),
        );
        self
    }

    /// Sets a JSON body on the request.
    pub fn json<T: Serialize>(mut self, body: &T) -> Self {
        self.body = Bytes::from(serde_json::to_vec(body).unwrap());
        self.headers.insert(
            http::header::CONTENT_TYPE,
            HeaderValue::from_static("application/json"),
        );
        self
    }

    /// Sets a form body on the request.
    pub fn form<T: Serialize>(mut self, body: &T) -> Self {
        self.body = Bytes::from(serde_urlencoded::to_string(body).unwrap());
        self.headers.insert(
            http::header::CONTENT_TYPE,
            HeaderValue::from_static("application/x-www-form-urlencoded"),
        );
        self
    }

    /// Sets raw body bytes.
    pub fn body(mut self, body: impl Into<Bytes>) -> Self {
        self.body = body.into();
        self
    }

    /// Sends the request and returns the response.
    pub async fn send(self) -> TestResponse {
        let uri = format!("http://{}{}", self.client.addr, self.path);

        let mut builder = Request::builder().method(self.method).uri(&uri);

        for (key, value) in self.headers.iter() {
            builder = builder.header(key, value);
        }

        let request = builder.body(Full::new(self.body)).unwrap();

        let response = self.client.client.request(request).await.unwrap();

        let status = response.status();
        let headers = response.headers().clone();
        let body = response.into_body().collect().await.unwrap().to_bytes();

        TestResponse {
            status,
            headers,
            body,
        }
    }
}

/// Response from a test request.
pub struct TestResponse {
    status: StatusCode,
    headers: HeaderMap,
    body: Bytes,
}

impl TestResponse {
    /// Returns the HTTP status code.
    pub fn status(&self) -> StatusCode {
        self.status
    }

    /// Returns the response headers.
    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }

    /// Returns the response body as text.
    pub fn text(&self) -> String {
        String::from_utf8_lossy(&self.body).to_string()
    }

    /// Returns the response body as raw bytes.
    pub fn bytes(&self) -> &Bytes {
        &self.body
    }

    /// Deserializes the response body as JSON.
    pub fn json<T: DeserializeOwned>(&self) -> T {
        serde_json::from_slice(&self.body).unwrap()
    }

    /// Attempts to deserialize the response body as JSON.
    pub fn try_json<T: DeserializeOwned>(&self) -> Result<T, serde_json::Error> {
        serde_json::from_slice(&self.body)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::Rapina;

    #[tokio::test]
    async fn test_client_get() {
        let app = Rapina::new()
            .with_introspection(false)
            .router(Router::new().route(http::Method::GET, "/", |_, _, _| async { "Hello!" }));

        let client = TestClient::new(app).await;
        let response = client.get("/").send().await;

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(response.text(), "Hello!");
    }

    #[tokio::test]
    async fn test_client_post_json() {
        let app = Rapina::new()
            .with_introspection(false)
            .router(
                Router::new().route(http::Method::POST, "/echo", |req, _, _| async move {
                    use http_body_util::BodyExt;
                    let body = req.into_body().collect().await.unwrap().to_bytes();
                    String::from_utf8_lossy(&body).to_string()
                }),
            );

        let client = TestClient::new(app).await;
        let response = client
            .post("/echo")
            .json(&serde_json::json!({"name": "test"}))
            .send()
            .await;

        assert_eq!(response.status(), StatusCode::OK);
        assert!(response.text().contains("test"));
    }

    #[tokio::test]
    async fn test_client_with_headers() {
        let app = Rapina::new()
            .with_introspection(false)
            .router(
                Router::new().route(http::Method::GET, "/headers", |req, _, _| async move {
                    let auth = req
                        .headers()
                        .get("authorization")
                        .map(|v| v.to_str().unwrap_or(""))
                        .unwrap_or("");
                    auth.to_string()
                }),
            );

        let client = TestClient::new(app).await;
        let response = client
            .get("/headers")
            .header("authorization", "Bearer token123")
            .send()
            .await;

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(response.text(), "Bearer token123");
    }

    #[tokio::test]
    async fn test_client_not_found() {
        let app = Rapina::new()
            .with_introspection(false)
            .router(Router::new());

        let client = TestClient::new(app).await;
        let response = client.get("/nonexistent").send().await;

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_client_json_response() {
        let app = Rapina::new()
            .with_introspection(false)
            .router(
                Router::new().route(http::Method::GET, "/json", |_, _, _| async {
                    http::Response::builder()
                        .status(StatusCode::OK)
                        .header("content-type", "application/json")
                        .body(http_body_util::Full::new(bytes::Bytes::from(
                            r#"{"id":1,"name":"test"}"#,
                        )))
                        .unwrap()
                }),
            );

        let client = TestClient::new(app).await;
        let response = client.get("/json").send().await;

        assert_eq!(response.status(), StatusCode::OK);

        #[derive(serde::Deserialize, Debug, PartialEq)]
        struct Data {
            id: i32,
            name: String,
        }

        let data: Data = response.json();
        assert_eq!(data.id, 1);
        assert_eq!(data.name, "test");
    }

    #[tokio::test]
    async fn test_client_with_state() {
        use std::sync::Arc;

        #[derive(Clone)]
        struct AppConfig {
            name: String,
        }

        let app = Rapina::new()
            .with_introspection(false)
            .state(AppConfig {
                name: "TestApp".to_string(),
            })
            .router(Router::new().route(
                http::Method::GET,
                "/config",
                |_, _, state: Arc<AppState>| async move {
                    let config = state.get::<AppConfig>().unwrap();
                    config.name.clone()
                },
            ));

        let client = TestClient::new(app).await;
        let response = client.get("/config").send().await;

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(response.text(), "TestApp");
    }

    #[tokio::test]
    async fn test_client_put() {
        let app = Rapina::new()
            .with_introspection(false)
            .router(
                Router::new().route(Method::PUT, "/resource", |_, _, _| async {
                    StatusCode::NO_CONTENT
                }),
            );

        let client = TestClient::new(app).await;
        let response = client.put("/resource").send().await;

        assert_eq!(response.status(), StatusCode::NO_CONTENT);
    }

    #[tokio::test]
    async fn test_client_delete() {
        let app = Rapina::new()
            .with_introspection(false)
            .router(
                Router::new().route(Method::DELETE, "/resource", |_, _, _| async {
                    StatusCode::NO_CONTENT
                }),
            );

        let client = TestClient::new(app).await;
        let response = client.delete("/resource").send().await;

        assert_eq!(response.status(), StatusCode::NO_CONTENT);
    }

    #[tokio::test]
    async fn test_response_bytes() {
        let app = Rapina::new()
            .with_introspection(false)
            .router(
                Router::new().route(http::Method::GET, "/bytes", |_, _, _| async { "raw bytes" }),
            );

        let client = TestClient::new(app).await;
        let response = client.get("/bytes").send().await;

        assert_eq!(response.bytes(), &Bytes::from("raw bytes"));
    }

    #[tokio::test]
    async fn test_client_addr() {
        let app = Rapina::new()
            .with_introspection(false)
            .router(Router::new());

        let client = TestClient::new(app).await;
        let addr = client.addr();

        assert!(addr.port() > 0);
        assert_eq!(addr.ip().to_string(), "127.0.0.1");
    }
}