Skip to main content

stable_flight/testing/
conformance.rs

1//! Frame-conformance kit for state sources: simulator backends and estimators.
2//!
3//! Every simulator or sensor stack reports state in its own frames and units; a
4//! [`StateSource`](crate::StateSource) converts to the
5//! [`VehicleState` frame contract](crate::VehicleState#frame-contract) at its boundary. This
6//! module is a table of physical [`Scenario`]s with the state each must produce. A backend's
7//! tests build the simulator's *native* report for each scenario (a mock-client fixture), run
8//! it through the backend, and [`Scenario::check`] the result. That catches a swapped axis, a
9//! flipped sign, a wrong rotation order, or a unit slip before the backend flies.
10//!
11//! [`conformance_tests!`](crate::conformance_tests) generates one test per scenario and a
12//! test that fails when a scenario has none, so new scenarios reach every backend.
13//!
14//! # Examples
15//!
16//! ```
17//! use stable_flight::testing::conformance::{LEVEL, ROLL_RIGHT_30, SCENARIOS};
18//!
19//! // A backend that got the frames right produces the scenario's expected state.
20//! for scenario in SCENARIOS {
21//!     assert!(scenario.check(&scenario.expected_state()).is_ok());
22//! }
23//!
24//! // Level flight is not a 30° right bank.
25//! let error = ROLL_RIGHT_30.check(&LEVEL.expected_state()).unwrap_err();
26//! assert_eq!(error.mismatches()[0].field, "roll_rad");
27//! ```
28
29use core::fmt;
30
31use crate::Vec3;
32use nalgebra::UnitQuaternion;
33
34use crate::VehicleState;
35use crate::math::wrap_angle;
36
37#[cfg(test)]
38mod tests;
39
40/// Largest difference accepted for an angle (rad) or body rate (rad/s).
41pub const ANGLE_TOLERANCE: f32 = 1e-3;
42
43/// Largest difference accepted for a position (m), velocity (m/s), or acceleration (m/s²).
44pub const LINEAR_TOLERANCE: f32 = 1e-3;
45
46/// Altitude every scenario flies at, in meters. Nonzero so a dropped or negated altitude
47/// shows up.
48const SCENARIO_ALTITUDE: f32 = 100.0;
49
50/// One physical situation and the [`VehicleState`] it must map to.
51///
52/// Fields give the physical truth in the
53/// [frame contract's](crate::VehicleState#frame-contract) axes and signs, with angles in
54/// degrees (as simulators usually report them), so a backend can build its native fixture
55/// from them.
56#[derive(Debug, Clone, Copy, PartialEq)]
57pub struct Scenario {
58    /// Short name used in failure messages.
59    pub name: &'static str,
60    /// Roll angle in degrees.
61    pub roll_deg: f32,
62    /// Pitch angle in degrees.
63    pub pitch_deg: f32,
64    /// Heading in degrees.
65    pub heading_deg: f32,
66    /// Body rates (roll, pitch, yaw) in degrees per second.
67    pub body_rates_degps: [f32; 3],
68    /// World position (north, east, up) in meters.
69    pub position_neu_m: [f32; 3],
70    /// World velocity (north, east, up) in m/s.
71    pub velocity_neu_mps: [f32; 3],
72    /// World acceleration (north, east, up) in m/s².
73    pub acceleration_neu_mps2: [f32; 3],
74}
75
76/// At rest, wings level, nose north.
77pub const LEVEL: Scenario = Scenario {
78    name: "level",
79    roll_deg: 0.0,
80    pitch_deg: 0.0,
81    heading_deg: 0.0,
82    body_rates_degps: [0.0; 3],
83    position_neu_m: [0.0, 0.0, SCENARIO_ALTITUDE],
84    velocity_neu_mps: [0.0; 3],
85    acceleration_neu_mps2: [0.0; 3],
86};
87
88/// Banked 30° right (right wing down).
89pub const ROLL_RIGHT_30: Scenario = Scenario {
90    name: "roll right 30°",
91    roll_deg: 30.0,
92    ..LEVEL
93};
94
95/// Nose 15° up.
96pub const PITCH_UP_15: Scenario = Scenario {
97    name: "pitch up 15°",
98    pitch_deg: 15.0,
99    ..LEVEL
100};
101
102/// Level, nose pointing east.
103pub const HEADING_EAST: Scenario = Scenario {
104    name: "heading east",
105    heading_deg: 90.0,
106    ..LEVEL
107};
108
109/// Nose east, 10° up, banked 30° right. Distinct angles on every axis catch a wrong rotation
110/// order or swapped Euler angles.
111pub const BANKED_CLIMB_EAST: Scenario = Scenario {
112    name: "banked climb east",
113    roll_deg: 30.0,
114    pitch_deg: 10.0,
115    heading_deg: 90.0,
116    ..LEVEL
117};
118
119/// Level, climbing at 2 m/s and accelerating upward at 1 m/s².
120pub const CLIMBING: Scenario = Scenario {
121    name: "climbing",
122    velocity_neu_mps: [0.0, 0.0, 2.0],
123    acceleration_neu_mps2: [0.0, 0.0, 1.0],
124    ..LEVEL
125};
126
127/// Northeast of the origin, flying northeast and speeding up. Distinct north and east values
128/// catch a swapped horizontal axis (e.g. ENU vs NED).
129pub const MOVING_NORTHEAST: Scenario = Scenario {
130    name: "moving northeast",
131    position_neu_m: [30.0, 40.0, SCENARIO_ALTITUDE],
132    velocity_neu_mps: [3.0, 4.0, 0.0],
133    acceleration_neu_mps2: [0.5, 1.5, 0.0],
134    ..LEVEL
135};
136
137/// Level, yawing right (clockwise from above) at 30°/s.
138pub const YAW_RIGHT_RATE: Scenario = Scenario {
139    name: "yaw right rate",
140    body_rates_degps: [0.0, 0.0, 30.0],
141    ..LEVEL
142};
143
144/// Rolling right, pitching up, and yawing right at distinct rates, which catches swapped
145/// rate axes.
146pub const COMBINED_RATES: Scenario = Scenario {
147    name: "combined rates",
148    body_rates_degps: [10.0, 20.0, 30.0],
149    ..LEVEL
150};
151
152/// Every scenario; a backend covers each one (see [`conformance_tests!`](crate::conformance_tests)).
153pub const SCENARIOS: &[Scenario] = &[
154    LEVEL,
155    ROLL_RIGHT_30,
156    PITCH_UP_15,
157    HEADING_EAST,
158    BANKED_CLIMB_EAST,
159    CLIMBING,
160    MOVING_NORTHEAST,
161    YAW_RIGHT_RATE,
162    COMBINED_RATES,
163];
164
165impl Scenario {
166    /// The [`VehicleState`] a conforming backend reports for this scenario.
167    pub fn expected_state(&self) -> VehicleState {
168        let [roll, pitch, heading] =
169            [self.roll_deg, self.pitch_deg, self.heading_deg].map(f32::to_radians);
170        let [p, q, r] = self.body_rates_degps.map(f32::to_radians);
171        let [x, y, z] = self.position_neu_m;
172        let [vx, vy, vz] = self.velocity_neu_mps;
173        let [ax, ay, az] = self.acceleration_neu_mps2;
174
175        VehicleState {
176            position_m: Vec3::new(x, y, z),
177            velocity_mps: Vec3::new(vx, vy, vz),
178            acceleration_mps2: Vec3::new(ax, ay, az),
179            attitude: UnitQuaternion::from_euler_angles(roll, pitch, heading),
180            angular_velocity_radps: Vec3::new(p, q, r),
181            roll_rad: roll,
182            pitch_rad: pitch,
183            heading_rad: heading,
184            // Still air: airspeed is ground speed.
185            airspeed_mps: Some(Vec3::new(vx, vy, vz).norm()),
186        }
187    }
188
189    /// Checks `state` against this scenario: position, velocity, acceleration, the Euler
190    /// angles, the attitude quaternion's Euler angles, the body rates, and airspeed when the
191    /// backend reports one (`None` passes: no air-data source).
192    ///
193    /// Angles are compared modulo a full turn, so a heading in [0, 2π) or [-π, π) both pass.
194    /// A NaN field always fails.
195    ///
196    /// # Errors
197    ///
198    /// [`ConformanceError`] listing every field outside [`ANGLE_TOLERANCE`] or
199    /// [`LINEAR_TOLERANCE`].
200    #[allow(
201        clippy::result_large_err,
202        reason = "mismatches are stored inline so the kit needs no allocator; test-only"
203    )]
204    pub fn check(&self, state: &VehicleState) -> Result<(), ConformanceError> {
205        let e = self.expected_state();
206        let mut error = ConformanceError::new(self.name);
207
208        let linear = [
209            ("position_m.x", e.position_m.x, state.position_m.x),
210            ("position_m.y", e.position_m.y, state.position_m.y),
211            ("position_m.z", e.position_m.z, state.position_m.z),
212            ("velocity_mps.x", e.velocity_mps.x, state.velocity_mps.x),
213            ("velocity_mps.y", e.velocity_mps.y, state.velocity_mps.y),
214            ("velocity_mps.z", e.velocity_mps.z, state.velocity_mps.z),
215            (
216                "acceleration_mps2.x",
217                e.acceleration_mps2.x,
218                state.acceleration_mps2.x,
219            ),
220            (
221                "acceleration_mps2.y",
222                e.acceleration_mps2.y,
223                state.acceleration_mps2.y,
224            ),
225            (
226                "acceleration_mps2.z",
227                e.acceleration_mps2.z,
228                state.acceleration_mps2.z,
229            ),
230        ];
231        let rates = [
232            (
233                "angular_velocity_radps.x",
234                e.angular_velocity_radps.x,
235                state.angular_velocity_radps.x,
236            ),
237            (
238                "angular_velocity_radps.y",
239                e.angular_velocity_radps.y,
240                state.angular_velocity_radps.y,
241            ),
242            (
243                "angular_velocity_radps.z",
244                e.angular_velocity_radps.z,
245                state.angular_velocity_radps.z,
246            ),
247        ];
248        let (q_roll, q_pitch, q_yaw) = crate::euler_angles(&state.attitude);
249        let angles = [
250            ("roll_rad", e.roll_rad, state.roll_rad),
251            ("pitch_rad", e.pitch_rad, state.pitch_rad),
252            ("heading_rad", e.heading_rad, state.heading_rad),
253            ("attitude roll", e.roll_rad, q_roll),
254            ("attitude pitch", e.pitch_rad, q_pitch),
255            ("attitude yaw", e.heading_rad, q_yaw),
256        ];
257
258        for (field, expected, actual) in linear {
259            error.check(field, expected, actual, expected - actual, LINEAR_TOLERANCE);
260        }
261        if let (Some(expected), Some(actual)) = (e.airspeed_mps, state.airspeed_mps) {
262            error.check(
263                "airspeed_mps",
264                expected,
265                actual,
266                expected - actual,
267                LINEAR_TOLERANCE,
268            );
269        }
270        for (field, expected, actual) in rates {
271            error.check(field, expected, actual, expected - actual, ANGLE_TOLERANCE);
272        }
273        for (field, expected, actual) in angles {
274            let difference = wrap_angle(expected - actual);
275            error.check(field, expected, actual, difference, ANGLE_TOLERANCE);
276        }
277
278        if error.mismatches().is_empty() {
279            Ok(())
280        } else {
281            Err(error)
282        }
283    }
284}
285
286/// Number of fields [`Scenario::check`] compares.
287const CHECKED_FIELDS: usize = 19;
288
289/// A backend's state for a [`Scenario`] broke the frame contract.
290///
291/// Holds its mismatches inline (no allocation), so it works in `no_std` tests.
292#[derive(Debug, Clone, Copy, PartialEq)]
293pub struct ConformanceError {
294    /// The scenario's name.
295    pub scenario: &'static str,
296    mismatches: [Mismatch; CHECKED_FIELDS],
297    len: usize,
298}
299
300impl ConformanceError {
301    fn new(scenario: &'static str) -> Self {
302        Self {
303            scenario,
304            mismatches: [Mismatch::EMPTY; CHECKED_FIELDS],
305            len: 0,
306        }
307    }
308
309    /// Every field that was off, in check order.
310    pub fn mismatches(&self) -> &[Mismatch] {
311        &self.mismatches[..self.len]
312    }
313
314    /// Records `field` unless `|difference| <= tolerance` (false for NaN, so NaN fails).
315    fn check(
316        &mut self,
317        field: &'static str,
318        expected: f32,
319        actual: f32,
320        difference: f32,
321        tolerance: f32,
322    ) {
323        if difference.abs() <= tolerance || self.len == CHECKED_FIELDS {
324            return;
325        }
326        self.mismatches[self.len] = Mismatch {
327            field,
328            expected,
329            actual,
330        };
331        self.len += 1;
332    }
333}
334
335impl fmt::Display for ConformanceError {
336    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
337        write!(f, "scenario `{}` off contract", self.scenario)?;
338        for (i, mismatch) in self.mismatches().iter().enumerate() {
339            let separator = if i == 0 { ": " } else { "; " };
340            write!(f, "{separator}{mismatch}")?;
341        }
342        Ok(())
343    }
344}
345
346impl core::error::Error for ConformanceError {}
347
348/// One field of a [`ConformanceError`].
349#[derive(Debug, Clone, Copy, PartialEq)]
350pub struct Mismatch {
351    /// The `VehicleState` field, e.g. `velocity_mps.z`.
352    pub field: &'static str,
353    /// The contract's value (SI: m, m/s, m/s², rad, rad/s).
354    pub expected: f32,
355    /// The backend's value.
356    pub actual: f32,
357}
358
359impl Mismatch {
360    const EMPTY: Mismatch = Mismatch {
361        field: "",
362        expected: 0.0,
363        actual: 0.0,
364    };
365}
366
367impl fmt::Display for Mismatch {
368    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
369        write!(
370            f,
371            "{} expected {} got {}",
372            self.field, self.expected, self.actual
373        )
374    }
375}
376
377/// Generates a backend's conformance tests: one `#[test]` per listed scenario, plus
378/// `conformance_covers_every_scenario`, which fails if any scenario in
379/// [`SCENARIOS`](crate::testing::conformance::SCENARIOS) has no test.
380///
381/// `$state_for` is a `fn(&Scenario) -> VehicleState` that builds the simulator's native report
382/// for the scenario and runs it through the backend. Each row is `test_name: SCENARIO`,
383/// optionally followed by `, ignore = "reason"` for a known failure.
384///
385/// # Examples
386///
387/// ```
388/// use stable_flight::VehicleState;
389/// use stable_flight::testing::conformance::Scenario;
390///
391/// // A real backend builds its simulator's native report here.
392/// fn state_for(scenario: &Scenario) -> VehicleState {
393///     scenario.expected_state()
394/// }
395///
396/// stable_flight::conformance_tests! {
397///     state_for;
398///     conforms_level: LEVEL;
399///     conforms_roll_right_30: ROLL_RIGHT_30;
400///     conforms_pitch_up_15: PITCH_UP_15, ignore = "pitch sign not converted yet";
401/// }
402/// ```
403#[macro_export]
404macro_rules! conformance_tests {
405    ($state_for:path; $($test:ident: $scenario:ident $(, ignore = $reason:literal)?;)+) => {
406        $(
407            #[test]
408            $(#[ignore = $reason])?
409            fn $test() {
410                let scenario = $crate::testing::conformance::$scenario;
411                if let Err(error) = scenario.check(&$state_for(&scenario)) {
412                    panic!("{error}");
413                }
414            }
415        )+
416
417        #[test]
418        fn conformance_covers_every_scenario() {
419            let covered = [$($crate::testing::conformance::$scenario),+];
420            for scenario in $crate::testing::conformance::SCENARIOS {
421                assert!(
422                    covered.contains(scenario),
423                    "no conformance test for scenario `{}`",
424                    scenario.name
425                );
426            }
427        }
428    };
429}