Compare commits

..

6 Commits

Author SHA1 Message Date
Ryan Walters
d561b446c5 test: remove useless/redundant tests 2025-09-06 12:15:05 -05:00
Ryan Walters
9219c771d7 test: improve input & map_builder test coverage 2025-09-06 12:15:05 -05:00
Ryan Walters
cd501aafc4 test: general game testing 2025-09-06 12:15:05 -05:00
Ryan Walters
feae1ee191 test: add asset tests, file exists & has min size 2025-09-06 12:15:04 -05:00
Ryan Walters
2f0b9825c6 test: blinking system tests 2025-09-06 12:15:04 -05:00
Ryan Walters
cac490565e refactor: use speculoos for all test assertions 2025-09-06 12:15:04 -05:00
19 changed files with 1001 additions and 445 deletions

View File

@@ -359,12 +359,7 @@ impl Map {
+ IVec2::from(Direction::Left.as_ivec2()).as_vec2() * (CELL_SIZE as f32 * 2.0),
},
)
.map_err(|e| {
MapError::InvalidConfig(format!(
"Failed to connect left tunnel entrance to left tunnel hidden node: {}",
e
))
})?
.expect("Failed to connect left tunnel entrance to left tunnel hidden node")
};
// Create the right tunnel nodes
@@ -384,12 +379,7 @@ impl Map {
+ IVec2::from(Direction::Right.as_ivec2()).as_vec2() * (CELL_SIZE as f32 * 2.0),
},
)
.map_err(|e| {
MapError::InvalidConfig(format!(
"Failed to connect right tunnel entrance to right tunnel hidden node: {}",
e
))
})?
.expect("Failed to connect right tunnel entrance to right tunnel hidden node")
};
// Connect the left tunnel hidden node to the right tunnel hidden node
@@ -401,12 +391,7 @@ impl Map {
Some(0.0),
Direction::Left,
)
.map_err(|e| {
MapError::InvalidConfig(format!(
"Failed to connect left tunnel hidden node to right tunnel hidden node: {}",
e
))
})?;
.expect("Failed to connect left tunnel hidden node to right tunnel hidden node");
Ok(())
}

View File

@@ -20,10 +20,10 @@ use crate::{
};
// Touch input constants
const TOUCH_DIRECTION_THRESHOLD: f32 = 10.0;
const TOUCH_EASING_DISTANCE_THRESHOLD: f32 = 1.0;
const MAX_TOUCH_MOVEMENT_SPEED: f32 = 100.0;
const TOUCH_EASING_FACTOR: f32 = 1.5;
pub const TOUCH_DIRECTION_THRESHOLD: f32 = 10.0;
pub const TOUCH_EASING_DISTANCE_THRESHOLD: f32 = 1.0;
pub const MAX_TOUCH_MOVEMENT_SPEED: f32 = 100.0;
pub const TOUCH_EASING_FACTOR: f32 = 1.5;
#[derive(Resource, Default, Debug, Copy, Clone)]
pub enum CursorPosition {
@@ -35,7 +35,7 @@ pub enum CursorPosition {
},
}
#[derive(Resource, Default, Debug)]
#[derive(Resource, Default, Debug, Clone)]
pub struct TouchState {
pub active_touch: Option<TouchData>,
}
@@ -160,7 +160,7 @@ pub fn process_simple_key_events(bindings: &mut Bindings, frame_events: &[Simple
}
/// Calculates the primary direction from a 2D vector delta
fn calculate_direction_from_delta(delta: Vec2) -> Direction {
pub fn calculate_direction_from_delta(delta: Vec2) -> Direction {
if delta.x.abs() > delta.y.abs() {
if delta.x > 0.0 {
Direction::Right
@@ -179,7 +179,7 @@ fn calculate_direction_from_delta(delta: Vec2) -> Direction {
/// This slowly moves the start_pos towards the current_pos, with the speed
/// decreasing as the distance gets smaller. The maximum movement speed is capped.
/// Returns the delta vector and its length for reuse by the caller.
fn update_touch_reference_position(touch_data: &mut TouchData, delta_time: f32) -> (Vec2, f32) {
pub fn update_touch_reference_position(touch_data: &mut TouchData, delta_time: f32) -> (Vec2, f32) {
// Calculate the vector from start to current position
let delta = touch_data.current_pos - touch_data.start_pos;
let distance = delta.length();
@@ -220,16 +220,6 @@ pub fn input_system(
// Collect all events for this frame.
let frame_events: SmallVec<[Event; 3]> = pump.poll_iter().collect();
// Warn if the smallvec was heap allocated due to exceeding stack capacity
#[cfg(debug_assertions)]
if frame_events.len() > frame_events.capacity() {
tracing::warn!(
"More than {} events in a frame, consider adjusting stack capacity: {:?}",
frame_events.capacity(),
frame_events
);
}
// Handle non-keyboard events inline and build a simplified keyboard event stream.
let mut simple_key_events: SmallVec<[SimpleKeyEvent; 3]> = smallvec![];
for event in &frame_events {

17
tests/asset.rs Normal file
View File

@@ -0,0 +1,17 @@
use pacman::asset::Asset;
use speculoos::prelude::*;
use strum::IntoEnumIterator;
#[test]
fn all_asset_paths_exist() {
for asset in Asset::iter() {
let path = asset.path();
let full_path = format!("assets/game/{}", path);
let metadata = std::fs::metadata(&full_path)
.map_err(|e| format!("Error getting metadata for {}: {}", full_path, e))
.unwrap();
assert_that(&metadata.is_file()).is_true();
assert_that(&metadata.len()).is_greater_than(1024);
}
}

316
tests/blinking.rs Normal file
View File

@@ -0,0 +1,316 @@
use bevy_ecs::{entity::Entity, system::RunSystemOnce, world::World};
use pacman::systems::{
blinking::{blinking_system, Blinking},
components::{DeltaTime, Renderable},
Frozen, Hidden,
};
use speculoos::prelude::*;
mod common;
/// Creates a test world with blinking system resources
fn create_blinking_test_world() -> World {
let mut world = World::new();
world.insert_resource(DeltaTime::from_ticks(1));
world
}
/// Spawns a test entity with blinking and renderable components
fn spawn_blinking_entity(world: &mut World, interval_ticks: u32) -> Entity {
world
.spawn((
Blinking::new(interval_ticks),
Renderable {
sprite: common::mock_atlas_tile(1),
layer: 0,
},
))
.id()
}
/// Spawns a test entity with blinking, renderable, and hidden components
fn spawn_hidden_blinking_entity(world: &mut World, interval_ticks: u32) -> Entity {
world
.spawn((
Blinking::new(interval_ticks),
Renderable {
sprite: common::mock_atlas_tile(1),
layer: 0,
},
Hidden,
))
.id()
}
/// Spawns a test entity with blinking, renderable, and frozen components
fn spawn_frozen_blinking_entity(world: &mut World, interval_ticks: u32) -> Entity {
world
.spawn((
Blinking::new(interval_ticks),
Renderable {
sprite: common::mock_atlas_tile(1),
layer: 0,
},
Frozen,
))
.id()
}
/// Spawns a test entity with blinking, renderable, hidden, and frozen components
fn spawn_frozen_hidden_blinking_entity(world: &mut World, interval_ticks: u32) -> Entity {
world
.spawn((
Blinking::new(interval_ticks),
Renderable {
sprite: common::mock_atlas_tile(1),
layer: 0,
},
Hidden,
Frozen,
))
.id()
}
/// Runs the blinking system with the given delta time
fn run_blinking_system(world: &mut World, delta_ticks: u32) {
world.resource_mut::<DeltaTime>().ticks = delta_ticks;
world.run_system_once(blinking_system).unwrap();
}
/// Checks if an entity has the Hidden component
fn has_hidden_component(world: &World, entity: Entity) -> bool {
world.entity(entity).contains::<Hidden>()
}
/// Checks if an entity has the Frozen component
fn has_frozen_component(world: &World, entity: Entity) -> bool {
world.entity(entity).contains::<Frozen>()
}
#[test]
fn test_blinking_component_creation() {
let blinking = Blinking::new(10);
assert_that(&blinking.tick_timer).is_equal_to(0);
assert_that(&blinking.interval_ticks).is_equal_to(10);
}
#[test]
fn test_blinking_system_normal_interval_no_toggle() {
let mut world = create_blinking_test_world();
let entity = spawn_blinking_entity(&mut world, 5);
// Run system with 3 ticks (less than interval)
run_blinking_system(&mut world, 3);
// Entity should not be hidden yet
assert_that(&has_hidden_component(&world, entity)).is_false();
// Check that timer was updated
let blinking = world.entity(entity).get::<Blinking>().unwrap();
assert_that(&blinking.tick_timer).is_equal_to(3);
}
#[test]
fn test_blinking_system_normal_interval_first_toggle() {
let mut world = create_blinking_test_world();
let entity = spawn_blinking_entity(&mut world, 5);
// Run system with 5 ticks (exactly one interval)
run_blinking_system(&mut world, 5);
// Entity should now be hidden
assert_that(&has_hidden_component(&world, entity)).is_true();
// Check that timer was reset
let blinking = world.entity(entity).get::<Blinking>().unwrap();
assert_that(&blinking.tick_timer).is_equal_to(0);
}
#[test]
fn test_blinking_system_normal_interval_second_toggle() {
let mut world = create_blinking_test_world();
let entity = spawn_blinking_entity(&mut world, 5);
// First toggle: 5 ticks
run_blinking_system(&mut world, 5);
assert_that(&has_hidden_component(&world, entity)).is_true();
// Second toggle: another 5 ticks
run_blinking_system(&mut world, 5);
assert_that(&has_hidden_component(&world, entity)).is_false();
}
#[test]
fn test_blinking_system_normal_interval_multiple_intervals() {
let mut world = create_blinking_test_world();
let entity = spawn_blinking_entity(&mut world, 3);
// Run system with 7 ticks (2 complete intervals + 1 remainder)
run_blinking_system(&mut world, 7);
// Should toggle twice (even number), so back to original state (not hidden)
assert_that(&has_hidden_component(&world, entity)).is_false();
// Check that timer was updated to remainder
let blinking = world.entity(entity).get::<Blinking>().unwrap();
assert_that(&blinking.tick_timer).is_equal_to(1);
}
#[test]
fn test_blinking_system_normal_interval_odd_intervals() {
let mut world = create_blinking_test_world();
let entity = spawn_blinking_entity(&mut world, 2);
// Run system with 5 ticks (2 complete intervals + 1 remainder)
run_blinking_system(&mut world, 5);
// Should toggle twice (even number), so back to original state (not hidden)
assert_that(&has_hidden_component(&world, entity)).is_false();
// Check that timer was updated to remainder
let blinking = world.entity(entity).get::<Blinking>().unwrap();
assert_that(&blinking.tick_timer).is_equal_to(1);
}
#[test]
fn test_blinking_system_zero_interval_with_ticks() {
let mut world = create_blinking_test_world();
let entity = spawn_blinking_entity(&mut world, 0);
// Run system with any positive ticks
run_blinking_system(&mut world, 1);
// Entity should be hidden immediately
assert_that(&has_hidden_component(&world, entity)).is_true();
}
#[test]
fn test_blinking_system_zero_interval_no_ticks() {
let mut world = create_blinking_test_world();
let entity = spawn_blinking_entity(&mut world, 0);
// Run system with 0 ticks
run_blinking_system(&mut world, 0);
// Entity should not be hidden (no time passed)
assert_that(&has_hidden_component(&world, entity)).is_false();
}
#[test]
fn test_blinking_system_zero_interval_toggle_back() {
let mut world = create_blinking_test_world();
let entity = spawn_hidden_blinking_entity(&mut world, 0);
// Run system with any positive ticks
run_blinking_system(&mut world, 1);
// Entity should be unhidden
assert_that(&has_hidden_component(&world, entity)).is_false();
}
#[test]
fn test_blinking_system_frozen_entity_unhidden() {
let mut world = create_blinking_test_world();
let entity = spawn_frozen_hidden_blinking_entity(&mut world, 5);
// Run system with ticks
run_blinking_system(&mut world, 10);
// Frozen entity should be unhidden and stay unhidden
assert_that(&has_hidden_component(&world, entity)).is_false();
assert_that(&has_frozen_component(&world, entity)).is_true();
}
#[test]
fn test_blinking_system_frozen_entity_no_blinking() {
let mut world = create_blinking_test_world();
let entity = spawn_frozen_blinking_entity(&mut world, 5);
// Run system with ticks
run_blinking_system(&mut world, 10);
// Frozen entity should not be hidden (blinking disabled)
assert_that(&has_hidden_component(&world, entity)).is_false();
assert_that(&has_frozen_component(&world, entity)).is_true();
}
#[test]
fn test_blinking_system_frozen_entity_timer_not_updated() {
let mut world = create_blinking_test_world();
let entity = spawn_frozen_blinking_entity(&mut world, 5);
// Run system with ticks
run_blinking_system(&mut world, 10);
// Timer should not be updated for frozen entities
let blinking = world.entity(entity).get::<Blinking>().unwrap();
assert_that(&blinking.tick_timer).is_equal_to(0);
}
#[test]
fn test_blinking_system_entity_without_renderable_ignored() {
let mut world = create_blinking_test_world();
// Spawn entity with only Blinking component (no Renderable)
let entity = world.spawn(Blinking::new(5)).id();
// Run system
run_blinking_system(&mut world, 10);
// Entity should not be affected (not in query)
assert_that(&has_hidden_component(&world, entity)).is_false();
}
#[test]
fn test_blinking_system_entity_without_blinking_ignored() {
let mut world = create_blinking_test_world();
// Spawn entity with only Renderable component (no Blinking)
let entity = world
.spawn(Renderable {
sprite: common::mock_atlas_tile(1),
layer: 0,
})
.id();
// Run system
run_blinking_system(&mut world, 10);
// Entity should not be affected (not in query)
assert_that(&has_hidden_component(&world, entity)).is_false();
}
#[test]
fn test_blinking_system_large_interval() {
let mut world = create_blinking_test_world();
let entity = spawn_blinking_entity(&mut world, 1000);
// Run system with 500 ticks (less than interval)
run_blinking_system(&mut world, 500);
// Entity should not be hidden yet
assert_that(&has_hidden_component(&world, entity)).is_false();
// Check that timer was updated
let blinking = world.entity(entity).get::<Blinking>().unwrap();
assert_that(&blinking.tick_timer).is_equal_to(500);
}
#[test]
fn test_blinking_system_very_small_interval() {
let mut world = create_blinking_test_world();
let entity = spawn_blinking_entity(&mut world, 1);
// Run system with 1 tick
run_blinking_system(&mut world, 1);
// Entity should be hidden
assert_that(&has_hidden_component(&world, entity)).is_true();
// Run system with another 1 tick
run_blinking_system(&mut world, 1);
// Entity should be unhidden
assert_that(&has_hidden_component(&world, entity)).is_false();
}

View File

@@ -1,5 +1,6 @@
use bevy_ecs::system::RunSystemOnce;
use pacman::systems::{check_collision, collision_system, Collider, EntityType, GhostState, Position};
use speculoos::prelude::*;
mod common;
@@ -9,8 +10,8 @@ fn test_collider_collision_detection() {
let collider2 = Collider { size: 8.0 };
// Test collision detection
assert!(collider1.collides_with(collider2.size, 5.0)); // Should collide (distance < 9.0)
assert!(!collider1.collides_with(collider2.size, 15.0)); // Should not collide (distance > 9.0)
assert_that(&collider1.collides_with(collider2.size, 5.0)).is_true(); // Should collide (distance < 9.0)
assert_that(&collider1.collides_with(collider2.size, 15.0)).is_false(); // Should not collide (distance > 9.0)
}
#[test]
@@ -23,13 +24,13 @@ fn test_check_collision_helper() {
// Test collision at same position
let result = check_collision(&pos1, &collider1, &pos2, &collider2, &map);
assert!(result.is_ok());
assert!(result.unwrap()); // Should collide at same position
assert_that(&result.is_ok()).is_true();
assert_that(&result.unwrap()).is_true(); // Should collide at same position
// Test collision at different positions
let pos3 = Position::Stopped { node: 1 }; // Different position
let result = check_collision(&pos1, &collider1, &pos3, &collider2, &map);
assert!(result.is_ok());
assert_that(&result.is_ok()).is_true();
// May or may not collide depending on actual node positions
}

View File

@@ -1,35 +0,0 @@
use pacman::constants::*;
#[test]
fn test_raw_board_structure() {
// Test board dimensions match expected size
assert_eq!(RAW_BOARD.len(), BOARD_CELL_SIZE.y as usize);
for row in RAW_BOARD.iter() {
assert_eq!(row.len(), BOARD_CELL_SIZE.x as usize);
}
// Test boundaries are properly walled
assert!(RAW_BOARD[0].chars().all(|c| c == '#'));
assert!(RAW_BOARD[RAW_BOARD.len() - 1].chars().all(|c| c == '#'));
}
#[test]
fn test_raw_board_contains_required_elements() {
// Test that essential game elements are present
assert!(
RAW_BOARD.iter().any(|row| row.contains('X')),
"Board should contain Pac-Man start position"
);
assert!(
RAW_BOARD.iter().any(|row| row.contains("==")),
"Board should contain ghost house door"
);
assert!(
RAW_BOARD.iter().any(|row| row.chars().any(|c| c == 'T')),
"Board should contain tunnel entrances"
);
assert!(
RAW_BOARD.iter().any(|row| row.chars().any(|c| c == 'o')),
"Board should contain power pellets"
);
}

View File

@@ -1,83 +1,15 @@
use pacman::error::{
AssetError, EntityError, GameError, GameResult, IntoGameError, MapError, OptionExt, ParseError, ResultExt, TextureError,
};
use pacman::error::{GameError, GameResult, IntoGameError, OptionExt, ResultExt};
use speculoos::prelude::*;
use std::io;
#[test]
fn test_game_error_from_asset_error() {
let asset_error = AssetError::NotFound("test.png".to_string());
let game_error: GameError = asset_error.into();
assert!(matches!(game_error, GameError::Asset(_)));
}
#[test]
fn test_game_error_from_parse_error() {
let parse_error = ParseError::UnknownCharacter('Z');
let game_error: GameError = parse_error.into();
assert!(matches!(game_error, GameError::MapParse(_)));
}
#[test]
fn test_game_error_from_map_error() {
let map_error = MapError::NodeNotFound(42);
let game_error: GameError = map_error.into();
assert!(matches!(game_error, GameError::Map(_)));
}
#[test]
fn test_game_error_from_texture_error() {
let texture_error = TextureError::LoadFailed("Failed to load".to_string());
let game_error: GameError = texture_error.into();
assert!(matches!(game_error, GameError::Texture(_)));
}
#[test]
fn test_game_error_from_entity_error() {
let entity_error = EntityError::NodeNotFound(10);
let game_error: GameError = entity_error.into();
assert!(matches!(game_error, GameError::Entity(_)));
}
#[test]
fn test_game_error_from_io_error() {
let io_error = io::Error::new(io::ErrorKind::NotFound, "File not found");
let game_error: GameError = io_error.into();
assert!(matches!(game_error, GameError::Io(_)));
}
#[test]
fn test_asset_error_from_io_error() {
let io_error = io::Error::new(io::ErrorKind::PermissionDenied, "Permission denied");
let asset_error: AssetError = io_error.into();
assert!(matches!(asset_error, AssetError::Io(_)));
}
#[test]
fn test_parse_error_display() {
let error = ParseError::UnknownCharacter('!');
assert_eq!(error.to_string(), "Unknown character in board: !");
let error = ParseError::InvalidHouseDoorCount(3);
assert_eq!(error.to_string(), "House door must have exactly 2 positions, found 3");
}
#[test]
fn test_entity_error_display() {
let error = EntityError::NodeNotFound(42);
assert_eq!(error.to_string(), "Node not found in graph: 42");
let error = EntityError::EdgeNotFound { from: 1, to: 2 };
assert_eq!(error.to_string(), "Edge not found: from 1 to 2");
}
#[test]
fn test_into_game_error_trait() {
let result: Result<i32, io::Error> = Err(io::Error::new(io::ErrorKind::Other, "test error"));
let game_result: GameResult<i32> = result.into_game_error();
assert!(game_result.is_err());
assert_that(&game_result.is_err()).is_true();
if let Err(GameError::InvalidState(msg)) = game_result {
assert!(msg.contains("test error"));
assert_that(&msg.contains("test error")).is_true();
} else {
panic!("Expected InvalidState error");
}
@@ -88,7 +20,7 @@ fn test_into_game_error_trait_success() {
let result: Result<i32, io::Error> = Ok(42);
let game_result: GameResult<i32> = result.into_game_error();
assert_eq!(game_result.unwrap(), 42);
assert_that(&game_result.unwrap()).is_equal_to(42);
}
#[test]
@@ -96,7 +28,7 @@ fn test_option_ext_some() {
let option: Option<i32> = Some(42);
let result: GameResult<i32> = option.ok_or_game_error(|| GameError::InvalidState("Not found".to_string()));
assert_eq!(result.unwrap(), 42);
assert_that(&result.unwrap()).is_equal_to(42);
}
#[test]
@@ -104,9 +36,9 @@ fn test_option_ext_none() {
let option: Option<i32> = None;
let result: GameResult<i32> = option.ok_or_game_error(|| GameError::InvalidState("Not found".to_string()));
assert!(result.is_err());
assert_that(&result.is_err()).is_true();
if let Err(GameError::InvalidState(msg)) = result {
assert_eq!(msg, "Not found");
assert_that(&msg).is_equal_to("Not found".to_string());
} else {
panic!("Expected InvalidState error");
}
@@ -117,7 +49,7 @@ fn test_result_ext_success() {
let result: Result<i32, io::Error> = Ok(42);
let game_result: GameResult<i32> = result.with_context(|_| GameError::InvalidState("Context".to_string()));
assert_eq!(game_result.unwrap(), 42);
assert_that(&game_result.unwrap()).is_equal_to(42);
}
#[test]
@@ -125,9 +57,9 @@ fn test_result_ext_error() {
let result: Result<i32, io::Error> = Err(io::Error::new(io::ErrorKind::Other, "original error"));
let game_result: GameResult<i32> = result.with_context(|_| GameError::InvalidState("Context error".to_string()));
assert!(game_result.is_err());
assert_that(&game_result.is_err()).is_true();
if let Err(GameError::InvalidState(msg)) = game_result {
assert_eq!(msg, "Context error");
assert_that(&msg).is_equal_to("Context error".to_string());
} else {
panic!("Expected InvalidState error");
}

View File

@@ -1,8 +1,7 @@
use pacman::systems::profiling::format_timing_display;
use speculoos::prelude::*;
use std::time::Duration;
use pretty_assertions::assert_eq;
fn get_timing_data() -> Vec<(String, Duration, Duration)> {
vec![
("total".to_string(), Duration::from_micros(1234), Duration::from_micros(570)),
@@ -53,45 +52,25 @@ fn test_complex_formatting_alignment() {
});
// Assert that all positions were found
assert_eq!(
[
assert_that(
&[
&colon_positions,
&first_decimal_positions,
&second_decimal_positions,
&first_unit_positions,
&second_unit_positions
&second_unit_positions,
]
.iter()
.all(|p| p.len() == 6),
true
);
)
.is_true();
// Assert that all positions are the same
assert!(
colon_positions.iter().all(|&p| p == colon_positions[0]),
"colon positions are not the same {:?}",
colon_positions
);
assert!(
first_decimal_positions.iter().all(|&p| p == first_decimal_positions[0]),
"first decimal positions are not the same {:?}",
first_decimal_positions
);
assert!(
second_decimal_positions.iter().all(|&p| p == second_decimal_positions[0]),
"second decimal positions are not the same {:?}",
second_decimal_positions
);
assert!(
first_unit_positions.iter().all(|&p| p == first_unit_positions[0]),
"first unit positions are not the same {:?}",
first_unit_positions
);
assert!(
second_unit_positions.iter().all(|&p| p == second_unit_positions[0]),
"second unit positions are not the same {:?}",
second_unit_positions
);
assert_that(&colon_positions.iter().all(|&p| p == colon_positions[0])).is_true();
assert_that(&first_decimal_positions.iter().all(|&p| p == first_decimal_positions[0])).is_true();
assert_that(&second_decimal_positions.iter().all(|&p| p == second_decimal_positions[0])).is_true();
assert_that(&first_unit_positions.iter().all(|&p| p == first_unit_positions[0])).is_true();
assert_that(&second_unit_positions.iter().all(|&p| p == second_unit_positions[0])).is_true();
}
#[test]
@@ -105,17 +84,17 @@ fn test_format_timing_display_basic() {
let formatted = format_timing_display(timing_data);
// Should have 3 lines (one for each system)
assert_eq!(formatted.len(), 3);
assert_that(&formatted.len()).is_equal_to(3);
// Each line should contain the system name
assert!(formatted.iter().any(|line| line.contains("render")));
assert!(formatted.iter().any(|line| line.contains("input")));
assert!(formatted.iter().any(|line| line.contains("physics")));
assert_that(&formatted.iter().any(|line| line.contains("render"))).is_true();
assert_that(&formatted.iter().any(|line| line.contains("input"))).is_true();
assert_that(&formatted.iter().any(|line| line.contains("physics"))).is_true();
// Each line should contain timing information with proper units
for line in formatted.iter() {
assert!(line.contains(":"), "Line should contain colon separator: {}", line);
assert!(line.contains("±"), "Line should contain ± symbol: {}", line);
assert_that(&line.contains(":")).is_true();
assert_that(&line.contains("±")).is_true();
}
}
@@ -132,10 +111,10 @@ fn test_format_timing_display_units() {
// Check that appropriate units are used
let all_lines = formatted.join(" ");
assert!(all_lines.contains("s"), "Should contain seconds unit");
assert!(all_lines.contains("ms"), "Should contain milliseconds unit");
assert!(all_lines.contains("µs"), "Should contain microseconds unit");
assert!(all_lines.contains("ns"), "Should contain nanoseconds unit");
assert_that(&all_lines.contains("s")).is_true();
assert_that(&all_lines.contains("ms")).is_true();
assert_that(&all_lines.contains("µs")).is_true();
assert_that(&all_lines.contains("ns")).is_true();
}
#[test]
@@ -157,9 +136,6 @@ fn test_format_timing_display_alignment() {
// All colons should be at the same position (aligned)
if colon_positions.len() > 1 {
let first_pos = colon_positions[0];
assert!(
colon_positions.iter().all(|&pos| pos == first_pos),
"Colons should be aligned at the same position"
);
assert_that(&colon_positions.iter().all(|&pos| pos == first_pos)).is_true();
}
}

79
tests/game.rs Normal file
View File

@@ -0,0 +1,79 @@
use pacman::error::{GameError, GameResult};
use pacman::game::Game;
use speculoos::prelude::*;
mod common;
use common::setup_sdl;
#[test]
fn test_game_30_seconds_60fps() -> GameResult<()> {
let (canvas, texture_creator, _sdl_context) = setup_sdl().map_err(GameError::Sdl)?;
let ttf_context = sdl2::ttf::init().map_err(GameError::Sdl)?;
let event_pump = _sdl_context
.event_pump()
.map_err(|e| pacman::error::GameError::Sdl(e.to_string()))?;
let mut game = Game::new(canvas, ttf_context, texture_creator, event_pump)?;
// Run for 30 seconds at 60 FPS = 1800 frames
let frame_time = 1.0 / 60.0;
let total_frames = 1800;
let mut frame_count = 0;
for _ in 0..total_frames {
let should_exit = game.tick(frame_time);
if should_exit {
break;
}
frame_count += 1;
}
assert_eq!(
frame_count, total_frames,
"Should have processed exactly {} frames",
total_frames
);
Ok(())
}
/// Test that runs the game for 30 seconds with variable frame timing
#[test]
fn test_game_30_seconds_variable_timing() -> GameResult<()> {
let (canvas, texture_creator, _sdl_context) = setup_sdl().map_err(GameError::Sdl)?;
let ttf_context = sdl2::ttf::init().map_err(|e| GameError::Sdl(e.to_string()))?;
let event_pump = _sdl_context
.event_pump()
.map_err(|e| pacman::error::GameError::Sdl(e.to_string()))?;
let mut game = Game::new(canvas, ttf_context, texture_creator, event_pump)?;
// Simulate 30 seconds with variable frame timing
let mut total_time = 0.0;
let target_time = 30.0;
let mut frame_count = 0;
while total_time < target_time {
// Alternate between different frame rates to simulate real gameplay
let frame_time = match frame_count % 4 {
0 => 1.0 / 60.0, // 60 FPS
1 => 1.0 / 30.0, // 30 FPS (lag spike)
2 => 1.0 / 120.0, // 120 FPS (very fast)
_ => 1.0 / 60.0, // 60 FPS
};
let should_exit = game.tick(frame_time);
if should_exit {
break;
}
total_time += frame_time;
frame_count += 1;
}
assert_that(&total_time).is_greater_than_or_equal_to(target_time);
Ok(())
}

View File

@@ -1,5 +1,6 @@
use pacman::map::direction::Direction;
use pacman::map::graph::{Graph, Node, TraversalFlags};
use speculoos::prelude::*;
mod common;
@@ -13,10 +14,10 @@ fn test_graph_basic_operations() {
position: glam::Vec2::new(16.0, 0.0),
});
assert_eq!(graph.nodes().count(), 2);
assert!(graph.get_node(node1).is_some());
assert!(graph.get_node(node2).is_some());
assert!(graph.get_node(999).is_none());
assert_that(&graph.nodes().count()).is_equal_to(2);
assert_that(&graph.get_node(node1).is_some()).is_true();
assert_that(&graph.get_node(node2).is_some()).is_true();
assert_that(&graph.get_node(999).is_none()).is_true();
}
#[test]
@@ -29,15 +30,15 @@ fn test_graph_connect() {
position: glam::Vec2::new(16.0, 0.0),
});
assert!(graph.connect(node1, node2, false, None, Direction::Right).is_ok());
assert_that(&graph.connect(node1, node2, false, None, Direction::Right).is_ok()).is_true();
let edge1 = graph.find_edge_in_direction(node1, Direction::Right);
let edge2 = graph.find_edge_in_direction(node2, Direction::Left);
assert!(edge1.is_some());
assert!(edge2.is_some());
assert_eq!(edge1.unwrap().target, node2);
assert_eq!(edge2.unwrap().target, node1);
assert_that(&edge1.is_some()).is_true();
assert_that(&edge2.is_some()).is_true();
assert_that(&edge1.unwrap().target).is_equal_to(node2);
assert_that(&edge2.unwrap().target).is_equal_to(node1);
}
#[test]
@@ -47,8 +48,8 @@ fn test_graph_connect_errors() {
position: glam::Vec2::new(0.0, 0.0),
});
assert!(graph.connect(node1, 999, false, None, Direction::Right).is_err());
assert!(graph.connect(999, node1, false, None, Direction::Right).is_err());
assert_that(&graph.connect(node1, 999, false, None, Direction::Right).is_err()).is_true();
assert_that(&graph.connect(999, node1, false, None, Direction::Right).is_err()).is_true();
}
#[test]
@@ -66,7 +67,7 @@ fn test_graph_edge_permissions() {
.unwrap();
let edge = graph.find_edge_in_direction(node1, Direction::Right).unwrap();
assert_eq!(edge.traversal_flags, TraversalFlags::GHOST);
assert_that(&edge.traversal_flags).is_equal_to(TraversalFlags::GHOST);
}
#[test]
@@ -86,10 +87,10 @@ fn should_add_connected_node() {
)
.unwrap();
assert_eq!(graph.nodes().count(), 2);
assert_that(&graph.nodes().count()).is_equal_to(2);
let edge = graph.find_edge(node1, node2);
assert!(edge.is_some());
assert_eq!(edge.unwrap().direction, Direction::Right);
assert_that(&edge.is_some()).is_true();
assert_that(&edge.unwrap().direction).is_equal_to(Direction::Right);
}
#[test]
@@ -103,33 +104,33 @@ fn should_error_on_negative_edge_distance() {
});
let result = graph.add_edge(node1, node2, false, Some(-1.0), Direction::Right, TraversalFlags::ALL);
assert!(result.is_err());
assert_that(&result.is_err()).is_true();
}
#[test]
fn should_error_on_duplicate_edge_without_replace() {
let mut graph = common::create_test_graph();
let result = graph.add_edge(0, 1, false, None, Direction::Right, TraversalFlags::ALL);
assert!(result.is_err());
assert_that(&result.is_err()).is_true();
}
#[test]
fn should_allow_replacing_an_edge() {
let mut graph = common::create_test_graph();
let result = graph.add_edge(0, 1, true, Some(42.0), Direction::Right, TraversalFlags::ALL);
assert!(result.is_ok());
assert_that(&result.is_ok()).is_true();
let edge = graph.find_edge(0, 1).unwrap();
assert_eq!(edge.distance, 42.0);
assert_that(&edge.distance).is_equal_to(42.0);
}
#[test]
fn should_find_edge_between_nodes() {
let graph = common::create_test_graph();
let edge = graph.find_edge(0, 1);
assert!(edge.is_some());
assert_eq!(edge.unwrap().target, 1);
assert_that(&edge.is_some()).is_true();
assert_that(&edge.unwrap().target).is_equal_to(1);
let non_existent_edge = graph.find_edge(0, 99);
assert!(non_existent_edge.is_none());
assert_that(&non_existent_edge.is_none()).is_true();
}

View File

@@ -1,38 +1,321 @@
use glam::Vec2;
use pacman::events::{GameCommand, GameEvent};
use pacman::map::direction::Direction;
use pacman::systems::input::{process_simple_key_events, Bindings, SimpleKeyEvent};
use pacman::systems::input::{
calculate_direction_from_delta, process_simple_key_events, update_touch_reference_position, Bindings, CursorPosition,
SimpleKeyEvent, TouchData, TouchState, TOUCH_DIRECTION_THRESHOLD, TOUCH_EASING_DISTANCE_THRESHOLD,
};
use sdl2::keyboard::Keycode;
use speculoos::prelude::*;
#[test]
fn resumes_previous_direction_when_secondary_key_released() {
let mut bindings = Bindings::default();
// Test modules for better organization
mod keyboard_tests {
use super::*;
// Frame 1: Press W (Up) => emits Move Up
let events = process_simple_key_events(&mut bindings, &[SimpleKeyEvent::KeyDown(Keycode::W)]);
assert!(events.contains(&GameEvent::Command(GameCommand::MovePlayer(Direction::Up))));
#[test]
fn key_down_emits_bound_command() {
let mut bindings = Bindings::default();
let events = process_simple_key_events(&mut bindings, &[SimpleKeyEvent::KeyDown(Keycode::W)]);
assert_that(&events).contains(GameEvent::Command(GameCommand::MovePlayer(Direction::Up)));
}
// Frame 2: Press D (Right) => emits Move Right
let events = process_simple_key_events(&mut bindings, &[SimpleKeyEvent::KeyDown(Keycode::D)]);
assert!(events.contains(&GameEvent::Command(GameCommand::MovePlayer(Direction::Right))));
#[test]
fn key_down_emits_non_movement_commands() {
let mut bindings = Bindings::default();
let events = process_simple_key_events(&mut bindings, &[SimpleKeyEvent::KeyDown(Keycode::P)]);
assert_that(&events).contains(GameEvent::Command(GameCommand::TogglePause));
}
// Frame 3: Release D, no new key this frame => should continue previous key W (Up)
let events = process_simple_key_events(&mut bindings, &[SimpleKeyEvent::KeyUp(Keycode::D)]);
assert!(events.contains(&GameEvent::Command(GameCommand::MovePlayer(Direction::Up))));
#[test]
fn unbound_key_emits_nothing() {
let mut bindings = Bindings::default();
let events = process_simple_key_events(&mut bindings, &[SimpleKeyEvent::KeyDown(Keycode::Z)]);
assert_that(&events).is_empty();
}
#[test]
fn movement_key_held_continues_across_frames() {
let mut bindings = Bindings::default();
process_simple_key_events(&mut bindings, &[SimpleKeyEvent::KeyDown(Keycode::Left)]);
let events = process_simple_key_events(&mut bindings, &[]);
assert_that(&events).contains(GameEvent::Command(GameCommand::MovePlayer(Direction::Left)));
}
#[test]
fn releasing_movement_key_stops_continuation() {
let mut bindings = Bindings::default();
process_simple_key_events(&mut bindings, &[SimpleKeyEvent::KeyDown(Keycode::Up)]);
let events = process_simple_key_events(&mut bindings, &[SimpleKeyEvent::KeyUp(Keycode::Up)]);
assert_that(&events).is_empty();
}
#[test]
fn multiple_movement_keys_resumes_previous_when_current_released() {
let mut bindings = Bindings::default();
process_simple_key_events(&mut bindings, &[SimpleKeyEvent::KeyDown(Keycode::W)]);
process_simple_key_events(&mut bindings, &[SimpleKeyEvent::KeyDown(Keycode::D)]);
let events = process_simple_key_events(&mut bindings, &[SimpleKeyEvent::KeyUp(Keycode::D)]);
assert_that(&events).contains(GameEvent::Command(GameCommand::MovePlayer(Direction::Up)));
}
}
#[test]
fn holds_last_pressed_key_across_frames_when_no_new_input() {
let mut bindings = Bindings::default();
mod direction_calculation_tests {
use super::*;
// Frame 1: Press Left
let events = process_simple_key_events(&mut bindings, &[SimpleKeyEvent::KeyDown(Keycode::Left)]);
assert!(events.contains(&GameEvent::Command(GameCommand::MovePlayer(Direction::Left))));
#[test]
fn prioritizes_horizontal_movement() {
let test_cases = vec![
(Vec2::new(6.0, 5.0), Direction::Right),
(Vec2::new(-6.0, 5.0), Direction::Left),
];
// Frame 2: No input => continues Left
let events = process_simple_key_events(&mut bindings, &[]);
assert!(events.contains(&GameEvent::Command(GameCommand::MovePlayer(Direction::Left))));
for (delta, expected) in test_cases {
assert_that(&calculate_direction_from_delta(delta)).is_equal_to(expected);
}
}
// Frame 3: Release Left, no input remains => nothing emitted
let events = process_simple_key_events(&mut bindings, &[SimpleKeyEvent::KeyUp(Keycode::Left)]);
assert!(events.is_empty());
#[test]
fn uses_vertical_when_dominant() {
let test_cases = vec![
(Vec2::new(3.0, 10.0), Direction::Down),
(Vec2::new(3.0, -10.0), Direction::Up),
];
for (delta, expected) in test_cases {
assert_that(&calculate_direction_from_delta(delta)).is_equal_to(expected);
}
}
#[test]
fn handles_zero_delta() {
let delta = Vec2::ZERO;
// Should default to Up when both components are zero
assert_that(&calculate_direction_from_delta(delta)).is_equal_to(Direction::Up);
}
#[test]
fn handles_equal_magnitudes() {
// When x and y have equal absolute values, should prioritize vertical
let delta = Vec2::new(5.0, 5.0);
assert_that(&calculate_direction_from_delta(delta)).is_equal_to(Direction::Down);
let delta = Vec2::new(-5.0, 5.0);
assert_that(&calculate_direction_from_delta(delta)).is_equal_to(Direction::Down);
}
}
mod touch_easing_tests {
use super::*;
#[test]
fn easing_within_threshold_does_nothing() {
let mut touch_data = TouchData::new(0, Vec2::new(100.0, 100.0));
touch_data.current_pos = Vec2::new(100.0 + TOUCH_EASING_DISTANCE_THRESHOLD - 0.1, 100.0);
let (_delta, distance) = update_touch_reference_position(&mut touch_data, 0.016);
assert_that(&distance).is_less_than(TOUCH_EASING_DISTANCE_THRESHOLD);
assert_that(&touch_data.start_pos).is_equal_to(Vec2::new(100.0, 100.0));
}
#[test]
fn easing_beyond_threshold_moves_towards_target() {
let mut touch_data = TouchData::new(0, Vec2::new(100.0, 100.0));
touch_data.current_pos = Vec2::new(150.0, 100.0);
let original_start_pos = touch_data.start_pos;
let (_delta, distance) = update_touch_reference_position(&mut touch_data, 0.016);
assert_that(&distance).is_greater_than(TOUCH_EASING_DISTANCE_THRESHOLD);
assert_that(&touch_data.start_pos.x).is_greater_than(original_start_pos.x);
assert_that(&touch_data.start_pos.x).is_less_than(touch_data.current_pos.x);
}
#[test]
fn easing_overshoot_sets_to_target() {
let mut touch_data = TouchData::new(0, Vec2::new(100.0, 100.0));
touch_data.current_pos = Vec2::new(101.0, 100.0);
let (_delta, _distance) = update_touch_reference_position(&mut touch_data, 10.0);
assert_that(&touch_data.start_pos).is_equal_to(touch_data.current_pos);
}
#[test]
fn easing_returns_correct_delta() {
let mut touch_data = TouchData::new(0, Vec2::new(100.0, 100.0));
touch_data.current_pos = Vec2::new(120.0, 110.0);
let (delta, distance) = update_touch_reference_position(&mut touch_data, 0.016);
let expected_delta = Vec2::new(20.0, 10.0);
let expected_distance = expected_delta.length();
assert_that(&delta).is_equal_to(expected_delta);
assert_that(&distance).is_equal_to(expected_distance);
}
}
// Integration tests for the full input system
mod integration_tests {
use super::*;
fn mouse_motion_event(x: i32, y: i32) -> sdl2::event::Event {
sdl2::event::Event::MouseMotion {
x,
y,
xrel: 0,
yrel: 0,
mousestate: sdl2::mouse::MouseState::from_sdl_state(0),
which: 0,
window_id: 0,
timestamp: 0,
}
}
fn mouse_button_down_event(x: i32, y: i32) -> sdl2::event::Event {
sdl2::event::Event::MouseButtonDown {
x,
y,
mouse_btn: sdl2::mouse::MouseButton::Left,
clicks: 1,
which: 0,
window_id: 0,
timestamp: 0,
}
}
fn mouse_button_up_event(x: i32, y: i32) -> sdl2::event::Event {
sdl2::event::Event::MouseButtonUp {
x,
y,
mouse_btn: sdl2::mouse::MouseButton::Left,
clicks: 1,
which: 0,
window_id: 0,
timestamp: 0,
}
}
// Simplified helper for testing SDL integration
fn run_input_system_with_events(events: Vec<sdl2::event::Event>, delta_time: f32) -> (CursorPosition, TouchState) {
use bevy_ecs::{event::Events, system::RunSystemOnce, world::World};
use pacman::systems::components::DeltaTime;
use pacman::systems::input::input_system;
let sdl_context = sdl2::init().expect("Failed to initialize SDL");
let event_subsystem = sdl_context.event().expect("Failed to get event subsystem");
let event_pump = sdl_context.event_pump().expect("Failed to create event pump");
let mut world = World::new();
world.insert_resource(Events::<GameEvent>::default());
world.insert_resource(DeltaTime {
seconds: delta_time,
ticks: 1,
});
world.insert_resource(Bindings::default());
world.insert_resource(CursorPosition::None);
world.insert_resource(TouchState::default());
world.insert_non_send_resource(event_pump);
// Inject events into SDL's event queue
for event in events {
event_subsystem.push_event(event).expect("Failed to push event");
}
// Run the real input system
world
.run_system_once(input_system)
.expect("Input system should run successfully");
let cursor = *world.resource::<CursorPosition>();
let touch_state = world.resource::<TouchState>().clone();
(cursor, touch_state)
}
#[test]
fn mouse_motion_updates_cursor_position() {
let events = vec![mouse_motion_event(100, 200)];
let (cursor, _touch_state) = run_input_system_with_events(events, 0.016);
match cursor {
CursorPosition::Some {
position,
remaining_time,
} => {
assert_that(&position).is_equal_to(Vec2::new(100.0, 200.0));
assert_that(&remaining_time).is_equal_to(0.20);
}
CursorPosition::None => panic!("Expected cursor position to be set"),
}
}
#[test]
fn mouse_button_down_starts_touch() {
let events = vec![mouse_button_down_event(150, 250)];
let (_cursor, touch_state) = run_input_system_with_events(events, 0.016);
assert_that(&touch_state.active_touch).is_some();
if let Some(touch_data) = &touch_state.active_touch {
assert_that(&touch_data.finger_id).is_equal_to(0);
assert_that(&touch_data.start_pos).is_equal_to(Vec2::new(150.0, 250.0));
}
}
#[test]
fn mouse_button_up_ends_touch() {
let events = vec![mouse_button_down_event(150, 250), mouse_button_up_event(150, 250)];
let (_cursor, touch_state) = run_input_system_with_events(events, 0.016);
assert_that(&touch_state.active_touch).is_none();
}
}
// Touch direction tests
mod touch_direction_tests {
use super::*;
#[test]
fn movement_above_threshold_emits_direction() {
let mut touch_data = TouchData::new(1, Vec2::new(100.0, 100.0));
touch_data.current_pos = Vec2::new(100.0 + TOUCH_DIRECTION_THRESHOLD + 5.0, 100.0);
let (delta, distance) = update_touch_reference_position(&mut touch_data, 0.016);
assert_that(&distance).is_greater_than_or_equal_to(TOUCH_DIRECTION_THRESHOLD);
let direction = calculate_direction_from_delta(delta);
assert_that(&direction).is_equal_to(Direction::Right);
}
#[test]
fn movement_below_threshold_no_direction() {
let mut touch_data = TouchData::new(1, Vec2::new(100.0, 100.0));
touch_data.current_pos = Vec2::new(100.0 + TOUCH_DIRECTION_THRESHOLD - 1.0, 100.0);
let (_delta, distance) = update_touch_reference_position(&mut touch_data, 0.016);
assert_that(&distance).is_less_than(TOUCH_DIRECTION_THRESHOLD);
}
#[test]
fn all_directions_work_correctly() {
let test_cases = vec![
(Vec2::new(TOUCH_DIRECTION_THRESHOLD + 5.0, 0.0), Direction::Right),
(Vec2::new(-TOUCH_DIRECTION_THRESHOLD - 5.0, 0.0), Direction::Left),
(Vec2::new(0.0, TOUCH_DIRECTION_THRESHOLD + 5.0), Direction::Down),
(Vec2::new(0.0, -TOUCH_DIRECTION_THRESHOLD - 5.0), Direction::Up),
];
for (offset, expected_direction) in test_cases {
let mut touch_data = TouchData::new(1, Vec2::new(100.0, 100.0));
touch_data.current_pos = Vec2::new(100.0, 100.0) + offset;
let (delta, distance) = update_touch_reference_position(&mut touch_data, 0.016);
assert_that(&distance).is_greater_than_or_equal_to(TOUCH_DIRECTION_THRESHOLD);
let direction = calculate_direction_from_delta(delta);
assert_that(&direction).is_equal_to(expected_direction);
}
}
}

View File

@@ -1,41 +1,42 @@
use bevy_ecs::{entity::Entity, system::RunSystemOnce};
use pacman::systems::{is_valid_item_collision, item_system, EntityType, GhostState, Position, ScoreResource};
use speculoos::prelude::*;
mod common;
#[test]
fn test_calculate_score_for_item() {
assert!(EntityType::Pellet.score_value() < EntityType::PowerPellet.score_value());
assert!(EntityType::Pellet.score_value().is_some());
assert!(EntityType::PowerPellet.score_value().is_some());
assert!(EntityType::Player.score_value().is_none());
assert!(EntityType::Ghost.score_value().is_none());
assert_that(&(EntityType::Pellet.score_value() < EntityType::PowerPellet.score_value())).is_true();
assert_that(&EntityType::Pellet.score_value().is_some()).is_true();
assert_that(&EntityType::PowerPellet.score_value().is_some()).is_true();
assert_that(&EntityType::Player.score_value().is_none()).is_true();
assert_that(&EntityType::Ghost.score_value().is_none()).is_true();
}
#[test]
fn test_is_collectible_item() {
// Collectible
assert!(EntityType::Pellet.is_collectible());
assert!(EntityType::PowerPellet.is_collectible());
assert_that(&EntityType::Pellet.is_collectible()).is_true();
assert_that(&EntityType::PowerPellet.is_collectible()).is_true();
// Non-collectible
assert!(!EntityType::Player.is_collectible());
assert!(!EntityType::Ghost.is_collectible());
assert_that(&EntityType::Player.is_collectible()).is_false();
assert_that(&EntityType::Ghost.is_collectible()).is_false();
}
#[test]
fn test_is_valid_item_collision() {
// Player-item collisions should be valid
assert!(is_valid_item_collision(EntityType::Player, EntityType::Pellet));
assert!(is_valid_item_collision(EntityType::Player, EntityType::PowerPellet));
assert!(is_valid_item_collision(EntityType::Pellet, EntityType::Player));
assert!(is_valid_item_collision(EntityType::PowerPellet, EntityType::Player));
assert_that(&is_valid_item_collision(EntityType::Player, EntityType::Pellet)).is_true();
assert_that(&is_valid_item_collision(EntityType::Player, EntityType::PowerPellet)).is_true();
assert_that(&is_valid_item_collision(EntityType::Pellet, EntityType::Player)).is_true();
assert_that(&is_valid_item_collision(EntityType::PowerPellet, EntityType::Player)).is_true();
// Non-player-item collisions should be invalid
assert!(!is_valid_item_collision(EntityType::Player, EntityType::Ghost));
assert!(!is_valid_item_collision(EntityType::Ghost, EntityType::Pellet));
assert!(!is_valid_item_collision(EntityType::Pellet, EntityType::PowerPellet));
assert!(!is_valid_item_collision(EntityType::Player, EntityType::Player));
assert_that(&is_valid_item_collision(EntityType::Player, EntityType::Ghost)).is_false();
assert_that(&is_valid_item_collision(EntityType::Ghost, EntityType::Pellet)).is_false();
assert_that(&is_valid_item_collision(EntityType::Pellet, EntityType::PowerPellet)).is_false();
assert_that(&is_valid_item_collision(EntityType::Player, EntityType::Player)).is_false();
}
#[test]
@@ -52,7 +53,7 @@ fn test_item_system_pellet_collection() {
// Check that score was updated
let score = world.resource::<ScoreResource>();
assert_eq!(score.0, 10);
assert_that(&score.0).is_equal_to(10);
// Check that the pellet was despawned (query should return empty)
let item_count = world
@@ -60,7 +61,7 @@ fn test_item_system_pellet_collection() {
.iter(&world)
.filter(|&entity_type| matches!(entity_type, EntityType::Pellet))
.count();
assert_eq!(item_count, 0);
assert_that(&item_count).is_equal_to(0);
}
#[test]
@@ -75,7 +76,7 @@ fn test_item_system_power_pellet_collection() {
// Check that score was updated with power pellet value
let score = world.resource::<ScoreResource>();
assert_eq!(score.0, 50);
assert_that(&score.0).is_equal_to(50);
// Check that the power pellet was despawned (query should return empty)
let item_count = world
@@ -83,7 +84,7 @@ fn test_item_system_power_pellet_collection() {
.iter(&world)
.filter(|&entity_type| matches!(entity_type, EntityType::PowerPellet))
.count();
assert_eq!(item_count, 0);
assert_that(&item_count).is_equal_to(0);
}
#[test]
@@ -103,7 +104,7 @@ fn test_item_system_multiple_collections() {
// Check final score: 2 pellets (20) + 1 power pellet (50) = 70
let score = world.resource::<ScoreResource>();
assert_eq!(score.0, 70);
assert_that(&score.0).is_equal_to(70);
// Check that all items were despawned
let pellet_count = world
@@ -116,8 +117,8 @@ fn test_item_system_multiple_collections() {
.iter(&world)
.filter(|&entity_type| matches!(entity_type, EntityType::PowerPellet))
.count();
assert_eq!(pellet_count, 0);
assert_eq!(power_pellet_count, 0);
assert_that(&pellet_count).is_equal_to(0);
assert_that(&power_pellet_count).is_equal_to(0);
}
#[test]
@@ -138,7 +139,7 @@ fn test_item_system_ignores_non_item_collisions() {
// Score should remain unchanged
let score = world.resource::<ScoreResource>();
assert_eq!(score.0, initial_score);
assert_that(&score.0).is_equal_to(initial_score);
// Ghost should still exist (not despawned)
let ghost_count = world
@@ -146,7 +147,7 @@ fn test_item_system_ignores_non_item_collisions() {
.iter(&world)
.filter(|&entity_type| matches!(entity_type, EntityType::Ghost))
.count();
assert_eq!(ghost_count, 1);
assert_that(&ghost_count).is_equal_to(1);
}
#[test]
@@ -162,13 +163,13 @@ fn test_item_system_no_collision_events() {
// Nothing should change
let score = world.resource::<ScoreResource>();
assert_eq!(score.0, initial_score);
assert_that(&score.0).is_equal_to(initial_score);
let pellet_count = world
.query::<&EntityType>()
.iter(&world)
.filter(|&entity_type| matches!(entity_type, EntityType::Pellet))
.count();
assert_eq!(pellet_count, 1);
assert_that(&pellet_count).is_equal_to(1);
}
#[test]
@@ -188,7 +189,7 @@ fn test_item_system_collision_with_missing_entity() {
// Score should remain unchanged
let score = world.resource::<ScoreResource>();
assert_eq!(score.0, 0);
assert_that(&score.0).is_equal_to(0);
}
#[test]
@@ -207,7 +208,7 @@ fn test_item_system_preserves_existing_score() {
// Score should be initial + pellet value
let score = world.resource::<ScoreResource>();
assert_eq!(score.0, 110);
assert_that(&score.0).is_equal_to(110);
}
#[test]
@@ -228,7 +229,7 @@ fn test_power_pellet_does_not_affect_ghosts_in_eyes_state() {
// Check that the power pellet was collected and score updated
let score = world.resource::<ScoreResource>();
assert_eq!(score.0, 50);
assert_that(&score.0).is_equal_to(50);
// Check that the power pellet was despawned
let power_pellet_count = world
@@ -236,13 +237,13 @@ fn test_power_pellet_does_not_affect_ghosts_in_eyes_state() {
.iter(&world)
.filter(|&entity_type| matches!(entity_type, EntityType::PowerPellet))
.count();
assert_eq!(power_pellet_count, 0);
assert_that(&power_pellet_count).is_equal_to(0);
// Check that the Eyes ghost state was not changed
let eyes_ghost_state = world.entity(eyes_ghost).get::<GhostState>().unwrap();
assert!(matches!(*eyes_ghost_state, GhostState::Eyes));
assert_that(&matches!(*eyes_ghost_state, GhostState::Eyes)).is_true();
// Check that the Normal ghost state was changed to Frightened
let normal_ghost_state = world.entity(normal_ghost).get::<GhostState>().unwrap();
assert!(matches!(*normal_ghost_state, GhostState::Frightened { .. }));
assert_that(&matches!(*normal_ghost_state, GhostState::Frightened { .. })).is_true();
}

View File

@@ -1,13 +1,15 @@
use glam::Vec2;
use pacman::constants::{CELL_SIZE, RAW_BOARD};
use pacman::map::builder::Map;
use pacman::map::graph::TraversalFlags;
use speculoos::prelude::*;
#[test]
fn test_map_creation() {
fn test_map_creation_success() {
let map = Map::new(RAW_BOARD).unwrap();
assert!(map.graph.nodes().count() > 0);
assert!(!map.grid_to_node.is_empty());
assert_that(&map.graph.nodes().count()).is_greater_than(0);
assert_that(&map.grid_to_node.is_empty()).is_false();
// Check that some connections were made
let mut has_connections = false;
@@ -17,11 +19,11 @@ fn test_map_creation() {
break;
}
}
assert!(has_connections);
assert_that(&has_connections).is_true();
}
#[test]
fn test_map_node_positions() {
fn test_map_node_positions_accuracy() {
let map = Map::new(RAW_BOARD).unwrap();
for (grid_pos, &node_id) in &map.grid_to_node {
@@ -31,6 +33,57 @@ fn test_map_node_positions() {
(grid_pos.y as i32 * CELL_SIZE as i32) as f32,
) + Vec2::splat(CELL_SIZE as f32 / 2.0);
assert_eq!(node.position, expected_pos);
assert_that(&node.position).is_equal_to(expected_pos);
}
}
#[test]
fn test_start_positions_are_valid() {
let map = Map::new(RAW_BOARD).unwrap();
let positions = &map.start_positions;
// All start positions should exist in the graph
assert_that(&map.graph.get_node(positions.pacman)).is_some();
assert_that(&map.graph.get_node(positions.blinky)).is_some();
assert_that(&map.graph.get_node(positions.pinky)).is_some();
assert_that(&map.graph.get_node(positions.inky)).is_some();
assert_that(&map.graph.get_node(positions.clyde)).is_some();
}
#[test]
fn test_ghost_house_has_ghost_only_entrance() {
let map = Map::new(RAW_BOARD).unwrap();
// Find the house entrance node
let house_entrance = map.start_positions.blinky;
// Check that there's a ghost-only connection from the house entrance
let mut has_ghost_only_connection = false;
for edge in map.graph.adjacency_list[house_entrance as usize].edges() {
if edge.traversal_flags == TraversalFlags::GHOST {
has_ghost_only_connection = true;
break;
}
}
assert_that(&has_ghost_only_connection).is_true();
}
#[test]
fn test_tunnel_connections_exist() {
let map = Map::new(RAW_BOARD).unwrap();
// Find tunnel nodes by looking for nodes with zero-distance connections
let mut has_tunnel_connection = false;
for intersection in &map.graph.adjacency_list {
for edge in intersection.edges() {
if edge.distance == 0.0f32 {
has_tunnel_connection = true;
break;
}
}
if has_tunnel_connection {
break;
}
}
assert_that(&has_tunnel_connection).is_true();
}

View File

@@ -1,6 +1,7 @@
use glam::Vec2;
use pacman::map::direction::Direction;
use pacman::systems::movement::{BufferedDirection, Position, Velocity};
use speculoos::prelude::*;
mod common;
@@ -13,8 +14,8 @@ fn test_position_is_at_node() {
remaining_distance: 8.0,
};
assert!(stopped_pos.is_at_node());
assert!(!moving_pos.is_at_node());
assert_that(&stopped_pos.is_at_node()).is_true();
assert_that(&moving_pos.is_at_node()).is_false();
}
#[test]
@@ -26,8 +27,8 @@ fn test_position_current_node() {
remaining_distance: 12.0,
};
assert_eq!(stopped_pos.current_node(), 5);
assert_eq!(moving_pos.current_node(), 3);
assert_that(&stopped_pos.current_node()).is_equal_to(5);
assert_that(&moving_pos.current_node()).is_equal_to(3);
}
#[test]
@@ -35,8 +36,8 @@ fn test_position_tick_no_movement_when_stopped() {
let mut pos = Position::Stopped { node: 0 };
let result = pos.tick(5.0);
assert!(result.is_none());
assert_eq!(pos, Position::Stopped { node: 0 });
assert_that(&result.is_none()).is_true();
assert_that(&pos).is_equal_to(Position::Stopped { node: 0 });
}
#[test]
@@ -48,15 +49,12 @@ fn test_position_tick_no_movement_when_zero_distance() {
};
let result = pos.tick(0.0);
assert!(result.is_none());
assert_eq!(
pos,
Position::Moving {
from: 0,
to: 1,
remaining_distance: 10.0,
}
);
assert_that(&result.is_none()).is_true();
assert_that(&pos).is_equal_to(Position::Moving {
from: 0,
to: 1,
remaining_distance: 10.0,
});
}
#[test]
@@ -68,15 +66,12 @@ fn test_position_tick_partial_movement() {
};
let result = pos.tick(3.0);
assert!(result.is_none());
assert_eq!(
pos,
Position::Moving {
from: 0,
to: 1,
remaining_distance: 7.0,
}
);
assert_that(&result.is_none()).is_true();
assert_that(&pos).is_equal_to(Position::Moving {
from: 0,
to: 1,
remaining_distance: 7.0,
});
}
#[test]
@@ -88,8 +83,8 @@ fn test_position_tick_exact_arrival() {
};
let result = pos.tick(5.0);
assert!(result.is_none());
assert_eq!(pos, Position::Stopped { node: 1 });
assert_that(&result.is_none()).is_true();
assert_that(&pos).is_equal_to(Position::Stopped { node: 1 });
}
#[test]
@@ -101,8 +96,8 @@ fn test_position_tick_overshoot_with_overflow() {
};
let result = pos.tick(8.0);
assert_eq!(result, Some(5.0));
assert_eq!(pos, Position::Stopped { node: 1 });
assert_that(&result).is_equal_to(Some(5.0));
assert_that(&pos).is_equal_to(Position::Stopped { node: 1 });
}
#[test]
@@ -116,7 +111,7 @@ fn test_position_get_pixel_position_stopped() {
0.0 + pacman::constants::BOARD_PIXEL_OFFSET.y as f32,
);
assert_eq!(pixel_pos, expected);
assert_that(&pixel_pos).is_equal_to(expected);
}
#[test]
@@ -135,7 +130,7 @@ fn test_position_get_pixel_position_moving() {
0.0 + pacman::constants::BOARD_PIXEL_OFFSET.y as f32,
);
assert_eq!(pixel_pos, expected);
assert_that(&pixel_pos).is_equal_to(expected);
}
#[test]
@@ -145,14 +140,14 @@ fn test_velocity_basic_properties() {
direction: Direction::Up,
};
assert_eq!(velocity.speed, 2.5);
assert_eq!(velocity.direction, Direction::Up);
assert_that(&velocity.speed).is_equal_to(2.5);
assert_that(&velocity.direction).is_equal_to(Direction::Up);
}
#[test]
fn test_buffered_direction_none() {
let buffered = BufferedDirection::None;
assert_eq!(buffered, BufferedDirection::None);
assert_that(&buffered).is_equal_to(BufferedDirection::None);
}
#[test]
@@ -167,8 +162,8 @@ fn test_buffered_direction_some() {
remaining_time,
} = buffered
{
assert_eq!(direction, Direction::Left);
assert_eq!(remaining_time, 0.5);
assert_that(&direction).is_equal_to(Direction::Left);
assert_that(&remaining_time).is_equal_to(0.5);
} else {
panic!("Expected BufferedDirection::Some");
}

View File

@@ -1,6 +1,7 @@
use pacman::constants::{BOARD_CELL_SIZE, RAW_BOARD};
use pacman::error::ParseError;
use pacman::map::parser::MapTileParser;
use speculoos::prelude::*;
#[test]
fn test_parse_character() {
@@ -15,25 +16,25 @@ fn test_parse_character() {
];
for (char, _expected) in test_cases {
assert!(matches!(MapTileParser::parse_character(char).unwrap(), _expected));
assert_that(&matches!(MapTileParser::parse_character(char).unwrap(), _expected)).is_true();
}
assert!(MapTileParser::parse_character('Z').is_err());
assert_that(&MapTileParser::parse_character('Z').is_err()).is_true();
}
#[test]
fn test_parse_board() {
let result = MapTileParser::parse_board(RAW_BOARD);
assert!(result.is_ok());
assert_that(&result.is_ok()).is_true();
let parsed = result.unwrap();
assert_eq!(parsed.tiles.len(), BOARD_CELL_SIZE.x as usize);
assert_eq!(parsed.tiles[0].len(), BOARD_CELL_SIZE.y as usize);
assert!(parsed.house_door[0].is_some());
assert!(parsed.house_door[1].is_some());
assert!(parsed.tunnel_ends[0].is_some());
assert!(parsed.tunnel_ends[1].is_some());
assert!(parsed.pacman_start.is_some());
assert_that(&parsed.tiles.len()).is_equal_to(BOARD_CELL_SIZE.x as usize);
assert_that(&parsed.tiles[0].len()).is_equal_to(BOARD_CELL_SIZE.y as usize);
assert_that(&parsed.house_door[0].is_some()).is_true();
assert_that(&parsed.house_door[1].is_some()).is_true();
assert_that(&parsed.tunnel_ends[0].is_some()).is_true();
assert_that(&parsed.tunnel_ends[1].is_some()).is_true();
assert_that(&parsed.pacman_start.is_some()).is_true();
}
#[test]
@@ -42,6 +43,6 @@ fn test_parse_board_invalid_character() {
invalid_board[0] = "###########################Z".to_string();
let result = MapTileParser::parse_board(invalid_board.each_ref().map(|s| s.as_str()));
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), ParseError::UnknownCharacter('Z')));
assert_that(&result.is_err()).is_true();
assert_that(&matches!(result.unwrap_err(), ParseError::UnknownCharacter('Z'))).is_true();
}

View File

@@ -10,6 +10,7 @@ use pacman::{
EntityType, GlobalState, Position, Velocity,
},
};
use speculoos::prelude::*;
mod common;
@@ -22,7 +23,7 @@ fn test_can_traverse_player_on_all_edges() {
traversal_flags: TraversalFlags::ALL,
};
assert!(can_traverse(EntityType::Player, edge));
assert_that(&can_traverse(EntityType::Player, edge)).is_true();
}
#[test]
@@ -34,7 +35,7 @@ fn test_can_traverse_player_on_pacman_only_edges() {
traversal_flags: TraversalFlags::PACMAN,
};
assert!(can_traverse(EntityType::Player, edge));
assert_that(&can_traverse(EntityType::Player, edge)).is_true();
}
#[test]
@@ -46,7 +47,7 @@ fn test_can_traverse_player_blocked_on_ghost_only_edges() {
traversal_flags: TraversalFlags::GHOST,
};
assert!(!can_traverse(EntityType::Player, edge));
assert_that(&can_traverse(EntityType::Player, edge)).is_false();
}
#[test]
@@ -58,7 +59,7 @@ fn test_can_traverse_ghost_on_all_edges() {
traversal_flags: TraversalFlags::ALL,
};
assert!(can_traverse(EntityType::Ghost, edge));
assert_that(&can_traverse(EntityType::Ghost, edge)).is_true();
}
#[test]
@@ -70,7 +71,7 @@ fn test_can_traverse_ghost_on_ghost_only_edges() {
traversal_flags: TraversalFlags::GHOST,
};
assert!(can_traverse(EntityType::Ghost, edge));
assert_that(&can_traverse(EntityType::Ghost, edge)).is_true();
}
#[test]
@@ -82,7 +83,7 @@ fn test_can_traverse_ghost_blocked_on_pacman_only_edges() {
traversal_flags: TraversalFlags::PACMAN,
};
assert!(!can_traverse(EntityType::Ghost, edge));
assert_that(&can_traverse(EntityType::Ghost, edge)).is_false();
}
#[test]
@@ -97,16 +98,16 @@ fn test_can_traverse_static_entities_flags() {
// Static entities have empty traversal flags but can still "traverse"
// in the sense that empty flags are contained in any flag set
// This is the expected behavior since empty ⊆ any set
assert!(can_traverse(EntityType::Pellet, edge));
assert!(can_traverse(EntityType::PowerPellet, edge));
assert_that(&can_traverse(EntityType::Pellet, edge)).is_true();
assert_that(&can_traverse(EntityType::PowerPellet, edge)).is_true();
}
#[test]
fn test_entity_type_traversal_flags() {
assert_eq!(EntityType::Player.traversal_flags(), TraversalFlags::PACMAN);
assert_eq!(EntityType::Ghost.traversal_flags(), TraversalFlags::GHOST);
assert_eq!(EntityType::Pellet.traversal_flags(), TraversalFlags::empty());
assert_eq!(EntityType::PowerPellet.traversal_flags(), TraversalFlags::empty());
assert_that(&EntityType::Player.traversal_flags()).is_equal_to(TraversalFlags::PACMAN);
assert_that(&EntityType::Ghost.traversal_flags()).is_equal_to(TraversalFlags::GHOST);
assert_that(&EntityType::Pellet.traversal_flags()).is_equal_to(TraversalFlags::empty());
assert_that(&EntityType::PowerPellet.traversal_flags()).is_equal_to(TraversalFlags::empty());
}
#[test]
@@ -131,8 +132,8 @@ fn test_player_control_system_move_command() {
direction,
remaining_time,
} => {
assert_eq!(direction, Direction::Up);
assert_eq!(remaining_time, 0.25);
assert_that(&direction).is_equal_to(Direction::Up);
assert_that(&remaining_time).is_equal_to(0.25);
}
BufferedDirection::None => panic!("Expected buffered direction to be set"),
}
@@ -153,7 +154,7 @@ fn test_player_control_system_exit_command() {
// Check that exit flag was set
let state = world.resource::<GlobalState>();
assert!(state.exit);
assert_that(&state.exit).is_true();
}
#[test]
@@ -171,7 +172,7 @@ fn test_player_control_system_toggle_debug() {
// Check that debug state changed
let debug_state = world.resource::<DebugState>();
assert!(debug_state.enabled);
assert_that(&debug_state.enabled).is_true();
}
#[test]
@@ -189,7 +190,7 @@ fn test_player_control_system_mute_audio() {
// Check that audio was muted
let audio_state = world.resource::<AudioState>();
assert!(audio_state.muted);
assert_that(&audio_state.muted).is_true();
// Send mute audio command again to unmute - need fresh events
world.resource_mut::<Events<GameEvent>>().clear(); // Clear previous events
@@ -200,7 +201,7 @@ fn test_player_control_system_mute_audio() {
// Check that audio was unmuted
let audio_state = world.resource::<AudioState>();
assert!(!audio_state.muted, "Audio should be unmuted after second toggle");
assert_that(&audio_state.muted).is_false();
}
#[test]
@@ -245,10 +246,7 @@ fn test_player_movement_system_buffered_direction_expires() {
match *buffered_direction {
BufferedDirection::None => {} // Expected - fully expired
BufferedDirection::Some { remaining_time, .. } => {
assert!(
remaining_time <= 0.0,
"Buffered direction should be expired or have non-positive time"
);
assert_that(&(remaining_time <= 0.0)).is_true();
}
}
}
@@ -271,7 +269,7 @@ fn test_player_movement_system_start_moving_from_stopped() {
match *position {
Position::Moving { from, .. } => {
assert_eq!(from, 0, "Player should start from node 0");
assert_that(&from).is_equal_to(0);
// Don't assert exact target node since the real map has different connectivity
}
Position::Stopped { .. } => {} // May stay stopped if no valid edge in current direction
@@ -299,8 +297,8 @@ fn test_player_movement_system_buffered_direction_change() {
match *position {
Position::Moving { from, to, .. } => {
assert_eq!(from, 0);
assert_eq!(to, 2); // Should be moving to node 2 (down)
assert_that(&from).is_equal_to(0);
assert_that(&to).is_equal_to(2); // Should be moving to node 2 (down)
}
Position::Stopped { .. } => panic!("Player should have started moving"),
}
@@ -329,7 +327,7 @@ fn test_player_movement_system_no_valid_edge() {
let position = query.single(&world).expect("Player should exist");
match *position {
Position::Stopped { node } => assert_eq!(node, 0),
Position::Stopped { node } => assert_that(&node).is_equal_to(0),
Position::Moving { .. } => panic!("Player shouldn't be able to move without valid edge"),
}
}
@@ -356,7 +354,7 @@ fn test_player_movement_system_continue_moving() {
match *position {
Position::Moving { remaining_distance, .. } => {
assert!(remaining_distance < 50.0); // Should have moved
assert_that(&(remaining_distance < 50.0)).is_true(); // Should have moved
}
Position::Stopped { .. } => {
// If player reached destination, that's also valid
@@ -388,8 +386,8 @@ fn test_full_player_input_to_movement_flow() {
match *position {
Position::Moving { from, to, .. } => {
assert_eq!(from, 0);
assert_eq!(to, 2); // Moving to node 2 (down)
assert_that(&from).is_equal_to(0);
assert_that(&to).is_equal_to(2); // Moving to node 2 (down)
}
Position::Stopped { .. } => panic!("Player should be moving"),
}
@@ -421,8 +419,8 @@ fn test_buffered_direction_timing() {
match *buffered_direction {
BufferedDirection::Some { remaining_time, .. } => {
assert!(remaining_time > 0.0);
assert!(remaining_time < 0.25);
assert_that(&(remaining_time > 0.0)).is_true();
assert_that(&(remaining_time < 0.25)).is_true();
}
BufferedDirection::None => panic!("Buffered direction should still be active"),
}
@@ -434,7 +432,7 @@ fn test_buffered_direction_timing() {
.expect("System should run successfully");
let buffered_direction = query.single(&world).expect("Player should exist");
assert_eq!(*buffered_direction, BufferedDirection::None);
assert_that(buffered_direction).is_equal_to(BufferedDirection::None);
}
#[test]
@@ -464,7 +462,7 @@ fn test_multiple_rapid_direction_changes() {
match *buffered_direction {
BufferedDirection::Some { direction, .. } => {
assert_eq!(direction, Direction::Left);
assert_that(&direction).is_equal_to(Direction::Left);
}
BufferedDirection::None => panic!("Expected buffered direction"),
}
@@ -510,8 +508,8 @@ fn test_player_state_persistence_across_systems() {
let position = *query.single(&world).expect("Player should exist");
// Check that the state changes persisted individually
assert!(debug_state_after_toggle.enabled, "Debug state should have toggled");
assert!(audio_muted_after_toggle, "Audio should be muted");
assert_that(&debug_state_after_toggle.enabled).is_true();
assert_that(&audio_muted_after_toggle).is_true();
// Player position depends on actual map connectivity
match position {

View File

@@ -1,4 +1,5 @@
use pacman::systems::profiling::{SystemId, SystemTimings};
use speculoos::prelude::*;
use std::time::Duration;
use strum::IntoEnumIterator;
@@ -6,15 +7,7 @@ macro_rules! assert_close {
($actual:expr, $expected:expr, $concern:expr) => {
let tolerance = Duration::from_micros(500);
let diff = $actual.abs_diff($expected);
assert!(
diff < tolerance,
"Expected {expected:?} ± {tolerance:.0?}, got {actual:?}, off by {diff:?} ({concern})",
concern = $concern,
expected = $expected,
actual = $actual,
tolerance = tolerance,
diff = diff
);
assert_that(&(diff < tolerance)).is_true();
};
}
@@ -55,7 +48,7 @@ fn test_default_zero_timing_for_unused_systems() {
// Verify all SystemId variants are present in the stats
let expected_count = SystemId::iter().count();
assert_eq!(stats.len(), expected_count, "All SystemId variants should be in stats");
assert_that(&stats.len()).is_equal_to(expected_count);
// Verify that the system with data has non-zero timing
let (avg, std_dev) = stats.get(&SystemId::PlayerControls).unwrap();
@@ -80,29 +73,6 @@ fn test_default_zero_timing_for_unused_systems() {
}
}
#[test]
fn test_pre_populated_timing_entries() {
let timings = SystemTimings::default();
// Verify that we can add timing to any SystemId without panicking
// (this would fail with the old implementation if the entry didn't exist)
// Use the same tick for all systems to avoid zero-padding
for id in SystemId::iter() {
timings.add_timing(id, Duration::from_nanos(1), 1);
}
// Verify all systems now have non-zero timing
let stats = timings.get_stats(1);
for id in SystemId::iter() {
let (avg, _) = stats.get(&id).unwrap();
assert!(
*avg > Duration::ZERO,
"System {:?} should have non-zero timing after add_timing",
id
);
}
}
#[test]
fn test_total_system_timing() {
let timings = SystemTimings::default();
@@ -118,8 +88,5 @@ fn test_total_system_timing() {
// Should have 16ms average (16+18+14)/3 = 16ms
assert_close!(*avg, Duration::from_millis(16), "Total system average timing");
// Should have some standard deviation
assert!(
*std_dev > Duration::ZERO,
"Total system should have non-zero std dev with multiple measurements"
);
assert_that(&(*std_dev > Duration::ZERO)).is_true();
}

View File

@@ -1,6 +1,7 @@
use glam::U16Vec2;
use pacman::texture::sprite::{AtlasMapper, AtlasTile, MapperFrame};
use sdl2::pixels::Color;
use speculoos::prelude::*;
use std::collections::HashMap;
mod common;
@@ -20,10 +21,10 @@ fn test_atlas_mapper_frame_lookup() {
// Test direct frame lookup
let frame = mapper.frames.get("test");
assert!(frame.is_some());
assert_that(&frame.is_some()).is_true();
let frame = frame.unwrap();
assert_eq!(frame.pos, U16Vec2::new(10, 20));
assert_eq!(frame.size, U16Vec2::new(32, 64));
assert_that(&frame.pos).is_equal_to(U16Vec2::new(10, 20));
assert_that(&frame.size).is_equal_to(U16Vec2::new(32, 64));
}
#[test]
@@ -46,11 +47,11 @@ fn test_atlas_mapper_multiple_frames() {
let mapper = AtlasMapper { frames };
assert_eq!(mapper.frames.len(), 2);
assert!(mapper.frames.contains_key("tile1"));
assert!(mapper.frames.contains_key("tile2"));
assert!(!mapper.frames.contains_key("tile3"));
assert!(!mapper.frames.contains_key("nonexistent"));
assert_that(&mapper.frames.len()).is_equal_to(2);
assert_that(&mapper.frames.contains_key("tile1")).is_true();
assert_that(&mapper.frames.contains_key("tile2")).is_true();
assert_that(&mapper.frames.contains_key("tile3")).is_false();
assert_that(&mapper.frames.contains_key("nonexistent")).is_false();
}
#[test]
@@ -60,10 +61,10 @@ fn test_atlas_tile_new_and_with_color() {
let color = Color::RGB(100, 150, 200);
let tile = AtlasTile::new(pos, size, None);
assert_eq!(tile.pos, pos);
assert_eq!(tile.size, size);
assert_eq!(tile.color, None);
assert_that(&tile.pos).is_equal_to(pos);
assert_that(&tile.size).is_equal_to(size);
assert_that(&tile.color).is_equal_to(None);
let tile_with_color = tile.with_color(color);
assert_eq!(tile_with_color.color, Some(color));
assert_that(&tile_with_color.color).is_equal_to(Some(color));
}

View File

@@ -1,4 +1,5 @@
use pacman::texture::{sprite::SpriteAtlas, text::TextTexture};
use speculoos::prelude::*;
mod common;
@@ -16,22 +17,16 @@ fn get_all_chars() -> String {
/// Helper function to check if a character is in the atlas and char_map
fn check_char(text_texture: &mut TextTexture, atlas: &mut SpriteAtlas, c: char) {
// Check that the character is not in the char_map yet
assert!(
!text_texture.get_char_map().contains_key(&c),
"Character {c} should not yet be in char_map"
);
assert_that(&text_texture.get_char_map().contains_key(&c)).is_false();
// Get the tile from the atlas, which caches the tile in the char_map
let tile = text_texture.get_tile(c, atlas);
assert!(tile.is_ok(), "Failed to get tile for character {c}");
assert!(tile.unwrap().is_some(), "Tile for character {c} not found in atlas");
assert_that(&tile.is_ok()).is_true();
assert_that(&tile.unwrap().is_some()).is_true();
// Check that the tile is now cached in the char_map
assert!(
text_texture.get_char_map().contains_key(&c),
"Tile for character {c} was not cached in char_map"
);
assert_that(&text_texture.get_char_map().contains_key(&c)).is_true();
}
#[test]
@@ -74,8 +69,8 @@ fn test_text_width() -> Result<(), String> {
let width = text_texture.text_width(&string);
let height = text_texture.text_height();
assert!(width > 0, "Width for string {string} should be greater than 0");
assert!(height > 0, "Height for string {string} should be greater than 0");
assert_that(&(width > 0)).is_true();
assert_that(&(height > 0)).is_true();
}
Ok(())
@@ -88,22 +83,22 @@ fn test_text_scale() -> Result<(), String> {
let mut text_texture = TextTexture::new(0.5);
assert_eq!(text_texture.scale(), 0.5);
assert_eq!(text_texture.text_height(), 4);
assert_eq!(text_texture.text_width(""), 0);
assert_eq!(text_texture.text_width(string), base_width / 2);
assert_that(&text_texture.scale()).is_equal_to(0.5);
assert_that(&text_texture.text_height()).is_equal_to(4);
assert_that(&text_texture.text_width("")).is_equal_to(0);
assert_that(&text_texture.text_width(string)).is_equal_to(base_width / 2);
text_texture.set_scale(2.0);
assert_eq!(text_texture.scale(), 2.0);
assert_eq!(text_texture.text_height(), 16);
assert_eq!(text_texture.text_width(string), base_width * 2);
assert_eq!(text_texture.text_width(""), 0);
assert_that(&text_texture.scale()).is_equal_to(2.0);
assert_that(&text_texture.text_height()).is_equal_to(16);
assert_that(&text_texture.text_width(string)).is_equal_to(base_width * 2);
assert_that(&text_texture.text_width("")).is_equal_to(0);
text_texture.set_scale(1.0);
assert_eq!(text_texture.scale(), 1.0);
assert_eq!(text_texture.text_height(), 8);
assert_eq!(text_texture.text_width(string), base_width);
assert_eq!(text_texture.text_width(""), 0);
assert_that(&text_texture.scale()).is_equal_to(1.0);
assert_that(&text_texture.text_height()).is_equal_to(8);
assert_that(&text_texture.text_width(string)).is_equal_to(base_width);
assert_that(&text_texture.text_width("")).is_equal_to(0);
Ok(())
}
@@ -113,17 +108,17 @@ fn test_text_color() -> Result<(), String> {
let mut text_texture = TextTexture::new(1.0);
// Test default color (should be None initially)
assert_eq!(text_texture.color(), None);
assert_that(&text_texture.color()).is_equal_to(None);
// Test setting color
let test_color = sdl2::pixels::Color::YELLOW;
text_texture.set_color(test_color);
assert_eq!(text_texture.color(), Some(test_color));
assert_that(&text_texture.color()).is_equal_to(Some(test_color));
// Test changing color
let new_color = sdl2::pixels::Color::RED;
text_texture.set_color(new_color);
assert_eq!(text_texture.color(), Some(new_color));
assert_that(&text_texture.color()).is_equal_to(Some(new_color));
Ok(())
}