nitr_http/testing/
unit.rs1use 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
25pub 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
86pub 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
107struct TestApp;
109
110fn 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
121fn 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 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 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 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}