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        }
185    }
186
187    /// Checks `state` against this scenario: position, velocity, acceleration, the Euler
188    /// angles, the attitude quaternion's Euler angles, and the body rates.
189    ///
190    /// Angles are compared modulo a full turn, so a heading in [0, 2π) or [-π, π) both pass.
191    /// A NaN field always fails.
192    ///
193    /// # Errors
194    ///
195    /// [`ConformanceError`] listing every field outside [`ANGLE_TOLERANCE`] or
196    /// [`LINEAR_TOLERANCE`].
197    #[allow(
198        clippy::result_large_err,
199        reason = "mismatches are stored inline so the kit needs no allocator; test-only"
200    )]
201    pub fn check(&self, state: &VehicleState) -> Result<(), ConformanceError> {
202        let e = self.expected_state();
203        let mut error = ConformanceError::new(self.name);
204
205        let linear = [
206            ("position_m.x", e.position_m.x, state.position_m.x),
207            ("position_m.y", e.position_m.y, state.position_m.y),
208            ("position_m.z", e.position_m.z, state.position_m.z),
209            ("velocity_mps.x", e.velocity_mps.x, state.velocity_mps.x),
210            ("velocity_mps.y", e.velocity_mps.y, state.velocity_mps.y),
211            ("velocity_mps.z", e.velocity_mps.z, state.velocity_mps.z),
212            (
213                "acceleration_mps2.x",
214                e.acceleration_mps2.x,
215                state.acceleration_mps2.x,
216            ),
217            (
218                "acceleration_mps2.y",
219                e.acceleration_mps2.y,
220                state.acceleration_mps2.y,
221            ),
222            (
223                "acceleration_mps2.z",
224                e.acceleration_mps2.z,
225                state.acceleration_mps2.z,
226            ),
227        ];
228        let rates = [
229            (
230                "angular_velocity_radps.x",
231                e.angular_velocity_radps.x,
232                state.angular_velocity_radps.x,
233            ),
234            (
235                "angular_velocity_radps.y",
236                e.angular_velocity_radps.y,
237                state.angular_velocity_radps.y,
238            ),
239            (
240                "angular_velocity_radps.z",
241                e.angular_velocity_radps.z,
242                state.angular_velocity_radps.z,
243            ),
244        ];
245        let (q_roll, q_pitch, q_yaw) = crate::euler_angles(&state.attitude);
246        let angles = [
247            ("roll_rad", e.roll_rad, state.roll_rad),
248            ("pitch_rad", e.pitch_rad, state.pitch_rad),
249            ("heading_rad", e.heading_rad, state.heading_rad),
250            ("attitude roll", e.roll_rad, q_roll),
251            ("attitude pitch", e.pitch_rad, q_pitch),
252            ("attitude yaw", e.heading_rad, q_yaw),
253        ];
254
255        for (field, expected, actual) in linear {
256            error.check(field, expected, actual, expected - actual, LINEAR_TOLERANCE);
257        }
258        for (field, expected, actual) in rates {
259            error.check(field, expected, actual, expected - actual, ANGLE_TOLERANCE);
260        }
261        for (field, expected, actual) in angles {
262            let difference = wrap_angle(expected - actual);
263            error.check(field, expected, actual, difference, ANGLE_TOLERANCE);
264        }
265
266        if error.mismatches().is_empty() {
267            Ok(())
268        } else {
269            Err(error)
270        }
271    }
272}
273
274/// Number of fields [`Scenario::check`] compares.
275const CHECKED_FIELDS: usize = 18;
276
277/// A backend's state for a [`Scenario`] broke the frame contract.
278///
279/// Holds its mismatches inline (no allocation), so it works in `no_std` tests.
280#[derive(Debug, Clone, Copy, PartialEq)]
281pub struct ConformanceError {
282    /// The scenario's name.
283    pub scenario: &'static str,
284    mismatches: [Mismatch; CHECKED_FIELDS],
285    len: usize,
286}
287
288impl ConformanceError {
289    fn new(scenario: &'static str) -> Self {
290        Self {
291            scenario,
292            mismatches: [Mismatch::EMPTY; CHECKED_FIELDS],
293            len: 0,
294        }
295    }
296
297    /// Every field that was off, in check order.
298    pub fn mismatches(&self) -> &[Mismatch] {
299        &self.mismatches[..self.len]
300    }
301
302    /// Records `field` unless `|difference| <= tolerance` (false for NaN, so NaN fails).
303    fn check(
304        &mut self,
305        field: &'static str,
306        expected: f32,
307        actual: f32,
308        difference: f32,
309        tolerance: f32,
310    ) {
311        if difference.abs() <= tolerance || self.len == CHECKED_FIELDS {
312            return;
313        }
314        self.mismatches[self.len] = Mismatch {
315            field,
316            expected,
317            actual,
318        };
319        self.len += 1;
320    }
321}
322
323impl fmt::Display for ConformanceError {
324    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
325        write!(f, "scenario `{}` off contract", self.scenario)?;
326        for (i, mismatch) in self.mismatches().iter().enumerate() {
327            let separator = if i == 0 { ": " } else { "; " };
328            write!(f, "{separator}{mismatch}")?;
329        }
330        Ok(())
331    }
332}
333
334impl core::error::Error for ConformanceError {}
335
336/// One field of a [`ConformanceError`].
337#[derive(Debug, Clone, Copy, PartialEq)]
338pub struct Mismatch {
339    /// The `VehicleState` field, e.g. `velocity_mps.z`.
340    pub field: &'static str,
341    /// The contract's value (SI: m, m/s, m/s², rad, rad/s).
342    pub expected: f32,
343    /// The backend's value.
344    pub actual: f32,
345}
346
347impl Mismatch {
348    const EMPTY: Mismatch = Mismatch {
349        field: "",
350        expected: 0.0,
351        actual: 0.0,
352    };
353}
354
355impl fmt::Display for Mismatch {
356    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
357        write!(
358            f,
359            "{} expected {} got {}",
360            self.field, self.expected, self.actual
361        )
362    }
363}
364
365/// Generates a backend's conformance tests: one `#[test]` per listed scenario, plus
366/// `conformance_covers_every_scenario`, which fails if any scenario in
367/// [`SCENARIOS`](crate::testing::conformance::SCENARIOS) has no test.
368///
369/// `$state_for` is a `fn(&Scenario) -> VehicleState` that builds the simulator's native report
370/// for the scenario and runs it through the backend. Each row is `test_name: SCENARIO`,
371/// optionally followed by `, ignore = "reason"` for a known failure.
372///
373/// # Examples
374///
375/// ```
376/// use stable_flight::VehicleState;
377/// use stable_flight::testing::conformance::Scenario;
378///
379/// // A real backend builds its simulator's native report here.
380/// fn state_for(scenario: &Scenario) -> VehicleState {
381///     scenario.expected_state()
382/// }
383///
384/// stable_flight::conformance_tests! {
385///     state_for;
386///     conforms_level: LEVEL;
387///     conforms_roll_right_30: ROLL_RIGHT_30;
388///     conforms_pitch_up_15: PITCH_UP_15, ignore = "pitch sign not converted yet";
389/// }
390/// ```
391#[macro_export]
392macro_rules! conformance_tests {
393    ($state_for:path; $($test:ident: $scenario:ident $(, ignore = $reason:literal)?;)+) => {
394        $(
395            #[test]
396            $(#[ignore = $reason])?
397            fn $test() {
398                let scenario = $crate::testing::conformance::$scenario;
399                if let Err(error) = scenario.check(&$state_for(&scenario)) {
400                    panic!("{error}");
401                }
402            }
403        )+
404
405        #[test]
406        fn conformance_covers_every_scenario() {
407            let covered = [$($crate::testing::conformance::$scenario),+];
408            for scenario in $crate::testing::conformance::SCENARIOS {
409                assert!(
410                    covered.contains(scenario),
411                    "no conformance test for scenario `{}`",
412                    scenario.name
413                );
414            }
415        }
416    };
417}