Skip to content

Commit

Permalink
test(canvas): add unit tests for line (#437)
Browse files Browse the repository at this point in the history
Also add constructor to simplify creating lines
  • Loading branch information
joshka authored Aug 26, 2023
1 parent f0716ed commit ad3413e
Showing 1 changed file with 170 additions and 0 deletions.
170 changes: 170 additions & 0 deletions src/widgets/canvas/line.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,19 @@ pub struct Line {
pub color: Color,
}

impl Line {
/// Create a new line from (x1, y1) to (x2, y2) with the given color
pub fn new(x1: f64, y1: f64, x2: f64, y2: f64, color: Color) -> Self {
Self {
x1,
y1,
x2,
y2,
color,
}
}
}

impl Shape for Line {
fn draw(&self, painter: &mut Painter) {
let Some((x1, y1)) = painter.get_point(self.x1, self.y1) else {
Expand Down Expand Up @@ -91,3 +104,160 @@ fn draw_line_high(painter: &mut Painter, x1: usize, y1: usize, x2: usize, y2: us
d += 2 * dx;
}
}

#[cfg(test)]
mod tests {
use super::Line;
use crate::{
assert_buffer_eq,
prelude::*,
widgets::{canvas::Canvas, Widget},
};

#[track_caller]
fn test(line: Line, expected_lines: Vec<&str>) {
let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 10));
let canvas = Canvas::default()
.marker(Marker::Dot)
.x_bounds([0.0, 10.0])
.y_bounds([0.0, 10.0])
.paint(|context| {
context.draw(&line);
});
canvas.render(buffer.area, &mut buffer);

let mut expected = Buffer::with_lines(expected_lines);
for cell in expected.content.iter_mut() {
if cell.symbol == "•" {
cell.set_style(Style::new().red());
}
}
assert_buffer_eq!(buffer, expected);
}

#[test]
fn off_grid() {
test(
Line::new(-1.0, -1.0, 10.0, 10.0, Color::Red),
vec![" "; 10],
);
test(
Line::new(0.0, 0.0, 11.0, 11.0, Color::Red),
vec![" "; 10],
);
}

#[test]
fn horizontal() {
test(
Line::new(0.0, 0.0, 10.0, 0.0, Color::Red),
vec![
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
"••••••••••",
],
);
test(
Line::new(10.0, 10.0, 0.0, 10.0, Color::Red),
vec![
"••••••••••",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
],
);
}

#[test]
fn vertical() {
test(
Line::new(0.0, 0.0, 0.0, 10.0, Color::Red),
vec!["• "; 10],
);
test(
Line::new(10.0, 10.0, 10.0, 0.0, Color::Red),
vec![" •"; 10],
);
}

#[test]
fn diagonal() {
// dy < dx, x1 < x2
test(
Line::new(0.0, 0.0, 10.0, 5.0, Color::Red),
vec![
" ",
" ",
" ",
" ",
" •",
" •• ",
" •• ",
" •• ",
" •• ",
"• ",
],
);
// dy < dx, x1 > x2
test(
Line::new(10.0, 0.0, 0.0, 5.0, Color::Red),
vec![
" ",
" ",
" ",
" ",
"• ",
" •• ",
" •• ",
" •• ",
" •• ",
" •",
],
);
// dy > dx, y1 < y2
test(
Line::new(0.0, 0.0, 5.0, 10.0, Color::Red),
vec![
" • ",
" • ",
" • ",
" • ",
" • ",
" • ",
" • ",
" • ",
"• ",
"• ",
],
);
// dy > dx, y1 > y2
test(
Line::new(0.0, 10.0, 5.0, 0.0, Color::Red),
vec![
"• ",
"• ",
" • ",
" • ",
" • ",
" • ",
" • ",
" • ",
" • ",
" • ",
],
);
}
}

0 comments on commit ad3413e

Please sign in to comment.