From bad477fbee76722b594c8dd4c7279d1b2806ceb8 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Mon, 19 Oct 2026 12:31:05 +0800 Subject: [PATCH] Add compiler and server regression tests Expose the compiler session as a library target, run core as a workspace member, and add direct typeset tests plus end-to-end HTTP tests. Coverage: examples, arXiv fixture, starred headings, rectangles, errors, page-hash cache stability, static frontend assets, project API, preview/PDF, traversal rejection, and the legacy endpoint. --- Cargo.lock | 1 + Cargo.toml | 6 + README.md | 13 ++ crates/texrra-core/Cargo.toml | 2 +- docs/STATUS.md | 5 +- src/lib.rs | 7 + src/main.rs | 3 +- tests/server.rs | 288 ++++++++++++++++++++++++++++++++++ tests/typeset.rs | 179 +++++++++++++++++++++ 9 files changed, 501 insertions(+), 3 deletions(-) create mode 100644 src/lib.rs create mode 100644 tests/server.rs create mode 100644 tests/typeset.rs diff --git a/Cargo.lock b/Cargo.lock index fe79890..615241d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -953,6 +953,7 @@ dependencies = [ "rmp-serde", "rusttype", "serde", + "serde_json", "texcraft-stdext", "texlang", "texlang-common", diff --git a/Cargo.toml b/Cargo.toml index c9cda7e..0d42be8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,9 @@ description = "Rust-native incremental LaTeX typesetting engine with a live prev name = "texrra" path = "src/main.rs" +[workspace] +members = ["crates/texrra-core"] + [dependencies] texrra-core = { path = "crates/texrra-core", features = ["serde"] } flate2 = "1.1" @@ -32,3 +35,6 @@ ttf-parser = "0.25.1" [patch."https://github.com/jamespfennell/texcraft"] texlang = { path = "vendor/texlang" } texlang-stdlib = { path = "vendor/texlang-stdlib" } + +[dev-dependencies] +serde_json = "1" diff --git a/README.md b/README.md index 2169a13..899d7c4 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,19 @@ directory is imported as the first project, so the sample document is ready to open. Edits are saved to the file inside the project and recompiled after a short pause. +## Testing + +```sh +cargo test --workspace +``` + +The suite has two layers. `tests/typeset.rs` drives `CompilerSession` directly +and checks the three examples, the arXiv Letter fixture, starred headings, box +and rule painting, error reporting, and page-hash cache stability. +`tests/server.rs` starts the real `texrra serve` binary on an ephemeral port and +checks static frontend assets, font CSS, the project API, preview/PDF responses, +path traversal rejection, and the renamed `/texrra` legacy endpoint. + ## Project API | Endpoint | Purpose | diff --git a/crates/texrra-core/Cargo.toml b/crates/texrra-core/Cargo.toml index 0521018..b874934 100644 --- a/crates/texrra-core/Cargo.toml +++ b/crates/texrra-core/Cargo.toml @@ -11,5 +11,5 @@ ttf-parser = "0.25.1" serde = { version = "1.0", features = ["derive"], optional = true } [features] -default = [] +default = ["serde"] serde = ["dep:serde", "common/serde"] diff --git a/docs/STATUS.md b/docs/STATUS.md index 3c08ded..d62dc66 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -52,5 +52,8 @@ See `docs/ROADMAP.md` for concrete implementation plans. - `examples/hello.tex`, `examples/boxes.tex`, `examples/compat.tex` compile to one A4 page each; the arXiv template project compiles to 3 Letter pages. -- `cargo fmt --check` passes; `cargo test` currently has no test cases. +- `cargo fmt --check` passes; `cargo test --workspace` (12 tests) covers the three + examples, the arXiv fixture, SVG/PDF output, project API, static frontend + assets, path traversal, the legacy `/texrra` endpoint, and page-hash cache + stability. - Warm preview: hello ~0.6ms, arXiv ~13ms (release server, page layout cached). diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..6bc747b --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,7 @@ +//! texrra engine library. +//! +//! Process, CLI, and HTTP concerns live in `src/main.rs`; this crate exposes +//! the typesetting session so tests and other frontends can drive the compiler +//! directly. + +pub mod rust_typeset; diff --git a/src/main.rs b/src/main.rs index 68d3cdf..e89f69a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,7 +9,8 @@ use std::{ use tiny_http::{Header, Method, Request, Response, Server, StatusCode}; mod projects; -mod rust_typeset; + +use texrra_engine::rust_typeset; fn main() { if let Err(error) = run() { diff --git a/tests/server.rs b/tests/server.rs new file mode 100644 index 0000000..a658850 --- /dev/null +++ b/tests/server.rs @@ -0,0 +1,288 @@ +//! End-to-end HTTP tests for the `texrra serve` binary. +//! +//! Each test owns a temporary project/web directory and an ephemeral port, so +//! the suite can run in parallel and never touches the developer's `projects/`. + +use std::{ + fs, + io::{Read, Write}, + net::{TcpListener, TcpStream}, + path::{Path, PathBuf}, + process::{Child, Command, Stdio}, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; + +use serde_json::Value; + +struct Response { + status: u16, + headers: String, + body: Vec, +} + +impl Response { + fn text(&self) -> String { + String::from_utf8_lossy(&self.body).to_string() + } + + fn header(&self, name: &str) -> Option<&str> { + self.headers + .lines() + .find_map(|line| line.strip_prefix(&format!("{name}: "))) + } +} + +struct TestServer { + child: Child, + port: u16, + root: PathBuf, +} + +impl TestServer { + fn start(label: &str) -> Self { + let stamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("clock") + .as_nanos(); + let root = std::env::temp_dir().join(format!( + "texrra-test-{label}-{}-{stamp}", + std::process::id() + )); + let web = root.join("web"); + fs::create_dir_all(&web).expect("create web dir"); + fs::write( + web.join("index.html"), + "test-frontend

test-index

", + ) + .expect("write index"); + fs::write(web.join("styles.css"), "body { color: #123456; }").expect("write css"); + fs::write(web.join("app.js"), "console.log('test-app');").expect("write js"); + fs::copy( + Path::new(env!("CARGO_MANIFEST_DIR")).join("examples/hello.tex"), + root.join("hello.tex"), + ) + .expect("copy input"); + + let port = free_port(); + let child = Command::new(env!("CARGO_BIN_EXE_texrra")) + .arg("serve") + .arg(root.join("hello.tex")) + .arg(port.to_string()) + .current_dir(&root) + .env("TEXRRA_WEB_DIR", &web) + .env("TEXRRA_PROJECTS_DIR", root.join("projects")) + .stdout(Stdio::null()) + .stderr(Stdio::inherit()) + .spawn() + .expect("spawn texrra serve"); + let server = Self { child, port, root }; + server.wait_ready(); + server + } + + fn wait_ready(&self) { + for _ in 0..120 { + if let Ok(response) = send(self.port, "GET", "/", &[], "text/plain") { + if response.status == 200 { + return; + } + } + std::thread::sleep(Duration::from_millis(50)); + } + panic!("server on port {} did not become ready", self.port); + } + + fn request(&self, method: &str, path: &str, body: &[u8], content_type: &str) -> Response { + send(self.port, method, path, body, content_type).expect("HTTP request") + } + + fn get(&self, path: &str) -> Response { + self.request("GET", path, &[], "text/plain") + } +} + +impl Drop for TestServer { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + let _ = fs::remove_dir_all(&self.root); + } +} + +fn free_port() -> u16 { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port"); + listener.local_addr().expect("local addr").port() +} + +fn send( + port: u16, + method: &str, + path: &str, + body: &[u8], + content_type: &str, +) -> std::io::Result { + let mut stream = TcpStream::connect(("127.0.0.1", port))?; + stream.set_read_timeout(Some(Duration::from_secs(30)))?; + let mut request = + format!("{method} {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n"); + if method != "GET" || !body.is_empty() { + request.push_str(&format!( + "Content-Length: {}\r\nContent-Type: {content_type}\r\n", + body.len() + )); + } + request.push_str("\r\n"); + stream.write_all(request.as_bytes())?; + stream.write_all(body)?; + + let mut raw = Vec::new(); + stream.read_to_end(&mut raw)?; + let header_end = raw + .windows(4) + .position(|window| window == b"\r\n\r\n") + .ok_or_else(|| std::io::Error::other("missing HTTP header terminator"))?; + let headers = String::from_utf8_lossy(&raw[..header_end]).to_string(); + let status = headers + .lines() + .next() + .and_then(|line| line.split_whitespace().nth(1)) + .and_then(|status| status.parse::().ok()) + .ok_or_else(|| std::io::Error::other("missing HTTP status"))?; + let headers = headers.to_ascii_lowercase(); + let mut body = raw[header_end + 4..].to_vec(); + if headers.contains("transfer-encoding: chunked") { + body = decode_chunked(&body); + } + Ok(Response { + status, + headers, + body, + }) +} + +fn decode_chunked(body: &[u8]) -> Vec { + let mut decoded = Vec::new(); + let mut rest = body; + loop { + let Some(line_end) = rest.windows(2).position(|window| window == b"\r\n") else { + break; + }; + let size_text = std::str::from_utf8(&rest[..line_end]) + .ok() + .and_then(|line| line.split(';').next()) + .map(str::trim) + .unwrap_or(""); + let Ok(size) = usize::from_str_radix(size_text, 16) else { + break; + }; + rest = &rest[line_end + 2..]; + if size == 0 { + break; + } + if rest.len() < size { + break; + } + decoded.extend_from_slice(&rest[..size]); + rest = &rest[size..]; + if rest.starts_with(b"\r\n") { + rest = &rest[2..]; + } + } + decoded +} + +#[test] +fn serves_frontend_assets_and_fonts() { + let server = TestServer::start("assets"); + + let index = server.get("/"); + assert_eq!(index.status, 200); + assert!(index.text().contains("test-frontend")); + assert_eq!( + index.header("content-type"), + Some("text/html; charset=utf-8") + ); + + let styles = server.get("/styles.css"); + assert_eq!(styles.status, 200); + assert_eq!( + styles.header("content-type"), + Some("text/css; charset=utf-8") + ); + assert!(styles.text().contains("#123456")); + + let script = server.get("/app.js"); + assert_eq!(script.status, 200); + assert_eq!( + script.header("content-type"), + Some("text/javascript; charset=utf-8") + ); + assert!(script.text().contains("test-app")); + + let fonts = server.get("/fonts.css"); + assert_eq!(fonts.status, 200); + assert!(fonts.text().contains("TexrraSerif")); + + let missing = server.get("/missing.txt"); + assert_eq!(missing.status, 404); +} + +#[test] +fn serves_project_api_preview_and_pdf() { + let server = TestServer::start("api"); + + let projects = server.get("/api/projects"); + assert_eq!(projects.status, 200); + let value: Value = serde_json::from_slice(&projects.body).expect("projects JSON"); + let listed = value["projects"] + .as_array() + .expect("projects array") + .iter() + .any(|project| project["id"] == "hello"); + assert!(listed, "seeded hello project missing: {value}"); + + let raw = server.get("/api/projects/hello/raw?path=hello.tex"); + assert_eq!(raw.status, 200); + assert!(raw.text().contains("\\documentclass")); + + let preview = server.request( + "POST", + "/api/projects/hello/preview", + &[], + "application/json", + ); + assert_eq!(preview.status, 200); + let value: Value = serde_json::from_slice(&preview.body).expect("preview JSON"); + assert_eq!(value["status"], "ok", "{}", value["message"]); + assert_eq!(value["pages"].as_array().map(Vec::len), Some(1)); + assert!((value["pageWidthMm"].as_f64().unwrap() - 210.0).abs() < 0.1); + + let pdf = server.request("POST", "/api/projects/hello/pdf", &[], "application/pdf"); + assert_eq!(pdf.status, 200); + assert!(pdf.body.starts_with(b"%PDF-"), "missing PDF header"); +} + +#[test] +fn rejects_static_path_traversal() { + let server = TestServer::start("traversal"); + let encoded = server.get("/%2e%2e/hello.tex"); + assert_eq!(encoded.status, 404); + let plain = server.get("/assets/../../hello.tex"); + assert_eq!(plain.status, 404); +} + +#[test] +fn legacy_texrra_endpoint_renders_html_and_old_name_is_gone() { + let server = TestServer::start("legacy"); + let source = + b"\\documentclass{article}\n\\begin{document}\nLegacy endpoint.\n\\end{document}\n"; + let response = server.request("POST", "/texrra", source, "text/plain; charset=utf-8"); + assert_eq!(response.status, 200); + assert_eq!( + response.header("content-type"), + Some("text/html; charset=utf-8") + ); + + let old = server.request("POST", "/texcraft", source, "text/plain; charset=utf-8"); + assert_eq!(old.status, 404); +} diff --git a/tests/typeset.rs b/tests/typeset.rs new file mode 100644 index 0000000..c3712dd --- /dev/null +++ b/tests/typeset.rs @@ -0,0 +1,179 @@ +//! Compiler-session regression tests. +//! +//! These tests drive the same public `CompilerSession` API used by the HTTP +//! server, so they cover parsing, layout, SVG serialization, and PDF painting +//! without network or process setup. + +use std::path::PathBuf; + +use serde_json::Value; +use texrra_engine::rust_typeset::CompilerSession; + +fn preview(session: &mut CompilerSession, source: &str, file_name: &str) -> Value { + let json = session + .preview_json(source, file_name) + .unwrap_or_else(|error| panic!("preview failed for {file_name}: {error}")); + serde_json::from_str(&json).unwrap_or_else(|error| panic!("invalid preview JSON: {error}")) +} + +fn fresh_preview(source: &str, file_name: &str) -> Value { + preview(&mut CompilerSession::default(), source, file_name) +} + +fn pages(value: &Value) -> &Vec { + value["pages"] + .as_array() + .unwrap_or_else(|| panic!("preview has no pages array: {value}")) +} + +fn number(value: &Value, key: &str) -> f64 { + value[key] + .as_f64() + .unwrap_or_else(|| panic!("preview has no numeric {key}: {value}")) +} + +fn page_svg(value: &Value, index: usize) -> String { + pages(value)[index]["svg"] + .as_str() + .unwrap_or_else(|| panic!("page {index} has no SVG")) + .to_string() +} + +#[test] +fn examples_compile_to_one_a4_page() { + let examples = [ + ("hello.tex", include_str!("../examples/hello.tex")), + ("boxes.tex", include_str!("../examples/boxes.tex")), + ("compat.tex", include_str!("../examples/compat.tex")), + ]; + for (name, source) in examples { + let value = fresh_preview(source, name); + assert_eq!(value["status"], "ok", "{name}: {value}"); + assert_eq!(pages(&value).len(), 1, "{name} page count"); + assert!( + (number(&value, "pageWidthMm") - 210.0).abs() < 0.1, + "{name} width" + ); + assert!( + (number(&value, "pageHeightMm") - 297.0).abs() < 0.1, + "{name} height" + ); + } +} + +#[test] +fn hello_compiles_to_pdf() { + let source = include_str!("../examples/hello.tex"); + let pdf = CompilerSession::default() + .compile(source, "hello.tex") + .expect("hello PDF"); + assert!(pdf.starts_with(b"%PDF-"), "missing PDF header"); + assert!( + pdf.len() > 10_000, + "suspiciously small PDF: {} bytes", + pdf.len() + ); +} + +#[test] +fn arxiv_fixture_is_three_letter_pages() { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("fixtures") + .join("arxiv-template") + .join("template.tex"); + let source = std::fs::read_to_string(&path).expect("read arXiv fixture"); + let file_name = path.to_string_lossy().to_string(); + let value = fresh_preview(&source, &file_name); + assert_eq!(value["status"], "ok", "{}", value["message"]); + assert_eq!(pages(&value).len(), 3, "arXiv page count"); + assert!( + (number(&value, "pageWidthMm") - 215.9).abs() < 0.1, + "Letter width" + ); + assert!( + (number(&value, "pageHeightMm") - 279.4).abs() < 0.1, + "Letter height" + ); +} + +#[test] +fn starred_headings_are_unnumbered() { + let source = r#"\documentclass{article} +\begin{document} +\section*{Starred Heading} +\section{Numbered Heading} +\end{document} +"#; + let value = fresh_preview(source, "headings.tex"); + assert_eq!(value["status"], "ok", "{}", value["message"]); + let svg = page_svg(&value, 0); + assert!(!svg.contains("1 *"), "starred heading was numbered: {svg}"); + assert!(svg.contains("Star"), "starred heading text missing"); + assert!(svg.contains("Number"), "numbered heading text missing"); +} + +#[test] +fn box_and_rule_material_paints_rectangles() { + let source = r#"\documentclass{article} +\begin{document} +\fbox{\rule{10mm}{5mm}} +\hrule width 20mm height 2pt +\end{document} +"#; + let value = fresh_preview(source, "rectangles.tex"); + assert_eq!(value["status"], "ok", "{}", value["message"]); + let svg = page_svg(&value, 0); + // Page background, fbox frame, the 10mm black rule, and the 20mm hrule. + assert!( + svg.matches("= 4, + "expected four rectangles: {svg}" + ); + assert!( + svg.contains("stroke=\"#000000\""), + "fbox frame is not stroked" + ); + assert!(svg.contains("width=\"10."), "10mm rule missing"); + assert!(svg.contains("width=\"20."), "20mm hrule missing"); +} + +#[test] +fn undefined_commands_report_an_error() { + let source = r#"\documentclass{article} +\begin{document} +\notacommand +\end{document} +"#; + let error = CompilerSession::default() + .preview_json(source, "bad.tex") + .expect_err("undefined command should fail"); + assert!( + error.contains("undefined control sequence"), + "unexpected error: {error}" + ); +} + +#[test] +fn repeated_previews_reuse_stable_page_hashes() { + let mut session = CompilerSession::default(); + let first_source = r#"\documentclass{article} +\begin{document} +First document. +\end{document} +"#; + let second_source = r#"\documentclass{article} +\begin{document} +Second document. +\end{document} +"#; + let first = preview(&mut session, first_source, "cache.tex"); + let second = preview(&mut session, second_source, "cache.tex"); + let again = preview(&mut session, first_source, "cache.tex"); + assert_eq!(first["status"], "ok"); + assert_eq!(second["status"], "ok"); + assert_eq!(again["status"], "ok"); + assert_eq!(first["pages"], again["pages"], "cache returned stale pages"); + assert_ne!( + first["pages"][0]["hash"], second["pages"][0]["hash"], + "different sources produced the same page hash" + ); +}