Skip to main content

nitr_http/testing/
unit.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6//! Unit-testing a handler without a server: a real request userdata built
7//! from a table ([`fake_request`], `t.fake_request`), and the application
8//! compiled into the test state ([`load_app`], `t.app()`).
9//!
10//! Both are unit-test tools and say so: a fake request passes no
11//! protection layer, no body guard and no route validation (`valid` is
12//! whatever the test says), and `app:dispatch` runs the composed
13//! middleware chain only — `on_error`, `on_invalid` and `input` are what
14//! `t.request` exercises.
15
16use http_body_util::{BodyExt as _, Full};
17use hyper::Method;
18use hyper::body::Bytes;
19use mlua::{AnyUserData, Function, Lua, Table, UserData, UserDataMethods, Value};
20
21use super::TestRequest;
22use crate::app::{self, AppState, Lookup};
23use crate::request::LuaRequest;
24
25/// Builds a request userdata for a unit test (`t.fake_request(spec)`):
26/// the same type a handler receives, so `req.*`, `req:json()`,
27/// `nitr.session(req, ...)`, `nitr.csrf.token(req)` and `nitr.auth.*`
28/// behave as in production.
29///
30/// `spec` takes `method` (default `GET`), `path` (default `/`), `params`
31/// (what the router would have captured), `valid` (what route validation
32/// would have produced), plus every [`TestRequest`] option — `query`,
33/// `headers`, `cookies`, `auth`, one body, `remote_addr`.
34///
35/// # Errors
36///
37/// A malformed spec: two bodies, a bad method, path, header or address.
38pub fn fake_request(lua: &Lua, spec: Option<Table>) -> mlua::Result<AnyUserData> {
39    let (method, path) = match &spec {
40        Some(spec) => (
41            spec.get::<Option<String>>("method")?
42                .unwrap_or_else(|| "GET".into()),
43            spec.get::<Option<String>>("path")?
44                .unwrap_or_else(|| "/".into()),
45        ),
46        None => ("GET".into(), "/".into()),
47    };
48    let parsed = TestRequest::from_lua(&method, &path, spec.as_ref())?;
49    let method: Method = parsed
50        .method
51        .to_uppercase()
52        .parse()
53        .map_err(|_| mlua::Error::RuntimeError(format!("invalid method `{method}`")))?;
54    let mut builder = hyper::Request::builder()
55        .method(method)
56        .uri(parsed.path.as_str());
57    for (name, value) in &parsed.headers {
58        builder = builder.header(name, value);
59    }
60    let req = builder
61        .body(
62            Full::new(parsed.body.unwrap_or_else(Bytes::new))
63                .map_err(|never| match never {})
64                .boxed(),
65        )
66        .map_err(|err| mlua::Error::RuntimeError(format!("invalid fake request: {err}")))?;
67    let peer = parsed
68        .remote_addr
69        .unwrap_or_else(|| super::DEFAULT_PEER.into());
70    let id = uuid::Uuid::now_v7().to_string();
71    let mut req = LuaRequest::synthetic(req, peer, id.into());
72    if let Some(spec) = &spec {
73        if let Some(params) = spec.get::<Option<Table>>("params")? {
74            let mut pairs = Vec::new();
75            for pair in params.pairs::<String, String>() {
76                pairs.push(pair?);
77            }
78            pairs.sort();
79            req.params = pairs;
80        }
81        req.valid = spec.get::<Option<Table>>("valid")?;
82    }
83    lua.create_userdata(req)
84}
85
86/// Compiles the application into this state and returns the object
87/// `t.app()` hands a test.
88///
89/// The same evaluation and compile the pool performs, into this state's
90/// registry only: nothing the server serves changes. The handler script's
91/// top-level code and every `app:use` factory run once more here.
92///
93/// # Errors
94///
95/// Anything that fails the application's own load.
96pub fn load_app(lua: &Lua, cfg: &crate::Config) -> nitr_core::Result<AnyUserData> {
97    app::register_nitr_app(lua)?;
98    app::load(
99        lua,
100        &cfg.handler_script,
101        &[],
102        &crate::server::input_env(cfg),
103    )?;
104    Ok(lua.create_userdata(TestApp)?)
105}
106
107/// `t.app()`: reads the compiled application from the state's registry.
108struct TestApp;
109
110/// The compiled application in this state (`load_app` put it there).
111fn compiled_state(lua: &Lua) -> mlua::Result<AnyUserData> {
112    app::state(lua).map_err(|err| mlua::Error::RuntimeError(err.to_string()))
113}
114
115fn method_of(name: &str) -> mlua::Result<Method> {
116    name.to_uppercase()
117        .parse()
118        .map_err(|_| mlua::Error::RuntimeError(format!("invalid method `{name}`")))
119}
120
121/// A response table like the ones the server's own answers carry.
122fn plain(lua: &Lua, status: u16, allow: Option<&[Method]>, body: &str) -> mlua::Result<Table> {
123    let resp = lua.create_table()?;
124    resp.set("status", status)?;
125    let headers = lua.create_table()?;
126    if let Some(allow) = allow {
127        let mut names: Vec<&str> = allow.iter().map(Method::as_str).collect();
128        names.sort_unstable();
129        headers.set("allow", names.join(", "))?;
130    }
131    resp.set("headers", headers)?;
132    resp.set("body", body)?;
133    Ok(resp)
134}
135
136impl UserData for TestApp {
137    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
138        // app:handler(method, path) — the route's own function, without
139        // its middleware. `path` is the pattern as registered
140        // ("/notes/:id"), or a concrete path the router matches.
141        methods.add_method("handler", |lua, _, (method, path): (String, String)| {
142            let wanted = method_of(&method)?;
143            let state = compiled_state(lua)?;
144            let state = state.borrow::<AppState>()?;
145            let compiled = &state.dispatch.0;
146            if let Some(chain) = compiled
147                .chains
148                .iter()
149                .find(|c| c.method == wanted && c.path == path)
150            {
151                return Ok(chain.handler.clone());
152            }
153            if let Lookup::Route { index, .. } = compiled.lookup(&wanted, &path) {
154                return Ok(compiled.chains[index].handler.clone());
155            }
156            let known = compiled
157                .chains
158                .iter()
159                .map(|c| format!("{} {}", c.method, c.path))
160                .collect::<Vec<_>>()
161                .join(", ");
162            Err(mlua::Error::RuntimeError(format!(
163                "app:handler: no route {wanted} {path} (routes: {known})"
164            )))
165        });
166
167        // app:dispatch(method, path, req) — the router lookup the server
168        // uses (params filled into `req`) and the composed middleware
169        // chain; the router's own 404/405/OPTIONS answers otherwise.
170        methods.add_async_method(
171            "dispatch",
172            |lua, _, (method, path, req): (String, String, AnyUserData)| async move {
173                let wanted = method_of(&method)?;
174                let chain: Function = {
175                    let state = compiled_state(&lua)?;
176                    let state = state.borrow::<AppState>()?;
177                    let compiled = &state.dispatch.0;
178                    match compiled.lookup(&wanted, &path) {
179                        Lookup::Route { index, params } => {
180                            req.borrow_mut::<LuaRequest>()
181                                .map_err(|_| {
182                                    mlua::Error::RuntimeError(
183                                        "app:dispatch takes a request (t.fake_request(...))".into(),
184                                    )
185                                })?
186                                .params = params;
187                            compiled.chains[index].fns.clone()
188                        }
189                        Lookup::NotFound => {
190                            return Ok(Value::Table(plain(&lua, 404, None, "Not Found")?));
191                        }
192                        Lookup::MethodNotAllowed(allowed) => {
193                            return Ok(Value::Table(plain(
194                                &lua,
195                                405,
196                                Some(&allowed),
197                                "Method Not Allowed",
198                            )?));
199                        }
200                        Lookup::Options(allowed) => {
201                            return Ok(Value::Table(plain(&lua, 204, Some(&allowed), "")?));
202                        }
203                    }
204                };
205                chain.call_async::<Value>(req).await
206            },
207        );
208
209        // app:routes() — { { method, path, file, line }, ... } in
210        // registration order.
211        methods.add_method("routes", |lua, _, ()| {
212            let state = compiled_state(lua)?;
213            let state = state.borrow::<AppState>()?;
214            let list = lua.create_table()?;
215            for chain in &state.dispatch.0.chains {
216                let route = lua.create_table()?;
217                route.set("method", chain.method.as_str())?;
218                route.set("path", chain.path.as_str())?;
219                if let Some((file, line)) = &chain.site {
220                    route.set("file", file.as_str())?;
221                    route.set("line", *line)?;
222                }
223                list.push(route)?;
224            }
225            Ok(list)
226        });
227    }
228}