Lines
100 %
Functions
Branches
use crate::DEFAULT_TEXT_PX;
use crate::spec::{ChartKind, ChartSpec, Series, SeriesPoint};
use crate::svg::render_svg;
fn point(x: &str, y: i64) -> SeriesPoint {
SeriesPoint {
x: x.to_string(),
y_num: y,
y_denom: 1,
}
fn series(label: &str, points: Vec<SeriesPoint>) -> Series {
Series {
label: label.to_string(),
commodity_symbol: "USD".to_string(),
points,
fn spec(series: Vec<Series>) -> ChartSpec {
ChartSpec {
title: "T".to_string(),
kind: ChartKind::Bar,
x_label: String::new(),
y_label: String::new(),
series,
notes: vec![],
fn flat(categories: i64) -> ChartSpec {
spec(
(1..=categories)
.map(|n| {
let name = format!("c{n}");
series(&name, vec![point(&name, n * 1000)])
})
.collect(),
)
fn attr(tag: &str, name: &str) -> Option<f64> {
let rest = tag.split_once(&format!(" {name}=\""))?.1;
rest.split('"').next()?.parse().ok()
/// The widths of the `<rect>` elements the SVG draws.
fn rect_widths(svg: &str) -> Vec<f64> {
svg.split("<rect")
.skip(1)
.filter_map(|tag| attr(tag, "width"))
.collect()
fn svg(spec: &ChartSpec, text_px: u32) -> String {
render_svg(spec, 1000, 600, text_px)
#[test]
fn a_flat_chart_bar_fills_its_slot() {
let widths = rect_widths(&svg(&flat(10), DEFAULT_TEXT_PX));
let plot = 1000.0 - 60.0 - 16.0;
assert_eq!(widths.len(), 10, "{widths:?}");
for width in widths {
assert!(
width >= plot / 10.0 / 2.0,
"bar {width} is under half a slot"
);
fn a_flat_chart_has_no_legend() {
let flat = svg(&flat(3), DEFAULT_TEXT_PX);
assert_eq!(rect_widths(&flat).len(), 3, "legend rectangles drawn");
fn grouped_series_share_a_slot() {
let two = spec(vec![
series("a", vec![point("p1", 5), point("p2", 6)]),
series("b", vec![point("p1", 7), point("p2", 8)]),
]);
let widths = rect_widths(&svg(&two, DEFAULT_TEXT_PX));
let bars: Vec<f64> = widths.into_iter().filter(|w| *w > 100.0).collect();
assert_eq!(bars.len(), 4, "{bars:?}");
for width in bars {
(width - plot / 2.0 * 5.0 / 7.0 / 2.0).abs() < 3.0,
"bar {width} is not half a slot's bar area"
fn a_slot_with_one_bar_is_full_width_beside_a_shared_one() {
let mixed = spec(vec![
series("b", vec![point("p1", 7)]),
let widths = rect_widths(&svg(&mixed, DEFAULT_TEXT_PX));
assert_eq!(bars.len(), 3, "{bars:?}");
let widest = bars.iter().copied().fold(0.0, f64::max);
(widest - plot / 2.0 * 5.0 / 7.0).abs() < 3.0,
"lone bar is {widest}"
fn text_scales_the_label_area() {
let small = svg(&flat(3), DEFAULT_TEXT_PX);
let large = svg(&flat(3), DEFAULT_TEXT_PX * 2);
let first_bar_x = |svg: &str| {
.find_map(|tag| attr(tag, "x"))
.unwrap_or_default()
};
first_bar_x(&large) > first_bar_x(&small) + 40.0,
"{} vs {}",
first_bar_x(&large),
first_bar_x(&small)
fn y_ticks_have_no_trailing_zero_decimals() {
let labelled = svg(&flat(3), DEFAULT_TEXT_PX);
assert!(!labelled.contains(".0\n<"), "{labelled}");
assert!(labelled.contains("\n0\n"), "{labelled}");
fn y_labels_print_whole_and_fractional_ticks() {
assert_eq!(super::format_y_label(100_000.0, 2), "100,000");
assert_eq!(super::format_y_label(-0.0, 2), "0");
assert_eq!(super::format_y_label(2.5, 2), "2.5");
assert_eq!(super::format_y_label(0.126, 2), "0.13");
fn bars_leave_a_gap_and_sit_centred_in_their_slots() {
let svg = svg(&flat(4), DEFAULT_TEXT_PX);
let bars: Vec<(f64, f64)> = svg
.split("<rect")
.filter_map(|tag| Some((attr(tag, "x")?, attr(tag, "width")?)))
.collect();
let slot = plot / 4.0;
for (n, (x, width)) in bars.iter().enumerate() {
assert!((width / slot - 5.0 / 7.0).abs() < 0.02, "{width} of {slot}");
let centre = x + width / 2.0;
let wanted = 68.0 + slot * (n as f64 + 0.5);
(centre - wanted).abs() < 3.0,
"bar {n} centre {centre} not {wanted}"
assert_eq!(bars.len(), 4);
fn x_labels_sit_below_the_axis_by_a_share_of_the_text_height() {
let text_px = 20;
let drawn = svg(&flat(3), text_px);
let axis = drawn
.find_map(|tag| Some(attr(tag, "y")? + attr(tag, "height")?))
.expect("a bar");
let tops: Vec<f64> = drawn
.split("<text")
.filter(|tag| {
["\nc1\n", "\nc2\n", "\nc3\n"]
.iter()
.any(|l| tag.contains(l))
.filter_map(|tag| attr(tag, "y"))
assert_eq!(tops.len(), 3, "{tops:?}");
for top in tops {
top >= axis + 0.4 * f64::from(text_px) - 1.0,
"label top {top}, axis {axis}"
fn x_labels_are_centred_under_their_bars() {
let drawn = svg(&flat(3), DEFAULT_TEXT_PX);
let centres: Vec<f64> = drawn
.filter_map(|tag| Some(attr(tag, "x")? + attr(tag, "width")? / 2.0))
let labels: Vec<f64> = drawn
.filter_map(|tag| attr(tag, "x"))
assert_eq!(labels.len(), 3);
for (label, centre) in labels.iter().zip(¢res) {
assert!((label - centre).abs() < 2.0, "label {label}, bar {centre}");
fn the_axis_starts_at_zero_when_nothing_is_negative() {
let (low, high) = super::y_range(&flat(3));
assert_eq!(low, 0.0);
assert!(high > 3000.0);
let negative = spec(vec![series("a", vec![point("p", -50)])]);
let (low, high) = super::y_range(&negative);
assert!(low < -50.0);
assert_eq!(high, 0.0);
fn y_labels_group_thousands() {
assert_eq!(super::format_y_label(10_000.0, 2), "10,000");
assert_eq!(super::format_y_label(1_234_567.5, 2), "1,234,567.5");
assert_eq!(super::format_y_label(-2_000.0, 2), "-2,000");
assert_eq!(super::format_y_label(999.0, 2), "999");
fn one_category_draws_for_every_kind() {
for kind in [ChartKind::Bar, ChartKind::StackedBar, ChartKind::Line] {
let one = ChartSpec { kind, ..flat(1) };
let drawn = svg(&one, DEFAULT_TEXT_PX);
assert!(drawn.contains("c1"), "{kind:?}: {drawn}");
assert!(drawn.contains("</svg>"), "{kind:?}");
fn a_chart_of_zeros_keeps_a_span() {
let zeros = spec(vec![series("a", vec![point("p", 0), point("q", 0)])]);
let (low, high) = super::y_range(&zeros);
assert_eq!((low, high), (0.0, 1.0));
let drawn = svg(&zeros, DEFAULT_TEXT_PX);
assert!(drawn.contains("</svg>"));
assert!(drawn.contains("\n1\n"), "no tick above zero: {drawn}");
fn small_values_get_the_decimals_their_ticks_need() {
assert_eq!(super::y_decimals(1000.0), 0);
assert_eq!(super::y_decimals(1.0), 2);
assert_eq!(super::y_decimals(0.02), 4);
assert_eq!(super::y_decimals(0.0), 0);
assert_eq!(super::format_y_label(0.004, 4), "0.004");
assert_eq!(super::format_y_label(1_234.5, 4), "1,234.5");
let btc = SeriesPoint {
x: "p".to_string(),
y_num: 4,
y_denom: 1000,
let drawn = svg(&spec(vec![series("a", vec![btc])]), DEFAULT_TEXT_PX);
let ticks: Vec<&str> = drawn
.filter_map(|tag| tag.split('\n').nth(1))
.filter(|text| text.starts_with("0."))
let mut distinct = ticks.clone();
distinct.sort_unstable();
distinct.dedup();
ticks.len() > 2 && ticks.len() == distinct.len(),
"{ticks:?}"
fn uneven(labels: usize) -> ChartSpec {
(0..labels)
.map(|s| {
let points = (s + 1..=labels)
.map(|k| point(&format!("l{k}"), 10))
series(&format!("s{s}"), points)
fn uneven_bar_counts_up_to_twenty_five_draw_without_overflow() {
let many = uneven(25);
let drawn = svg(&many, DEFAULT_TEXT_PX);
let bars = rect_widths(&drawn).len();
assert!(bars >= 325, "{bars} rectangles for 325 bars");
fn bars_of_a_label_stay_inside_its_slot_and_apart() {
let labels = super::x_labels(&many);
let slots = crate::layout::Slots::grouped(&many, &labels);
for label in 0..25 {
let mut edge = f64::from(u32::try_from(label).unwrap_or(0));
for rank in 0..=label {
let (left, right) = slots.span(label, rank);
left >= edge - 1e-9 && right > left,
"label {label} rank {rank}"
edge = right;
assert!(edge <= f64::from(u32::try_from(label).unwrap_or(0)) + 1.0);
fn rect_boxes(svg: &str) -> Vec<(f64, f64, f64)> {
.filter_map(|tag| Some((attr(tag, "y")?, attr(tag, "height")?, attr(tag, "width")?)))
fn the_legend_sits_above_the_plot_and_swatches_have_a_border() {
let quarters = spec(vec![
series("Salary", vec![point("Q3", 5000), point("Q4", 6000)]),
series("Savings", vec![point("Q3", 3000), point("Q4", 4000)]),
let boxes = rect_boxes(&svg(&quarters, DEFAULT_TEXT_PX));
let swatches: Vec<_> = boxes.iter().filter(|b| b.2 < 50.0).collect();
let bars: Vec<_> = boxes.iter().filter(|b| b.2 > 100.0).collect();
assert_eq!(swatches.len(), 4, "fill and border per series: {boxes:?}");
let legend_bottom = swatches.iter().map(|b| b.0 + b.1).fold(0.0, f64::max);
let plot_top = bars.iter().map(|b| b.0).fold(f64::MAX, f64::min);
assert!(legend_bottom <= plot_top, "{legend_bottom} vs {plot_top}");
fn x_labels_sit_just_under_the_axis_below_the_legend() {
let drawn = svg(&quarters, DEFAULT_TEXT_PX);
.split("<line")
.filter_map(|tag| attr(tag, "y1"))
.fold(0.0, f64::max);
let label = drawn
.find(|tag| tag.contains("Q3"))
.and_then(|tag| attr(tag, "y"))
.unwrap_or_default();
label > axis && label < axis + 30.0,
"{label} vs axis {axis}"
fn two_series() -> ChartSpec {
spec(vec![
series("a", vec![point("p", 1), point("q", 2)]),
series("b", vec![point("p", 2), point("q", 1)]),
])
fn line_dots_and_legend_marks_scale_with_the_text() {
let lines = ChartSpec {
kind: ChartKind::Line,
..two_series()
let first = |drawn: &str, tag: &str, name: &str| {
drawn
.split(tag)
.nth(1)
.and_then(|tag| attr(tag, name))
let (small, large) = (
svg(&lines, DEFAULT_TEXT_PX),
svg(&lines, DEFAULT_TEXT_PX * 2),
assert_eq!(first(&small, "<circle", "r"), 3.0);
assert_eq!(first(&large, "<circle", "r"), 6.0);
let legend_stroke = |drawn: &str| {
.split("<polyline")
.and_then(|tag| attr(tag, "stroke-width"))
assert_eq!(legend_stroke(&small), 2.0);
assert_eq!(legend_stroke(&large), 4.0);
let swatch = |drawn: &str| {
rect_boxes(drawn)
.into_iter()
.find(|b| b.2 < 50.0)
.map(|b| (b.2, b.1))
svg(&two_series(), DEFAULT_TEXT_PX),
svg(&two_series(), DEFAULT_TEXT_PX * 2),
assert_eq!(swatch(&small), (10.0, 6.0));
assert_eq!(swatch(&large), (20.0, 12.0));
/// The y of the top and the bottom of the plot's y axis.
fn axis_extent(svg: &str) -> (f64, f64) {
let points = svg
.and_then(|tag| tag.split_once("points=\"")?.1.split('"').next())
let ys: Vec<f64> = points
.split_whitespace()
.filter_map(|pair| pair.split(',').nth(1)?.parse().ok())
(
ys.iter().copied().fold(f64::MAX, f64::min),
ys.iter().copied().fold(f64::MIN, f64::max),
fn swatch_rows(svg: &str) -> usize {
let mut tops: Vec<i64> = rect_boxes(svg)
.filter(|b| b.1 == 6.0 && b.2 == 10.0)
.map(|b| b.0.round() as i64)
tops.dedup();
tops.len()
fn a_legend_that_wraps_takes_a_second_row_from_the_plot() {
let named = |label: &str| {
(0..3)
.map(|n| series(&format!("{label}{n}"), vec![point("p", 5), point("q", 6)]))
let (one, two) = (
svg(&named("s"), DEFAULT_TEXT_PX),
svg(&named(&"long ".repeat(14)), DEFAULT_TEXT_PX),
assert_eq!((swatch_rows(&one), swatch_rows(&two)), (1, 2));
let (top_one, bottom_one) = axis_extent(&one);
let (top_two, bottom_two) = axis_extent(&two);
assert_eq!(bottom_one, bottom_two);
assert_eq!(top_two - top_one, 18.0);
assert!(top_two < bottom_two);
fn a_legend_too_tall_for_the_chart_is_cut_and_the_plot_stays_upright() {
let many = spec(
(0..30)
series(
&format!("series number {n}"),
vec![point("p", 5), point("q", 6)],
let drawn = render_svg(&many, 300, 200, DEFAULT_TEXT_PX);
let (top, bottom) = axis_extent(&drawn);
assert!(bottom - top > 40.0, "plot {top}..{bottom}");
assert!(swatch_rows(&drawn) <= 3, "{} rows", swatch_rows(&drawn));
let shown = rect_boxes(&drawn)
.count()
/ 2;
drawn.contains(&format!("+{} more", 30 - shown)),
"{shown} shown"
fn the_more_entry_drops_a_wide_last_entry_to_fit_the_canvas() {
let wide = spec(
(0..5)
&format!("{n} {}", "w".repeat(38)),
let drawn = render_svg(&wide, 300, 200, DEFAULT_TEXT_PX);
let shown = swatch_rows(&drawn);
let hidden = 5 - rect_boxes(&drawn)
assert!(shown >= 1 && hidden >= 1, "{shown} rows, {hidden} hidden");
let tag = drawn
.find(|tag| tag.contains(&format!("+{hidden} more")))
let x = attr(tag, "x").unwrap_or(-1.0);
assert!((0.0..=300.0 - 30.0).contains(&x), "x {x}");