Tests: SVG, PDF and EPS tests check what they claim

Assertions that ran all() over a list that could be empty now check the
list's length first: mesh points, image inks, glyph origins, imported
text, the PDF mesh and arrowhead paths, and the resampled CMYK pixels.
An image that takes a Warp from its art style is checked to keep none of
the look's fills and strokes, instead of checking each of none.

The convolve-matrix tests check that the filtered rectangle is imported,
not only that the import returned Ok. The fan-out clip path test moves
to a unit test that counts the clip paths read. The self-nesting symbol
test checks that the other symbol comes back. The EPS level and preview
id test checks the param values and the trimming and case rules instead
of looping over every value. The ignored PDF text-heavy timing run says
why it is ignored.

A gradient that repeats or reflects with no stops now paints as one
that pads. Before, PDF export wrote it as two 160 by 160 images and EPS
wrote three runs of a conic where one that pads writes one;
`Gradient::is_spread` is false without stops. `paint.setFill`'s params
still report the spread.
This commit is contained in:
dotCooCoo committed 2026-12-01 17:38:19 -08:00
1 parent 5970647dec
commit 52d08f0f9c
20 files changed
+120 -50

No files matched your search

+3 -2
View File
@@ -464,9 +464,10 @@ impl Gradient {
self.repeats.clamp(1, MAX_REPEATS)
}
/// Does it paint something other than its end colors past the ends of its stops, or run its
/// stops more than once: a linear, radial, conic or diamond gradient that repeats or reflects?
/// stops more than once: a linear, radial, conic or diamond gradient with stops that repeats or
/// reflects? One without stops paints as one that pads.
pub fn is_spread(&self) -> bool {
!self.spread.is_pad() && self.kind != GradientKind::Freeform
!self.spread.is_pad() && self.kind != GradientKind::Freeform && !self.stops.is_empty()
}
/// The spread and count as the gradient paints them: Pad and 1 for one that pads (whatever
/// count it keeps) and for a freeform one, else its spread and [`Self::repeat_count`]. Equal
@@ -36,6 +36,10 @@ fn spread_maps_the_parameter_to_a_place_along_the_stops() {
let free = spread(GradientKind::Freeform, GradientSpread::Repeat, 3);
assert_eq!(free.spread_param(0.7), 0.7);
assert!(!free.is_spread() && !pad.is_spread() && repeat.is_spread());
// Without stops it paints as one that pads.
let empty = Gradient { stops: vec![], ..repeat.clone() };
assert!(!empty.is_spread());
assert_eq!(empty.painted_spread(), (GradientSpread::Pad, 1));
assert!(repeat.spread_param(f64::NAN).is_nan());
// A count out of range (set in code) counts as the nearest one in range.
assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 0).repeat_count(), 1);
+2
View File
@@ -873,6 +873,7 @@ mod tests {
}
r.entry(&[V::Num(0.0), name("E")], Affine::IDENTITY);
let mesh = r.one_mesh().unwrap();
assert_eq!(mesh.points.len(), 9, "{mesh:?}");
assert!(mesh.points.iter().all(|q| q.p.x.is_finite() && q.p.y.is_finite() && q.handles.iter().all(|h| h.x.is_finite() && h.y.is_finite())));
}
@@ -962,6 +963,7 @@ mod tests {
assert!(!reader.unread, "{with_opacity} {data_first}");
let mesh = reader.one_mesh().unwrap();
let want = if with_opacity { 0.25 } else { 1.0 };
assert_eq!(mesh.points.len(), 4, "{with_opacity} {data_first}: {mesh:?}");
assert!(mesh.points.iter().all(|p| p.opacity == want), "{with_opacity} {data_first}: {mesh:?}");
}
}
+2 -1
View File
@@ -2217,7 +2217,8 @@ mod tests {
let ap = styled(&image, &look, &st, &paints).expect("an image takes one Warp");
let ids: Vec<&str> = ap.effects.iter().map(|e| e.id.as_str()).collect();
assert_eq!(ids, ["warp.arc"]);
assert!(ap.items.iter().all(|i| i.paint().is_none()), "{ap:?}");
// The image's own look: none of the look's fills and strokes.
assert!(ap.items.is_empty(), "{ap:?}");
// Not on a path, nor on an image with an opacity mask.
assert!(styled(&square(3, Paint::None), &look, &st, &paints).is_none());
let mut masked = image.clone();
+1
View File
@@ -291,6 +291,7 @@ fn object_tags_without_an_object_before_them_tag_nothing() {
let doc = read7(&layer7("L", &body)).doc;
let mut all = art(&doc);
all.extend(all.iter().flat_map(|n| n.children().cloned().unwrap_or_default()).collect::<Vec<_>>());
assert!(!all.is_empty(), "{body}: no art");
assert!(all.iter().all(|n| n.extras().attrs.is_none()), "{body}");
}
for bad in ["(x) (y) XT\n", "/id 3 XT\n", "XT\n"] {
+1
View File
@@ -241,6 +241,7 @@ fn cmyk_jpegs_keep_their_ink_amounts() {
/ImageMatrix [2 0 0 -2 0 2] /DataSource currentfile /ASCIIHexDecode filter /DCTDecode filter >> image\n{data}>"
));
let got = inks(&r).data;
assert_eq!(got.len(), want.len(), "{decode}: {got:?}");
assert!(got.iter().zip(&want).all(|(a, b)| a.abs_diff(*b) <= 3), "{decode}: {got:?}");
}
}
+1
View File
@@ -8238,6 +8238,7 @@ fn type_with_a_distort_effect_comes_in_as_type_with_it_live() {
// An angle that isn't a number: the drawing as paths, and no effect on the type.
let (texts, paths) = open("Adobe Twirl", "NaN /Real (angle) ,\n");
assert_eq!(paths, 1, "{texts:?}");
assert_eq!(texts.len(), 1, "{texts:?}");
assert!(texts.iter().all(|(_, effects)| effects.is_empty()), "{texts:?}");
}
+23 -12
View File
@@ -301,12 +301,23 @@ fn spread_gradients_are_written_with_their_stops_repeated() {
fn a_spread_gradient_without_stops_is_written() {
use vectorcraft_color::GradientSpread;
for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond] {
let g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 3, ..Gradient::new(kind, vec![]) });
let paint = Paint::Gradient(Box::new(g));
let d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), paint.clone(), paint, 4.0)]);
export(&d, &opts(&d), None, None).unwrap();
export_legacy_ai(&d, &LegacyAiOptions::default()).unwrap();
crate::export_ai_editing(&d, &crate::AiEditingOptions::default()).unwrap();
let doc = |spread: GradientSpread| {
let g = GradientPaint::new(Gradient { spread, repeats: 3, ..Gradient::new(kind, vec![]) });
let paint = Paint::Gradient(Box::new(g));
doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), paint.clone(), paint, 4.0)])
};
let (d, pad) = (doc(GradientSpread::Repeat), doc(GradientSpread::Pad));
assert_eq!(page_of(&d, &opts(&d)), page_of(&pad, &opts(&pad)), "{kind:?}: EPS");
assert_eq!(
export_legacy_ai(&d, &LegacyAiOptions::default()).unwrap().bytes,
export_legacy_ai(&pad, &LegacyAiOptions::default()).unwrap().bytes,
"{kind:?}: legacy .ai"
);
assert_eq!(
crate::export_ai_editing(&d, &crate::AiEditingOptions::default()).unwrap().program,
crate::export_ai_editing(&pad, &crate::AiEditingOptions::default()).unwrap().program,
"{kind:?}: .ai editing data"
);
}
}
@@ -2359,15 +2370,15 @@ fn symbol_art_effects_are_written_where_they_draw() {
#[test]
fn level_preview_and_overprint_ids_read_back() {
for l in Level::ALL {
assert_eq!(Level::from_id(l.id()), Some(l));
}
assert_eq!(Level::from_id("3"), Some(Level::Three));
assert_eq!(Level::from_id("LanguageLevel 2"), Some(Level::Two));
assert_eq!(Level::from_id("1"), None);
for p in Preview::ALL {
assert_eq!(Preview::from_id(p.id()), Some(p));
}
assert_eq!(Level::from_id("23"), None);
assert_eq!(Preview::from_id(" TIFFCOLOR "), Some(Preview::TiffColor));
assert_eq!(Preview::from_id("tiffBw"), Some(Preview::TiffBlackWhite));
assert_eq!(Preview::from_id("tiff"), None);
assert_eq!(Overprint::from_id("DISCARD"), Some(Overprint::Discard));
assert_eq!(Overprint::from_id(""), None);
}
#[test]
+1
View File
@@ -915,6 +915,7 @@ mod tests {
let (inks, alpha) = resampled_inks(inks, Some(alpha.clone()), &rule(&c, Kind::Color), (4, 1)).unwrap();
let alpha = alpha.unwrap();
let m = |c: u8, a: u8| (u16::from(c) * u16::from(a) / 255) as u8;
assert_eq!((inks.as_chunks::<4>().0.len(), alpha.len()), (4, 4), "{method}");
for (p, &a) in inks.as_chunks::<4>().0.iter().zip(&alpha) {
assert!(a > 0 && p.iter().zip([40, 80, 120, 160]).all(|(&c, want)| m(c, a).abs_diff(m(want, a)) <= 1), "{method}: {p:?} at {a}");
}
+4 -1
View File
@@ -73,11 +73,14 @@ fn a_cmyk_mesh_is_written_smooth_in_its_inks() {
let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap();
let (meshes, paths) = kinds(&back);
assert!(meshes >= 1 && paths <= 4, "meshes {meshes}, paths {paths}");
let mut points = vec![];
back.walk(|n| {
if let NodeKind::Mesh(m) = &n.kind {
assert!(m.points.iter().all(|p| matches!(p.color, Color::Cmyk { .. })), "{:?}", m.points);
points.extend(m.points.iter().map(|p| p.color));
}
});
assert!(!points.is_empty(), "the meshes have points");
assert!(points.iter().all(|c| matches!(c, Color::Cmyk { .. })), "{points:?}");
assert_similar(&render_artboard(&d), &render_artboard(&back), 6.0, 0.02);
}
+12 -8
View File
@@ -236,17 +236,21 @@ fn a_perceptual_spot_gradient_too_long_once_repeated_is_an_image() {
}
}
/// A gradient that repeats with no stops (a file can hold one) exports, filled and stroked.
/// A gradient that repeats with no stops (a file can hold one) exports, filled and stroked, as the
/// same gradient that pads does.
#[test]
fn a_spread_gradient_without_stops_exports() {
for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond] {
let g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 3, ..Gradient::new(kind, vec![]) });
let paint = Paint::Gradient(Box::new(g));
let mut d = Document::new(200.0, 200.0);
let (l, id) = (d.layers[0].id, d.alloc_id());
let ap = Appearance::basic(paint.clone(), paint, 4.0);
d.insert(Some(l), 0, Node::path(id, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), ap)).unwrap();
export(&d, &PdfOptions::default()).unwrap();
let written = |spread: GradientSpread| {
let g = GradientPaint::new(Gradient { spread, repeats: 3, ..Gradient::new(kind, vec![]) });
let paint = Paint::Gradient(Box::new(g));
let mut d = Document::new(200.0, 200.0);
let (l, id) = (d.layers[0].id, d.alloc_id());
let ap = Appearance::basic(paint.clone(), paint, 4.0);
d.insert(Some(l), 0, Node::path(id, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), ap)).unwrap();
uncompressed(&d, &PdfOptions { created: Some(0), ..PdfOptions::uncompressed() })
};
assert_eq!(written(GradientSpread::Repeat), written(GradientSpread::Pad), "{kind:?}");
}
}
+1
View File
@@ -90,5 +90,6 @@ fn line_and_head_share_one_opacity_group() {
_ => {}
});
assert!(group_opacity.is_some_and(|o| (o - 0.5).abs() < 0.01), "{group_opacity:?}");
assert!(!leaf_opacities.is_empty(), "the line and its head come back as paths");
assert!(leaf_opacities.iter().all(|o| (o - 1.0).abs() < 1e-3), "{leaf_opacities:?}");
}
+1 -1
View File
@@ -745,7 +745,7 @@ fn text_heavy(columns: usize, rows: usize) -> Vec<u8> {
/// How long a text-heavy file takes to open as type (run by hand: `-- --ignored --nocapture`).
#[test]
#[ignore]
#[ignore = "timing, run by hand"]
fn perf_text_heavy_open() {
let bytes = text_heavy(20, 200);
for _ in 0..2 {
+37
View File
@@ -297,3 +297,40 @@ pub(super) fn rule(r: usvg::FillRule) -> FillRule {
usvg::FillRule::EvenOdd => FillRule::EvenOdd,
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Clip paths are shared, so children that each name the next one multiply at every level: ten
/// children on seven levels would take 10^7 reads unbounded. The paths read stay within ten (the
/// children of one clip path) per clip path read, and the clip still has shapes.
#[test]
fn clip_paths_whose_children_fan_out_are_read_a_bounded_number_of_times() {
let mut defs = String::from(r#"<clipPath id="c0"><rect width="10" height="10"/></clipPath>"#);
for n in 1..8 {
let kids = format!(r#"<rect width="10" height="10" clip-path="url(#c{})"/>"#, n - 1).repeat(10);
defs += &format!(r#"<clipPath id="c{n}">{kids}</clipPath>"#);
}
let svg = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"><defs>{defs}</defs><rect width="20" height="20" clip-path="url(#c7)"/></svg>"#
);
let tree = usvg::Tree::from_str(&svg, &usvg::Options::default()).unwrap();
let cp = tree
.root()
.children()
.iter()
.find_map(|c| match c {
usvg::Node::Group(g) => g.clip_path(),
_ => None,
})
.unwrap();
let visits = std::cell::Cell::new(0usize);
let shapes = clip_shapes(cp, Affine::IDENTITY, &|_, _| {
visits.set(visits.get() + 1);
None
});
assert!(!shapes.is_empty());
assert!(visits.get() <= 10 * MAX_CLIP_READS, "{} paths read", visits.get());
}
}
+16 -7
View File
@@ -8,8 +8,17 @@
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use vectorcraft_doc::NodeKind;
use vectorcraft_svg::import;
/// How many paths `svg` imports as: each file here holds one filtered rectangle.
fn paths(svg: &str) -> usize {
let d = import(svg).unwrap_or_else(|e| panic!("{e}: {svg}"));
let mut n = 0;
d.walk(|node| n += usize::from(matches!(node.kind, NodeKind::Path { .. })));
n
}
/// An overflowing `order` with a `kernelMatrix` that parses (usvg `parser/filter.rs`).
#[test]
fn convolve_matrix_overflowing_order_with_kernel_is_refused() {
@@ -44,7 +53,7 @@ fn convolve_matrix_large_but_fitting_order_still_imports() {
let svg = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="{order}"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#
);
assert!(import(&svg).is_ok(), "order={order} fits the u32 multiply and must keep importing");
assert_eq!(paths(&svg), 1, "order={order} fits the u32 multiply and must keep importing");
}
}
@@ -56,7 +65,7 @@ fn convolve_matrix_nonpositive_or_unparseable_order_still_imports() {
let svg = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="{order}" {kernel}/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#
);
assert!(import(&svg).is_ok(), "order={order} is usvg's pass-through and must keep importing");
assert_eq!(paths(&svg), 1, "order={order} is usvg's pass-through and must keep importing");
}
}
@@ -65,18 +74,18 @@ fn convolve_matrix_nonpositive_or_unparseable_order_still_imports() {
#[test]
fn convolve_matrix_unparseable_or_mismatched_kernel_still_imports() {
let mismatched = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="3" kernelMatrix="0 0 0 0 1 0 0 0"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#;
assert!(import(mismatched).is_ok(), "a kernel of the wrong length is usvg's pass-through");
assert_eq!(paths(mismatched), 1, "a kernel of the wrong length is usvg's pass-through");
let unparseable = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="3" kernelMatrix="1e999 0 0 0 0 0 0 0 0"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#;
assert!(import(unparseable).is_ok(), "an unparseable kernel is usvg's pass-through");
assert_eq!(paths(unparseable), 1, "an unparseable kernel is usvg's pass-through");
}
/// Sane kernels keep importing: 3×3, 2×2, and a defaulted order.
#[test]
fn sane_convolve_matrices_still_import() {
let three = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="3" kernelMatrix="0 0 0 0 1 0 0 0 0"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#;
assert!(import(three).is_ok(), "an ordinary filter must still import");
assert_eq!(paths(three), 1, "an ordinary filter must still import");
let two = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="2" kernelMatrix="0 1 1 0"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#;
assert!(import(two).is_ok(), "a small kernel must still import");
assert_eq!(paths(two), 1, "a small kernel must still import");
let defaulted = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix kernelMatrix="0 0 0 0 1 0 0 0 0"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#;
assert!(import(defaulted).is_ok(), "a filter without order must still import");
assert_eq!(paths(defaulted), 1, "a filter without order must still import");
}
-15
View File
@@ -552,21 +552,6 @@ fn clip_path_child_with_chained_clip_path_intersects() {
assert_eq!(mine.over_white(100, 25), [255, 255, 255], "top right is cut by inner clip");
}
/// Clip paths are shared, so children that each name the next one multiply at every level: ten
/// children on seven levels would take 10^7 reads unbounded. The import must still finish.
#[test]
fn clip_paths_whose_children_fan_out_still_import() {
let mut defs = String::from(r#"<clipPath id="c0"><rect width="10" height="10"/></clipPath>"#);
for n in 1..8 {
let kids = format!(r#"<rect width="10" height="10" clip-path="url(#c{})"/>"#, n - 1).repeat(10);
defs += &format!(r#"<clipPath id="c{n}">{kids}</clipPath>"#);
}
let svg = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"><defs>{defs}</defs><rect width="20" height="20" clip-path="url(#c7)"/></svg>"#
);
assert!(import_with_report(&svg).is_ok());
}
#[test]
fn clip_path_deep_chain_preserves_art() {
let mut defs = String::from(r#"<clipPath id="c0"><rect width="100" height="100"/></clipPath>"#);
+5 -1
View File
@@ -226,7 +226,10 @@ fn a_use_of_a_text_passes_its_properties_on_to_the_text() {
#[test]
fn a_use_inside_the_text_it_shows_opens() {
let d = open(r##"<text id="t" y="50" font-size="20">HI<use href="#t" font-size="100"/><tspan><use href="#t"/></tspan></text>"##);
assert!(texts(&d).iter().all(|t| close(t.first_style().size, 20.0, 1e-9)), "{:?}", texts(&d));
let t = texts(&d);
assert_eq!(t.len(), 1, "{t:?}");
assert_eq!(t[0].plain_text(), "HI");
assert!(close(t[0].first_style().size, 20.0, 1e-9), "{t:?}");
}
/// Past 1 MiB of text built for `<use>` elements, the rest show their text with its own properties.
@@ -1232,6 +1235,7 @@ fn vertical_writing_mode_runs_down_a_path() {
let b = path.bounds().unwrap();
assert!(close(b.x0, b.x1, 1e-9) && close(b.y0, 20.0, 1e-9) && b.height() > 20.0, "{b:?}");
let o = glyph_origins(t);
assert_eq!(o.len(), 4, "{o:?}");
assert!(o.windows(2).all(|w| w[1].y > w[0].y), "glyphs step down: {o:?}");
// The em box is centred on the column.
let lay = layout(FontDb::global(), t);
+1
View File
@@ -56,6 +56,7 @@ fn current_color_and_context_colours_are_the_texts() {
let (art, _) = glyph_art(doc.as_bytes(), 1, 1000.0, BLUE, None).unwrap();
let mut strokes = vec![];
art.walk(&mut |c| strokes.push(c.appearance.stroke_paint()));
assert_eq!(strokes.len(), seen.len(), "the same art without the text's stroke: {strokes:?}");
assert!(strokes.iter().all(|p| *p == Paint::None), "no stroke without the text's: {strokes:?}");
let plain = r##"<svg xmlns="http://www.w3.org/2000/svg"><g id="glyph1"><path fill="#f00" d="M0 0h5v-5z"/></g></svg>"##;
assert!(!glyph_art(plain.as_bytes(), 1, 1000.0, BLUE, None).unwrap().1, "a document in its own colours");
+4 -1
View File
@@ -554,7 +554,10 @@ fn symbols_inside_themselves_end() {
d.symbols.push(Symbol { dynamic: false, name: "Loop".into(), art: Arc::new(g) });
instance(&mut d, "Loop", Affine::translate((20.0, 20.0)));
let svg = export(&d, &ExportOptions::default());
assert!(import(&svg).is_ok(), "{svg}");
// The symbol that holds itself is not written into itself; the other one still comes back.
assert!(svg.matches("<use ").count() <= 3, "{svg}");
let back = import(&svg).unwrap_or_else(|e| panic!("{e}: {svg}"));
assert!(back.symbols.iter().any(|s| s.name == "My Mark"), "{svg}");
}
/// Two layers, the second hidden, each with a square.
+1 -1
View File
@@ -79,7 +79,7 @@ pub fn gradient_params(g: &GradientPaint) -> Value {
v["method"] = json!(g.gradient.method.id());
}
// A freeform gradient has no ends to spread past (`paint.setFill` refuses a spread for one).
if g.gradient.is_spread() {
if !g.gradient.spread.is_pad() && g.gradient.kind != vectorcraft_color::GradientKind::Freeform {
v["spread"] = json!(g.gradient.spread.label().to_lowercase());
}
// A gradient that pads keeps its count for later.