Skip to content

Commit eb5c68f

Browse files
authored
Add a test to ensure that state transitions happen before PreStartup. (#20543)
# Objective - Make sure future changes like #20407 maintains our intended before. ## Solution - Add a test! - If we ever decide to change this policy (e.g., run startup stuff first), it's easy enough to change the test. ## Testing - Add a test
1 parent 2ba758e commit eb5c68f

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

crates/bevy_state/src/lib.rs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,3 +94,54 @@ pub mod prelude {
9494
state_scoped::{DespawnOnEnterState, DespawnOnExitState},
9595
};
9696
}
97+
98+
#[cfg(test)]
99+
mod tests {
100+
use bevy_app::{App, PreStartup};
101+
use bevy_ecs::{
102+
resource::Resource,
103+
system::{Commands, ResMut},
104+
};
105+
use bevy_state_macros::States;
106+
107+
use crate::{
108+
app::{AppExtStates, StatesPlugin},
109+
state::OnEnter,
110+
};
111+
112+
#[test]
113+
fn state_transition_runs_before_pre_startup() {
114+
// This test is not really a "requirement" of states (we could run state transitions after
115+
// PreStartup), but this is the current policy and it is useful to ensure we are following
116+
// it if we ever change how we initialize stuff.
117+
118+
let mut app = App::new();
119+
app.add_plugins(StatesPlugin);
120+
121+
#[derive(States, Default, PartialEq, Eq, Hash, Debug, Clone)]
122+
enum TestState {
123+
#[default]
124+
A,
125+
B,
126+
}
127+
128+
#[derive(Resource, Default, PartialEq, Eq, Debug)]
129+
struct Thingy(usize);
130+
131+
app.init_state::<TestState>();
132+
133+
app.add_systems(OnEnter(TestState::A), move |mut commands: Commands| {
134+
commands.init_resource::<Thingy>();
135+
});
136+
137+
app.add_systems(PreStartup, move |mut thingy: ResMut<Thingy>| {
138+
// This system will fail if it runs before OnEnter.
139+
thingy.0 += 1;
140+
});
141+
142+
app.update();
143+
144+
// This assert only succeeds if first OnEnter(TestState::A) runs, followed by PreStartup.
145+
assert_eq!(app.world().resource::<Thingy>(), &Thingy(1));
146+
}
147+
}

0 commit comments

Comments
 (0)