mod.rs
⎇
Raw
1//! Shared integration-test harness: drives the real router with
2//! `tower::ServiceExt::oneshot` — no ports, no network, fully parallel.
3//
4// Every test binary compiles this module privately, so helpers unused by a
5// particular binary would warn as dead code.
6#![allow(dead_code)]
7
8use std::collections::BTreeMap;
9use std::sync::Arc;
10
11use axum::Router;
12use axum::body::Body;
13use axum::http::{HeaderMap, Method, StatusCode, header};
14use http_body_util::BodyExt;
15use server::db::Db;
16use server::error::AppState;
17use tower::ServiceExt;
18
19// ---------------------------------------------------------------------------
20// Environment
21// ---------------------------------------------------------------------------
22
23/// A server with a small fixture tree:
24///
25/// ```text
26/// root/
27/// docs/
28/// inner/
29/// hello.txt ("hello world")
30/// a.txt ("file a")
31/// src/
32/// main.rs
33/// config.json
34/// notes.md
35/// editme.txt ("v1")
36/// blob.bin (64 bytes)
37/// ```
38pub struct Env {
39 pub root: tempfile::TempDir,
40 pub state: Arc<AppState>,
41 pub app: Router,
42 /// Kept alive so the thumbnail cache folder outlives the server.
43 pub cache: Option<tempfile::TempDir>,
44}
45
46impl Env {
47 pub async fn new() -> Self {
48 Self::build(false, true).await
49 }
50
51 /// Same fixtures, plus a thumbnail cache in a temp folder.
52 pub async fn with_thumbs() -> Self {
53 Self::build(true, true).await
54 }
55
56 /// A thumbnail cache with ffmpeg reported as missing, so the no-video
57 /// branch can be exercised on a machine that has it.
58 pub async fn without_ffmpeg() -> Self {
59 Self::build(true, false).await
60 }
61
62 async fn build(thumbs: bool, ffmpeg: bool) -> Self {
63 let root = tempfile::tempdir().unwrap();
64 let p = root.path();
65 std::fs::create_dir_all(p.join("docs/inner")).unwrap();
66 std::fs::create_dir_all(p.join("src")).unwrap();
67 std::fs::write(p.join("docs/inner/hello.txt"), "hello world").unwrap();
68 std::fs::write(p.join("docs/a.txt"), "file a").unwrap();
69 std::fs::write(p.join("src/main.rs"), "fn main() {}").unwrap();
70 std::fs::write(p.join("config.json"), "{\"k\": 1}").unwrap();
71 std::fs::write(p.join("notes.md"), "# notes").unwrap();
72 std::fs::write(p.join("editme.txt"), "v1").unwrap();
73 std::fs::write(p.join("blob.bin"), (0..64u8).collect::<Vec<_>>()).unwrap();
74
75 // In-memory SQLite: no temp files, no WAL, faster than file-backed.
76 let db = Db::open_in_memory().await.unwrap();
77 let cache = match thumbs {
78 true => Some(tempfile::tempdir().unwrap()),
79 false => None,
80 };
81 let thumbs = match &cache {
82 Some(d) => Some(Arc::new(
83 server::thumb::Thumbs::with_ffmpeg(d.path().to_path_buf(), ffmpeg)
84 .await
85 .unwrap(),
86 )),
87 None => None,
88 };
89 let state = Arc::new(AppState {
90 db,
91 root: p.canonicalize().unwrap(),
92 root_name: server::root_file_name(p),
93 https: false,
94 thumbs,
95 });
96 let app = server::api::router(state.clone());
97 Self {
98 root,
99 state,
100 app,
101 cache,
102 }
103 }
104
105 /// Absolute path of a fixture file inside the root.
106 pub fn file(&self, rel: &str) -> std::path::PathBuf {
107 self.root.path().join(rel)
108 }
109
110 /// Create an admin account (first boot) and return a signed-in client.
111 pub async fn admin(&self) -> Client {
112 let c = Client::new(self.app.clone());
113 let r = c
114 .post_json(
115 "/api/auth/setup",
116 &serde_json::json!({ "name": "admin", "password": "admin1234" }),
117 )
118 .await;
119 assert_eq!(r.status, StatusCode::OK, "setup failed: {}", r.text());
120 let token = session_cookie(&r).expect("setup must set a session cookie");
121 let mut c = Client::new(self.app.clone());
122 c.set_cookie(&token);
123 c
124 }
125}
126
127// ---------------------------------------------------------------------------
128// Client
129// ---------------------------------------------------------------------------
130
131#[derive(Clone)]
132pub struct Client {
133 app: Router,
134 pub cookie: Option<String>,
135}
136
137pub struct Resp {
138 pub status: StatusCode,
139 pub headers: HeaderMap,
140 pub body: Vec<u8>,
141}
142
143impl Resp {
144 pub fn json(&self) -> serde_json::Value {
145 serde_json::from_slice(&self.body).unwrap_or_else(|e| {
146 panic!(
147 "body is not JSON ({e}):\n{}",
148 String::from_utf8_lossy(&self.body)
149 )
150 })
151 }
152
153 pub fn text(&self) -> String {
154 String::from_utf8_lossy(&self.body).into_owned()
155 }
156
157 pub fn header(&self, name: &str) -> Option<String> {
158 self.headers
159 .get(name)
160 .and_then(|v| v.to_str().ok())
161 .map(str::to_string)
162 }
163}
164
165impl Client {
166 pub fn new(app: Router) -> Self {
167 Self { app, cookie: None }
168 }
169
170 pub fn set_cookie(&mut self, token: &str) {
171 self.cookie = Some(token.to_string());
172 }
173
174 pub async fn raw(
175 &self,
176 method: Method,
177 path: &str,
178 extra_headers: &[(&str, &str)],
179 body: Vec<u8>,
180 ) -> Resp {
181 let mut b = axum::http::Request::builder().method(method).uri(path);
182 for (k, v) in extra_headers {
183 b = b.header(*k, *v);
184 }
185 if let Some(c) = &self.cookie {
186 b = b.header(header::COOKIE, format!("fbng_session={c}"));
187 }
188 let req = b
189 .body(Body::from(body))
190 .unwrap_or_else(|e| panic!("bad request: {e}"));
191 let res = self
192 .app
193 .clone()
194 .oneshot(req)
195 .await
196 .unwrap_or_else(|e| panic!("request failed: {e}"));
197 let status = res.status();
198 let headers = res.headers().clone();
199 let bytes = res.into_body().collect().await.unwrap().to_bytes();
200 Resp {
201 status,
202 headers,
203 body: bytes.to_vec(),
204 }
205 }
206
207 pub async fn get(&self, path: &str) -> Resp {
208 self.raw(Method::GET, path, &[], Vec::new()).await
209 }
210
211 pub async fn delete(&self, path: &str) -> Resp {
212 self.raw(Method::DELETE, path, &[], Vec::new()).await
213 }
214
215 pub async fn post_json(&self, path: &str, v: &serde_json::Value) -> Resp {
216 self.raw(
217 Method::POST,
218 path,
219 &[("content-type", "application/json")],
220 v.to_string().into_bytes(),
221 )
222 .await
223 }
224
225 pub async fn put_json(&self, path: &str, v: &serde_json::Value) -> Resp {
226 self.raw(
227 Method::PUT,
228 path,
229 &[("content-type", "application/json")],
230 v.to_string().into_bytes(),
231 )
232 .await
233 }
234
235 /// `PUT ...?action=content` (editor save).
236 pub async fn put_content(
237 &self,
238 path: &str,
239 content: &[u8],
240 expected_mtime: Option<i64>,
241 ) -> Resp {
242 let mut extra: Vec<(&str, String)> = vec![("content-type", "text/plain".to_string())];
243 if let Some(m) = expected_mtime {
244 extra.push(("x-expected-mtime", format!("{m}")));
245 }
246 let owned: Vec<(String, String)> =
247 extra.into_iter().map(|(k, v)| (k.to_string(), v)).collect();
248 let hdrs: Vec<(&str, &str)> = owned
249 .iter()
250 .map(|(k, v)| (k.as_str(), v.as_str()))
251 .collect();
252 self.raw(Method::PUT, path, &hdrs, content.to_vec()).await
253 }
254
255 /// POST a multipart upload with one file per part name.
256 pub async fn post_multipart(&self, path: &str, parts: &[(&str, &[u8])], query: &str) -> Resp {
257 let boundary = "testboundary123";
258 let (ct, body) = multipart_body(parts, boundary);
259 let full = if query.is_empty() {
260 path.to_string()
261 } else {
262 format!("{path}?{query}")
263 };
264 self.raw(Method::POST, &full, &[("content-type", &ct)], body)
265 .await
266 }
267}
268
269/// Extract the `fbng_session` cookie value from `Set-Cookie` headers.
270pub fn session_cookie(r: &Resp) -> Option<String> {
271 for v in r.headers.get_all(header::SET_COOKIE) {
272 let s = v.to_str().ok()?;
273 let first = s.split(';').next().unwrap_or("");
274 if let Some(tok) = first.strip_prefix("fbng_session=")
275 && !tok.is_empty()
276 {
277 return Some(tok.to_string());
278 }
279 }
280 None
281}
282
283/// POST /api/admin/users helper (used by several test files).
284pub async fn create_user(
285 admin: &Client,
286 name: &str,
287 password: &str,
288 roots: &[(&str, &str)],
289) -> serde_json::Value {
290 let roots_json: Vec<serde_json::Value> = roots
291 .iter()
292 .map(|(p, m)| serde_json::json!({ "path": p, "mode": m }))
293 .collect();
294 let r = admin
295 .post_json(
296 "/api/admin/users",
297 &serde_json::json!({
298 "name": name,
299 "password": password,
300 "is_admin": false,
301 "roots": roots_json,
302 }),
303 )
304 .await;
305 assert_eq!(r.status, StatusCode::OK, "create {name}: {}", r.text());
306 r.json()
307}
308
309/// Log in and return a signed-in client.
310pub async fn login(env: &Env, name: &str, password: &str) -> Client {
311 let c = Client::new(env.app.clone());
312 let r = c
313 .post_json(
314 "/api/auth/login",
315 &serde_json::json!({ "name": name, "password": password }),
316 )
317 .await;
318 assert_eq!(r.status, StatusCode::OK, "login {name}: {}", r.text());
319 let mut c = Client::new(env.app.clone());
320 c.set_cookie(&session_cookie(&r).unwrap());
321 c
322}
323
324/// Find a user id by name via the admin API.
325pub async fn user_id(admin: &Client, name: &str) -> i64 {
326 let r = admin.get("/api/admin/users").await;
327 assert_eq!(r.status, StatusCode::OK);
328 let j = r.json();
329 let users = j.as_array().unwrap();
330 users
331 .iter()
332 .find(|u| u["name"] == name)
333 .unwrap_or_else(|| panic!("user {name} not found"))
334 .as_object()
335 .unwrap()
336 .get("id")
337 .unwrap()
338 .as_i64()
339 .unwrap()
340}
341
342// ---------------------------------------------------------------------------
343// Helpers: multipart + archive readers
344// ---------------------------------------------------------------------------
345
346/// Build a minimal multipart/form-data body. Each part is a file whose
347/// `name` attribute is the (relative) target path — as the web client sends.
348pub fn multipart_body(parts: &[(&str, &[u8])], boundary: &str) -> (String, Vec<u8>) {
349 let mut buf = Vec::new();
350 for (name, content) in parts {
351 buf.extend_from_slice(format!("--{boundary}\r\n").as_bytes());
352 buf.extend_from_slice(
353 format!("Content-Disposition: form-data; name=\"{name}\"\r\n").as_bytes(),
354 );
355 buf.extend_from_slice(b"Content-Type: application/octet-stream\r\n\r\n");
356 buf.extend_from_slice(content);
357 buf.extend_from_slice(b"\r\n");
358 }
359 buf.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
360 (format!("multipart/form-data; boundary={boundary}"), buf)
361}
362
363/// Read a zip into a name → content map (files only).
364pub fn zip_map(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
365 let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("valid zip archive");
366 let mut map = BTreeMap::new();
367 for i in 0..zip.len() {
368 let mut f = zip.by_index(i).unwrap();
369 let name = f.name().unwrap().to_string();
370 if name.ends_with('/') {
371 continue;
372 }
373 let mut buf = Vec::new();
374 std::io::Read::read_to_end(&mut f, &mut buf).unwrap();
375 map.insert(name, buf);
376 }
377 map
378}
379
380/// Read a tar (optionally gz/zst compressed) into a name → content map.
381pub fn tar_map(raw: &[u8], compress: Compress) -> BTreeMap<String, Vec<u8>> {
382 let decompressed: Box<dyn std::io::Read> = match compress {
383 Compress::None => Box::new(std::io::Cursor::new(raw)),
384 Compress::Gz => Box::new(flate2::read::GzDecoder::new(std::io::Cursor::new(raw))),
385 Compress::Zst => {
386 Box::new(zstd::stream::read::Decoder::new(std::io::Cursor::new(raw)).unwrap())
387 }
388 };
389 let mut map = BTreeMap::new();
390 for entry in tar::Archive::new(decompressed).entries().unwrap() {
391 let mut e = entry.unwrap();
392 if !e.header().entry_type().is_file() {
393 continue;
394 }
395 let name = e.path().unwrap().to_string_lossy().into_owned();
396 let mut buf = Vec::new();
397 std::io::Read::read_to_end(&mut e, &mut buf).unwrap();
398 map.insert(name, buf);
399 }
400 map
401}
402
403pub enum Compress {
404 None,
405 Gz,
406 Zst,
407}
408