From 791780ddbbc83982312024b11057034a714a0a1d Mon Sep 17 00:00:00 2001 From: Fabian Schmidt Date: Mon, 24 Feb 2025 10:20:01 +0100 Subject: [PATCH] Add test --- src/lib.rs | 23 +++++++++++++++++++++++ tests/web.rs | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 tests/web.rs diff --git a/src/lib.rs b/src/lib.rs index 9abcce3..2c0c3b5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -123,6 +123,29 @@ impl Universe { pub fn cells(&self) -> *const Cell { self.cells.as_ptr() } + + pub fn set_width(&mut self, width: u32) { + self.width = width; + self.cells = (0..width * self.height).map(|_i| Cell::Dead).collect(); + } + + pub fn set_height(&mut self, height: u32) { + self.height = height; + self.cells = (0..height * self.height).map(|_i| Cell::Dead).collect(); + } +} + +impl Universe { + pub fn get_cells(&self) -> &[Cell] { + &self.cells + } + + pub fn set_cells(&mut self, cells: &[(u32, u32)]) { + for (row, col) in cells.iter().cloned() { + let idx = self.get_index(row, col); + self.cells[idx] = Cell::Alive; + } + } } impl Default for Universe { diff --git a/tests/web.rs b/tests/web.rs new file mode 100644 index 0000000..cfe1aa5 --- /dev/null +++ b/tests/web.rs @@ -0,0 +1,47 @@ +//! Test suite for the Web and headless browsers. + +#![cfg(target_arch = "wasm32")] + +extern crate wasm_bindgen_test; +use wasm_bindgen_test::*; + +use wasm_game_of_life::Universe; + +wasm_bindgen_test_configure!(run_in_browser); + +#[wasm_bindgen_test] +fn pass() { + assert_eq!(1 + 1, 2); +} + +#[cfg(test)] +pub fn input_spaceship() -> Universe { + let mut universe = Universe::new(); + universe.set_width(6); + universe.set_height(6); + universe.set_cells(&[(1, 2), (2, 3), (3, 1), (3, 2), (3, 3)]); + universe +} + +#[cfg(test)] +pub fn expected_spaceship() -> Universe { + let mut universe = Universe::new(); + universe.set_width(6); + universe.set_height(6); + universe.set_cells(&[(2, 1), (2, 3), (3, 2), (3, 3), (4, 2)]); + universe +} + +#[wasm_bindgen_test] +pub fn test_tick() { + // Let's create a smaller Universe with a small spaceship to test! + let mut input_universe = input_spaceship(); + + // This is what our spaceship should look like + // after one tick in our universe. + let expected_universe = expected_spaceship(); + + // Call `tick` and then see if the cells in the `Universe`s are the same. + input_universe.tick(); + assert_eq!(&input_universe.get_cells(), &expected_universe.get_cells()); +}