Files
texrra-engine/tests/typeset.rs
T

1125 lines
34 KiB
Rust

//! 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> {
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("<rect").count() >= 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"
);
}
fn text_x(svg: &str, needle: &str) -> f64 {
let closing = format!("{needle}</text>");
let index = svg
.find(&closing)
.unwrap_or_else(|| panic!("missing text element containing `{needle}`"));
let start = svg[..index]
.rfind("<text ")
.unwrap_or_else(|| panic!("no text element before `{needle}`"));
let tag = &svg[start..index];
tag.split("x=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok())
.unwrap_or_else(|| panic!("text element for `{needle}` has no x coordinate"))
}
fn first_black_rect_width(svg: &str) -> f64 {
for fragment in svg.split("<rect ").skip(1) {
let tag = fragment.split('>').next().unwrap_or(fragment);
if !tag.contains("fill=\"#000000\"") {
continue;
}
let value = tag
.split("width=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok());
if let Some(width) = value {
return width;
}
}
panic!("no filled rectangle in SVG: {svg}");
}
fn max_black_rect_height(svg: &str) -> f64 {
let mut maximum: Option<f64> = None;
for fragment in svg.split("<rect ").skip(1) {
let tag = fragment.split('>').next().unwrap_or(fragment);
if !tag.contains("fill=\"#000000\"") {
continue;
}
let value = tag
.split("height=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok());
if let Some(height) = value {
maximum = Some(maximum.map_or(height, |current| current.max(height)));
}
}
maximum.unwrap_or_else(|| panic!("no filled rectangle in SVG: {svg}"))
}
#[test]
fn paragraph_indent_tracks_setlength_groups_and_noindent() {
let source = r#"\documentclass{article}
\begin{document}
\parindent=0pt
First paragraph.
\setlength{\parindent}{10mm}
Second paragraph.
{\setlength{\parindent}{0pt}
Third paragraph.
}
Fourth paragraph.
\addtolength{\parindent}{5mm}
Fifth paragraph.
\noindent
Noindent paragraph.
\end{document}
"#;
let value = fresh_preview(source, "parindent.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
let first = text_x(&svg, "First");
let second = text_x(&svg, "Second");
let third = text_x(&svg, "Third");
let fourth = text_x(&svg, "Fourth");
let fifth = text_x(&svg, "Fifth");
let noindent = text_x(&svg, "Noindent");
assert!(
first.abs() < 0.1,
"first paragraph should not be indented: {first}"
);
assert!((second - 10.0).abs() < 0.25, "second indent: {second}");
assert!(third.abs() < 0.1, "grouped zero indent leaked: {third}");
assert!(
(fourth - 10.0).abs() < 0.25,
"group restore failed: {fourth}"
);
assert!((fifth - 15.0).abs() < 0.25, "addtolength failed: {fifth}");
assert!(noindent.abs() < 0.1, "noindent ignored: {noindent}");
}
#[test]
fn default_parindent_is_seventeen_points() {
let source = r#"\documentclass{article}
\begin{document}
Default indent.
\end{document}
"#;
let value = fresh_preview(source, "default-parindent.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
let x = text_x(&svg, "Default");
// 17pt is 5.98mm.
assert!((x - 5.98).abs() < 0.15, "default parindent: {x}");
}
#[test]
fn hfill_fills_the_remaining_line() {
let source = r#"\documentclass{article}
\begin{document}
\setlength{\parindent}{0pt}
A\hfill B
C\hfill D\hfill E
\end{document}
"#;
let value = fresh_preview(source, "hfill.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
let a = text_x(&svg, "A");
let b = text_x(&svg, "B");
let c = text_x(&svg, "C");
let d = text_x(&svg, "D");
let e = text_x(&svg, "E");
assert!(a.abs() < 0.1, "A should stay at the left margin: {a}");
assert!(b > 150.0, "single hfill did not reach the right edge: {b}");
assert!(c.abs() < 0.1, "C should stay at the left margin: {c}");
assert!(d > 70.0 && d < 100.0, "middle hfill is not centered: {d}");
assert!(e > 150.0, "last hfill did not reach the right edge: {e}");
}
#[test]
fn figure_placement_and_newpage_split_pages() {
let image = format!("{}/examples/plot.png", env!("CARGO_MANIFEST_DIR"));
let template = r#"\documentclass{article}
\begin{document}
Before text.
\begin{figure}[PLACE]
\includegraphics[width=3cm]{IMAGE}
\caption{Float caption.}
\end{figure}
After text.
\end{document}
"#;
let compile = |placement: &str| {
let source = template
.replace("PLACE", placement)
.replace("IMAGE", &image);
fresh_preview(&source, "float.tex")
};
let top = compile("t");
assert_eq!(top["status"], "ok", "{}", top["message"]);
assert_eq!(pages(&top).len(), 2, "[t] should move the figure to page 2");
assert!(
!page_svg(&top, 0).contains("<image"),
"[t] figure on page 1"
);
assert!(page_svg(&top, 1).contains("<image"), "[t] figure missing");
assert!(
page_svg(&top, 0).contains("After"),
"[t] text after the float should fill page 1: {}",
page_svg(&top, 0)
);
let top_image_y = page_svg(&top, 1)
.split("<image")
.nth(1)
.and_then(|rest| rest.split("y=\"").nth(1))
.and_then(|rest| rest.split("\"").next())
.and_then(|value| value.parse::<f64>().ok())
.unwrap_or_else(|| panic!("[t] image has no y coordinate: {}", page_svg(&top, 1)));
assert!(
top_image_y < 30.0,
"[t] figure was not placed at the top of page 2: {top_image_y}"
);
let here = compile("h");
assert_eq!(here["status"], "ok", "{}", here["message"]);
assert_eq!(pages(&here).len(), 1, "[h] should stay in flow");
assert!(page_svg(&here, 0).contains("<image"), "[h] figure missing");
let float_page = compile("p");
assert_eq!(float_page["status"], "ok", "{}", float_page["message"]);
assert_eq!(pages(&float_page).len(), 3, "[p] should use its own page");
assert!(
page_svg(&float_page, 1).contains("<image"),
"[p] figure page missing"
);
let bottom = compile("b");
assert_eq!(bottom["status"], "ok", "{}", bottom["message"]);
assert_eq!(pages(&bottom).len(), 2, "[b] should end the page");
let bottom_svg = page_svg(&bottom, 0);
assert!(bottom_svg.contains("<image"), "[b] figure missing");
let image_y = bottom_svg
.split("<image")
.nth(1)
.and_then(|rest| rest.split("y=\"").nth(1))
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok())
.unwrap_or_else(|| panic!("[b] image has no y coordinate: {bottom_svg}"));
assert!(
image_y > 200.0,
"[b] figure was not pushed to the bottom: {image_y}"
);
assert!(page_svg(&bottom, 1).contains("After"), "[b] following text");
let newpage = r#"\documentclass{article}
\begin{document}
First page.
\newpage
Second page.
\end{document}
"#;
let value = fresh_preview(newpage, "newpage.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
assert_eq!(pages(&value).len(), 2, "\\newpage page count");
assert!(page_svg(&value, 0).contains("First"), "first page text");
assert!(page_svg(&value, 1).contains("Second"), "second page text");
}
#[test]
fn sans_family_selects_the_sans_face() {
let source = r#"\documentclass{article}
\begin{document}
\setlength{\parindent}{0pt}
Serif text.
{\sffamily Sans family text.}
\textsf{Textsf sans} and {\sffamily\bfseries bold sans}.
\end{document}
"#;
let value = fresh_preview(source, "sans.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert!(
svg.contains("font-family=\"TexrraSans\""),
"sans face missing"
);
assert!(
svg.contains("font-family=\"TexrraSerif\""),
"serif face missing"
);
assert!(svg.contains(">Sans</text>"), "sans text missing");
assert!(svg.contains("extsf"), "textsf text missing");
assert!(
svg.contains("font-family=\"TexrraSans\" font-size=\"3.5278\" font-weight=\"700\""),
"bold sans face missing"
);
}
#[test]
fn small_caps_uses_reduced_uppercase_glyphs() {
let source = r#"\documentclass{article}
\begin{document}
\setlength{\parindent}{0pt}
\textsc{Small Caps} and {\scshape mixed Case}.
\end{document}
"#;
let value = fresh_preview(source, "smallcaps.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert!(
svg.contains(">MALL</text>"),
"lowercase letters were not uppercased"
);
assert!(!svg.contains("mall"), "small caps leaked lowercase glyphs");
assert!(
svg.contains("font-size=\"2.8222\""),
"small caps were not reduced to 80%"
);
assert!(
svg.contains("font-size=\"3.5278\""),
"full-size capitals should remain full-size"
);
}
fn text_y(svg: &str, needle: &str) -> f64 {
let closing = format!("{needle}</text>");
let index = svg
.find(&closing)
.unwrap_or_else(|| panic!("missing text element containing `{needle}`"));
let start = svg[..index]
.rfind("<text ")
.unwrap_or_else(|| panic!("no text element before `{needle}`"));
let tag = &svg[start..index];
tag.split("y=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok())
.unwrap_or_else(|| panic!("text element for `{needle}` has no y coordinate"))
}
#[test]
fn raisebox_lifts_content_inline() {
let source = r#"\documentclass{article}
\begin{document}
\setlength{\parindent}{0pt}
A\raisebox{4pt}{raised}B
\end{document}
"#;
let value = fresh_preview(source, "raisebox.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
let baseline = text_y(&svg, "A");
let raised = text_y(&svg, "raised");
let lift = baseline - raised;
// 4pt = 1.411mm.
assert!((lift - 1.411).abs() < 0.15, "raisebox lift: {lift}");
}
#[test]
fn makebox_honours_width_and_alignment() {
let source = r#"\documentclass{article}
\begin{document}
\setlength{\parindent}{0pt}
X\makebox[20mm][c]{mid}Y
\makebox[40mm][l]{L}\makebox[40mm][r]{R}
\end{document}
"#;
let value = fresh_preview(source, "makebox.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
let x = text_x(&svg, "X");
let mid = text_x(&svg, "mid");
let y = text_x(&svg, "Y");
assert!(
mid > x + 7.0,
"centered box content did not move right: {mid}"
);
assert!(mid < y - 4.0, "centered box content overflowed: {mid}");
assert!(
(y - x - 22.8).abs() < 0.5,
"fixed box width not honoured: {}",
y - x
);
let left = text_x(&svg, "L");
let right = text_x(&svg, "R");
assert!(
right > left + 70.0,
"right-aligned box did not fill width: {right}"
);
}
#[test]
fn inline_fbox_draws_a_frame_around_content() {
let source = r#"\documentclass{article}
\begin{document}
\setlength{\parindent}{0pt}
A\fbox{B}C
\end{document}
"#;
let value = fresh_preview(source, "inline-fbox.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert!(
svg.contains("fill=\"none\" stroke=\"#000000\""),
"inline fbox frame is missing"
);
assert!(svg.contains(">B</text>"), "inline fbox content is missing");
assert!(
svg.contains(">A</text>") && svg.contains(">C</text>"),
"text around fbox missing"
);
}
#[test]
fn minipage_wraps_to_requested_width_and_vbox_wraps() {
let source = r#"\documentclass{article}
\begin{document}
\begin{minipage}[t]{50mm}
This is a minipage with enough text to wrap across several lines and demonstrate that it is block-wide.
\end{minipage}
\vbox{A vbox wraps at text width with \textbf{bold} content.}
\end{document}
"#;
let value = fresh_preview(source, "minipage.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert!(svg.contains(">minipage</text>"), "minipage content missing");
assert!(
svg.contains(">block-wide.</text>"),
"wrapped minipage tail missing"
);
let first = text_y(&svg, "This");
let wrapped = text_y(&svg, "block-wide.");
assert!(
wrapped > first + 3.0,
"minipage did not wrap: {first} -> {wrapped}"
);
for word in ["This", "text", "block-wide."] {
assert!(
text_x(&svg, word) < 50.0,
"minipage content escaped its 50mm width: {word}"
);
}
assert!(svg.contains(">vbox</text>"), "vbox content missing");
assert!(svg.contains(">bold</text>"), "vbox styled content missing");
}
#[test]
fn footnotes_are_placed_at_the_page_bottom() {
let source = r#"\documentclass{article}
\begin{document}
First paragraph.\footnote{This is a footnote.}
Second paragraph.\footnote{Another note.}
Third paragraph.
\end{document}
"#;
let value = fresh_preview(source, "footnotes.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert!(svg.contains("¹"), "footnote marker missing");
assert!(svg.contains("²"), "second footnote marker missing");
let body = text_y(&svg, "First");
let note = text_y(&svg, "This");
assert!(
note > body + 150.0,
"footnote is not at the page bottom: {note}"
);
assert!(
text_x(&svg, "This") > 7.5 && text_x(&svg, "This") < 11.0,
"footnote indent missing"
);
assert!(
svg.contains("fill=\"#000000\"/>"),
"footnote separator rule missing"
);
}
#[test]
fn thanks_creates_a_title_footnote() {
let source = r#"\documentclass{article}
\title{A Title\thanks{Thanks to the test suite.}}
\author{Author\thanks{Author affiliation.}}
\begin{document}
\maketitle
Body text.
\end{document}
"#;
let value = fresh_preview(source, "thanks.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert!(svg.contains("¹"), "title thanks marker missing");
assert!(svg.contains("²"), "author thanks marker missing");
let note = text_y(&svg, "Thanks");
assert!(
note > 200.0,
"title footnote is not at the page bottom: {note}"
);
}
#[test]
fn page_style_decorates_headers_and_footers() {
let source = r#"\documentclass{article}
\pagestyle{fancy}
\fancyhead[L]{Left head}
\fancyhead[C]{Middle head}
\fancyhead[R]{Right head}
\fancyfoot[C]{Foot \thepage}
\begin{document}
Body text.
\end{document}
"#;
let value = fresh_preview(source, "pagestyle.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
for text in ["Left", "Middle", "Right", "Foot"] {
assert!(
svg.contains(&format!(">{text}</text>")),
"missing decoration `{text}`: {svg}"
);
}
assert!(
text_x(&svg, "Left") < 1.0,
"left header is not at the left margin"
);
assert!(
text_x(&svg, "Right") > 140.0,
"right header is not at the right edge"
);
assert!(
text_y(&svg, "Left") < 25.0,
"header is not near the top of the page"
);
assert!(
text_y(&svg, "Foot") > 250.0,
"footer is not near the bottom of the page"
);
}
#[test]
fn thispagestyle_empty_suppresses_one_page_decorations() {
let source = r#"\documentclass{article}
\pagestyle{fancy}
\fancyhead[L]{Left head}
\fancyfoot[C]{Foot \thepage}
\begin{document}
First page.\thispagestyle{empty}
\newpage
Second page.
\end{document}
"#;
let value = fresh_preview(source, "thispagestyle.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
assert_eq!(pages(&value).len(), 2, "page count");
let first = page_svg(&value, 0);
assert!(
!first.contains(">Left</text>"),
"page 1 header was not suppressed: {first}"
);
assert!(
!first.contains(">Foot</text>"),
"page 1 footer was not suppressed: {first}"
);
let second = page_svg(&value, 1);
assert!(
second.contains(">Left</text>"),
"page 2 header missing: {second}"
);
assert!(
second.contains(">Foot</text>"),
"page 2 footer missing: {second}"
);
assert!(
second.contains(">2</text>"),
"page 2 number missing: {second}"
);
}
#[test]
fn default_plain_style_prints_a_page_number() {
let value = fresh_preview(include_str!("../examples/hello.tex"), "hello.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert!(
text_y(&svg, "1") > 250.0,
"default page number is not in the footer"
);
}
#[test]
fn geometry_updates_text_width_and_text_height() {
let source = r#"\documentclass{article}
\geometry{textwidth=100mm,textheight=200mm}
\begin{document}
\noindent\rule{\textwidth}{2pt}
\noindent\rule{2pt}{\textheight}
\end{document}
"#;
let value = fresh_preview(source, "geometry-lengths.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
let width = first_black_rect_width(&svg);
assert!(
(width - 100.0).abs() < 1.0,
"textwidth did not follow geometry: {width}"
);
let height = max_black_rect_height(&svg);
assert!(
(height - 200.0).abs() < 1.0,
"textheight did not follow geometry: {height}"
);
}
#[test]
fn letter_paper_updates_text_width_length() {
let source = r#"\documentclass[letterpaper]{article}
\begin{document}
\noindent\rule{\textwidth}{2pt}
\end{document}
"#;
let value = fresh_preview(source, "letter-lengths.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let width = first_black_rect_width(&page_svg(&value, 0));
assert!(
(width - 165.9).abs() < 1.0,
"letter textwidth is wrong: {width}"
);
}
#[test]
fn document_class_font_size_scales_body_and_headings() {
for (option, body_size, heading_size) in [
("10pt", "3.5278", "4.9389"),
("11pt", "3.8806", "4.9389"),
("12pt", "4.2333", "5.9972"),
] {
let source = format!(
r"\documentclass[{option}]{{article}}
\begin{{document}}
\section{{Heading}}
Body text.
\end{{document}}
"
);
let value = fresh_preview(&source, "fontsize.tex");
assert_eq!(value["status"], "ok", "{option}: {}", value["message"]);
let svg = page_svg(&value, 0);
assert!(
svg.contains(&format!("font-size=\"{body_size}\" font-weight=\"400\"")),
"{option}: body size {body_size} missing"
);
assert!(
svg.contains(&format!("font-size=\"{heading_size}\" font-weight=\"700\"")),
"{option}: heading size {heading_size} missing"
);
}
}
#[test]
fn top_table_moves_to_the_next_page_and_text_flows() {
let source = r#"\documentclass{article}
\begin{document}
Before table.
\begin{table}[t]
\caption{Top table}
\begin{tabular}{ll}
Alpha & Beta \\
Gamma & Delta \\
\end{tabular}
\end{table}
After table.
\end{document}
"#;
let value = fresh_preview(source, "table-float.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
assert_eq!(pages(&value).len(), 2, "top table should start a new page");
assert!(
!page_svg(&value, 0).contains("Top"),
"table caption should not stay on page 1: {}",
page_svg(&value, 0)
);
assert!(
page_svg(&value, 0).contains("After"),
"text after the table should fill page 1"
);
let second = page_svg(&value, 1);
assert!(
second.contains(">op</text>"),
"table caption missing from page 2: {second}"
);
assert!(
second.contains(">Alpha</text>"),
"table body missing from page 2: {second}"
);
}
#[test]
fn bottom_table_sits_at_the_page_bottom() {
let source = r#"\documentclass{article}
\begin{document}
Before table.
\begin{table}[b]
\caption{Bottom table}
\begin{tabular}{ll}
Alpha & Beta \\
Gamma & Delta \\
\end{tabular}
\end{table}
After table.
\end{document}
"#;
let value = fresh_preview(source, "table-bottom.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
assert_eq!(pages(&value).len(), 2, "bottom table should end page 1");
let first = page_svg(&value, 0);
assert!(first.contains(">Alpha</text>"), "bottom table missing");
let alpha_y = text_y(&first, "Alpha");
assert!(
alpha_y > 220.0,
"bottom table was not pushed to the page bottom: {alpha_y}"
);
assert!(
page_svg(&value, 1).contains("After"),
"text after a bottom table should continue on the next page"
);
}
#[test]
fn table_of_contents_lists_numbered_sections_and_pages() {
let source = r"\documentclass{article}
\begin{document}
\tableofcontents
\section{Alpha section}
Alpha paragraph.
\newpage
\section{Beta section}
Beta paragraph.
\end{document}";
let value = fresh_preview(source, "contents.tex");
assert_eq!(value["status"], "ok", "{value}");
assert_eq!(pages(&value).len(), 2, "{value}");
let svg = page_svg(&value, 0);
assert!(svg.contains(">Contents</text>"), "missing contents heading");
assert!(svg.contains(">Alpha</text>"), "missing first entry");
assert!(svg.contains(">Beta</text>"), "missing second entry");
assert!(svg.contains(">1</text>"), "missing first page number");
assert!(svg.contains(">2</text>"), "missing second page number");
assert!(svg.contains(". . ."), "missing dotted leader: {svg}");
}
#[test]
fn list_of_tables_lists_captions_and_pages() {
let source = r"\documentclass{article}
\begin{document}
\listoftables
\begin{table}[h]
\caption{First table}
\begin{tabular}{ll}
A & B \\
\end{tabular}
\end{table}
\end{document}";
let value = fresh_preview(source, "lot.tex");
assert_eq!(value["status"], "ok", "{value}");
let svg = page_svg(&value, 0);
assert!(svg.contains(">List</text>"), "missing list heading");
assert!(svg.contains(">of</text>"), "missing tables heading word");
assert!(svg.contains(">ables</text>"), "missing tables word");
assert!(svg.contains(">First</text>"), "missing caption entry");
assert!(svg.contains(">1</text>"), "missing page number");
}
#[test]
fn list_of_figures_lists_captions_and_pages() {
let source = r"\documentclass{article}
\begin{document}
\listoffigures
\begin{figure}[h]
\includegraphics[width=20mm]{examples/plot.png}
\caption{First figure}
\end{figure}
\end{document}";
let value = fresh_preview(source, "lof.tex");
assert_eq!(value["status"], "ok", "{value}");
let svg = page_svg(&value, 0);
assert!(svg.contains(">List</text>"), "missing list heading");
assert!(svg.contains(">of</text>"), "missing figures heading word");
assert!(svg.contains(">First</text>"), "missing caption entry");
}
#[test]
fn rules_are_native_pdf_rectangles() {
let source = r"\documentclass{article}
\begin{document}
Before.
\rule{40mm}{5mm}
\fbox{Framed box}
After.
\end{document}";
let pdf = CompilerSession::default()
.compile(source, "rules.tex")
.expect("rule PDF");
assert!(pdf.starts_with(b"%PDF-"));
let text = String::from_utf8_lossy(&pdf);
assert!(
!text.contains("/Subtype /Image"),
"rules should not be painted as image XObjects"
);
}
#[test]
fn abstract_environment_gets_an_unumbered_heading() {
let source = r"\documentclass{article}
\begin{document}
\begin{abstract}
This is the abstract body.
\end{abstract}
\section{Introduction}
Body.
\end{document}";
let preview = CompilerSession::default()
.preview_json(source, "abstract.tex")
.expect("abstract preview");
let value: serde_json::Value = serde_json::from_str(&preview).expect("preview JSON");
let svg = value["pages"][0]["svg"].as_str().expect("svg");
assert!(
svg.contains(">Abstract</text>"),
"missing abstract heading: {svg}"
);
assert!(
svg.contains(">1</text>"),
"section numbering changed: {svg}"
);
}
#[test]
fn ragged_alignment_declarations_are_honoured() {
let prefix = r"\documentclass{article}
\usepackage[margin=6.5cm]{geometry}
\begin{document}
";
let ragged_source = format!(
"{prefix}{{\\raggedleft Right}}\n\n{{\\raggedright alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu}}\n\\end{{document}}"
);
let justified_source = format!(
"{prefix}alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu\n\\end{{document}}"
);
let ragged = fresh_preview(&ragged_source, "ragged.tex");
let justified = fresh_preview(&justified_source, "justified.tex");
let ragged_svg = page_svg(&ragged, 0);
let justified_svg = page_svg(&justified, 0);
assert!(
text_x(&ragged_svg, "Right") > 30.0,
"raggedleft did not move to the right margin: {ragged_svg}"
);
let ragged_beta = text_x(&ragged_svg, "beta");
let justified_beta = text_x(&justified_svg, "beta");
assert!(
ragged_beta + 0.2 < justified_beta,
"raggedright still justified the line: ragged={ragged_beta}, justified={justified_beta}\nRAGGED={ragged_svg}\nJUSTIFIED={justified_svg}"
);
}
#[test]
fn centering_declaration_centers_a_paragraph() {
let prefix = r"\documentclass{article}
\usepackage[margin=6.5cm]{geometry}
\begin{document}
";
let centered_source =
format!("{prefix}{{\\centering alpha beta}}\n\nplain paragraph\n\\end{{document}}");
let left_source = format!("{prefix}alpha beta\n\nplain paragraph\n\\end{{document}}");
let centered = fresh_preview(&centered_source, "centered.tex");
let left = fresh_preview(&left_source, "left.tex");
let centered_svg = page_svg(&centered, 0);
let left_svg = page_svg(&left, 0);
let centered_alpha = text_x(&centered_svg, "alpha");
let left_alpha = text_x(&left_svg, "alpha");
assert!(
centered_alpha > left_alpha + 10.0,
"centering did not move the line: centered={centered_alpha}, left={left_alpha}\n{centered_svg}"
);
let plain_alpha = text_x(&centered_svg, "plain");
let left_plain = text_x(&left_svg, "plain");
assert!(
(plain_alpha - left_plain).abs() < 0.5,
"centering leaked into the following paragraph: centered={plain_alpha}, left={left_plain}"
);
}
#[test]
fn chapter_headings_number_sections_and_enter_contents() {
let source = r#"\documentclass{book}
\begin{document}
\tableofcontents
\chapter{First Chapter}
\section{Alpha}
\subsection{Beta}
\chapter{Second Chapter}
\section{Gamma}
\end{document}
"#;
let value = fresh_preview(source, "chapters.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
assert!(
pages(&value).len() >= 2,
"chapters did not start on a new page: {value}"
);
let svg = (0..pages(&value).len())
.map(|index| page_svg(&value, index))
.collect::<Vec<_>>()
.join("");
for needle in [
"Contents", "First", "Chapter", "Alpha", "Beta", "Gamma", "1.1", "1.1.1", "2.1",
] {
assert!(svg.contains(needle), "chapter numbering is missing : {svg}");
}
assert!(
!svg.contains("0.1"),
"section was numbered under chapter zero: {svg}"
);
}
#[test]
fn custom_maketitle_replaces_the_engine_title_block() {
let source = r#"\documentclass{article}
\title{Custom title}
\author{Engine author}
\renewcommand{\maketitle}{\begin{center}\@title\end{center}}
\begin{document}
\maketitle
Body text.
\end{document}
"#;
let value = fresh_preview(source, "custom-title.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert!(svg.contains("Custom"), "custom title missing: {svg}");
assert!(
!svg.contains("Engine title"),
"engine title block was not replaced: {svg}"
);
assert!(svg.contains("Body"), "body text missing: {svg}");
}
#[test]
fn vbox_captures_vertical_material() {
let source = r#"\documentclass{article}
\begin{document}
Before.
\vbox{%
\hrule width 40mm height 2pt
\vskip 4pt
\hrule width 20mm height 2pt
}
After.
\end{document}
"#;
let value = fresh_preview(source, "vbox.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert_eq!(
svg.matches("fill=\"#000000\"/>").count(),
2,
"expected two rules in vbox: {svg}"
);
assert!(svg.contains("width=\"40.15"), "wide rule missing: {svg}");
assert!(svg.contains("width=\"20.07"), "narrow rule missing: {svg}");
assert!(svg.contains(">Before.</text>"), "text before vbox missing");
assert!(svg.contains(">After</text>"), "text after vbox missing");
}