Skip to main content

aura_test/
lib.rs

1//! Test helpers for AURA plugins.
2//!
3//! State round-trip, param sanity, and a small offline process harness.
4//! No host / CLAP load — pure `PluginLogic`.
5//!
6//! ```ignore
7//! #[test]
8//! fn state_round_trips() {
9//!     aura_test::assert_state_round_trip::<MyPlugin>();
10//! }
11//!
12//! #[test]
13//! fn process_is_finite() {
14//!     let out = aura_test::process_silence::<MyPlugin>(2, 256);
15//!     aura_test::assert_no_nans(&out);
16//! }
17//! ```
18
19#![forbid(unsafe_code)]
20// Assertion helpers panic on failure by design — same contract as product tests.
21#![allow(clippy::missing_panics_doc, clippy::must_use_candidate)]
22
23use aura_core::{
24    AudioBuffer, AudioConfig, PluginLogic, ProcessContext, ProcessMode, ProcessStatus,
25    decode_state, encode_state,
26};
27use aura_params::Params;
28
29// ---------------------------------------------------------------------------
30// State
31// ---------------------------------------------------------------------------
32
33/// Encode → fresh instance → decode; every param plain value must match.
34///
35/// # Panics
36///
37/// On decode failure, missing param id, or |Δ| ≥ 1e-4.
38pub fn assert_state_round_trip<L: PluginLogic>() {
39    let src = L::Params::default();
40    let blob = encode_state(&src);
41
42    let dst = L::Params::default();
43    assert!(
44        decode_state(&dst, &blob),
45        "decode_state failed on a blob produced by encode_state — codec bug"
46    );
47
48    let infos = src.param_infos();
49    for pi in &infos {
50        let v1 = src.get_plain(pi.id).unwrap_or_else(|| {
51            panic!(
52                "param {} ({}) missing from source after encode — id not registered",
53                pi.id, pi.name
54            )
55        });
56        let v2 = dst.get_plain(pi.id).unwrap_or_else(|| {
57            panic!(
58                "param {} ({}) lost during state round-trip — \
59                 blob id not restored on a fresh Default params",
60                pi.id, pi.name
61            )
62        });
63        assert!(
64            (v1 - v2).abs() < 1e-4,
65            "param {} ({}) mismatch after round-trip: {v1} vs {v2}",
66            pi.id,
67            pi.name
68        );
69    }
70}
71
72/// Corrupt / truncated blobs must not panic and must leave defaults intact.
73///
74/// # Panics
75///
76/// If `decode_state` panics, or if a failed decode still mutates values.
77pub fn assert_corrupt_state_no_crash<L: PluginLogic>() {
78    let params = L::Params::default();
79    let before = snapshot_plains(&params);
80
81    // Truncated / random / empty
82    for blob in [
83        &[][..],
84        &[0u8, 1, 2, 3][..],
85        &[0xff; 7][..],
86        // Lies about count
87        &[10, 0, 0, 0, 1, 0, 0, 0][..],
88    ] {
89        let ok = decode_state(&params, blob);
90        assert!(
91            !ok || blob.is_empty(),
92            "unexpected success on corrupt blob {blob:?}"
93        );
94        let after = snapshot_plains(&params);
95        assert_eq!(
96            before, after,
97            "failed decode must not mutate param values (blob {blob:?})"
98        );
99    }
100}
101
102/// Empty blob is a no-op reject (same as corrupt).
103pub fn assert_empty_state_no_crash<L: PluginLogic>() {
104    let params = L::Params::default();
105    let before = snapshot_plains(&params);
106    assert!(!decode_state(&params, &[]));
107    assert_eq!(before, snapshot_plains(&params));
108}
109
110fn snapshot_plains(params: &dyn Params) -> Vec<(u32, f64)> {
111    let infos = params.param_infos();
112    infos
113        .iter()
114        .filter_map(|pi| params.get_plain(pi.id).map(|v| (pi.id, v)))
115        .collect()
116}
117
118// ---------------------------------------------------------------------------
119// Params shape
120// ---------------------------------------------------------------------------
121
122/// No two infos share the same id.
123///
124/// # Panics
125///
126/// On duplicate ids.
127pub fn assert_no_duplicate_param_ids<L: PluginLogic>() {
128    let infos = L::Params::default().param_infos();
129    let mut seen = Vec::with_capacity(infos.len());
130    for pi in &infos {
131        assert!(
132            !seen.contains(&pi.id),
133            "duplicate param id {} ({})",
134            pi.id,
135            pi.name
136        );
137        seen.push(pi.id);
138    }
139}
140
141/// `count()` matches `param_infos().len()`.
142pub fn assert_param_count_matches<L: PluginLogic>() {
143    let p = L::Params::default();
144    assert_eq!(
145        p.count(),
146        p.param_infos().len(),
147        "Params::count() != param_infos().len()"
148    );
149}
150
151/// Defaults match `ParamInfo::default_plain` within 1e-9.
152pub fn assert_param_defaults_match<L: PluginLogic>() {
153    let p = L::Params::default();
154    for pi in p.param_infos() {
155        let v = p
156            .get_plain(pi.id)
157            .unwrap_or_else(|| panic!("param {} ({}) has no get_plain", pi.id, pi.name));
158        assert!(
159            (v - pi.default_plain).abs() < 1e-9,
160            "param {} ({}) default mismatch: value={v} info={}",
161            pi.id,
162            pi.name,
163            pi.default_plain
164        );
165    }
166}
167
168/// Plugin info strings are non-empty.
169pub fn assert_valid_info<L: PluginLogic>() {
170    let info = L::info();
171    assert!(!info.name.is_empty(), "PluginInfo.name is empty");
172    assert!(!info.vendor.is_empty(), "PluginInfo.vendor is empty");
173    assert!(!info.bundle_id.is_empty(), "PluginInfo.bundle_id is empty");
174    assert!(!info.clap_id.is_empty(), "PluginInfo.clap_id is empty");
175}
176
177// ---------------------------------------------------------------------------
178// Process smoke (offline, no host)
179// ---------------------------------------------------------------------------
180
181/// Run one process block of silence; return per-channel output buffers.
182///
183/// Uses the first bus layout’s main channel count (default stereo).
184///
185/// # Panics
186///
187/// If process panics (not fenced — test harness wants the panic).
188pub fn process_silence<L: PluginLogic>(channels: usize, frames: usize) -> Vec<Vec<f32>> {
189    process_with_input::<L>(&vec![vec![0.0f32; frames]; channels], frames)
190}
191
192/// Process one block from owned input channels (same length).
193pub fn process_with_input<L: PluginLogic>(inputs: &[Vec<f32>], frames: usize) -> Vec<Vec<f32>> {
194    let params = L::Params::default();
195    let sample_rate = 44_100.0;
196    let mut state = L::init(&params, sample_rate);
197    let layout = L::bus_layouts().into_iter().next();
198    let ch_in = layout.map_or(inputs.len(), |l| l.main_input_channels() as usize);
199    let ch_out = layout
200        .map_or(inputs.len(), |l| l.main_output_channels() as usize)
201        .max(1);
202    #[allow(clippy::cast_possible_truncation)] // channel counts are tiny
203    let config = AudioConfig::new(sample_rate, frames).with_channels(ch_in as u32, ch_out as u32);
204    L::reset(&mut state, &params, &config);
205
206    let owned_in: Vec<Vec<f32>> = (0..ch_out)
207        .map(|c| inputs.get(c).cloned().unwrap_or_else(|| vec![0.0; frames]))
208        .collect();
209    let mut owned_out = owned_in.clone();
210
211    let in_refs: Vec<&[f32]> = owned_in.iter().map(Vec::as_slice).collect();
212    let mut out_refs: Vec<&mut [f32]> = owned_out.iter_mut().map(Vec::as_mut_slice).collect();
213    let mut buffer = AudioBuffer::from_slices_checked(&in_refs, &mut out_refs, frames);
214    let mut ctx = ProcessContext::new(sample_rate, frames).with_process_mode(ProcessMode::Realtime);
215    let status = L::process(&mut state, &params, &mut buffer, &mut ctx);
216    assert!(
217        matches!(
218            status,
219            ProcessStatus::Continue | ProcessStatus::TailFinished
220        ),
221        "process returned Error"
222    );
223    owned_out
224}
225
226// ---------------------------------------------------------------------------
227// Buffer assertions
228// ---------------------------------------------------------------------------
229
230const AUDIBLE: f32 = 1e-3;
231
232/// Every sample is finite (no NaN / Inf).
233///
234/// # Panics
235///
236/// On first non-finite sample.
237pub fn assert_no_nans(channels: &[Vec<f32>]) {
238    for (ci, ch) in channels.iter().enumerate() {
239        for (i, s) in ch.iter().enumerate() {
240            assert!(s.is_finite(), "non-finite sample at ch={ci} i={i}: {s}");
241        }
242    }
243}
244
245/// At least one |sample| > 1e-3.
246pub fn assert_nonzero(channels: &[Vec<f32>]) {
247    let peak = channels
248        .iter()
249        .flat_map(|c| c.iter())
250        .map(|s| s.abs())
251        .fold(0.0f32, f32::max);
252    assert!(
253        peak > AUDIBLE,
254        "output is silent (peak={peak}); expected audible content"
255    );
256}
257
258/// Every |sample| ≤ 1e-3.
259pub fn assert_silence(channels: &[Vec<f32>]) {
260    let peak = channels
261        .iter()
262        .flat_map(|c| c.iter())
263        .map(|s| s.abs())
264        .fold(0.0f32, f32::max);
265    assert!(peak <= AUDIBLE, "output not silent (peak={peak})");
266}
267
268// ---------------------------------------------------------------------------
269// Self-tests (minimal PluginLogic)
270// ---------------------------------------------------------------------------
271
272#[cfg(test)]
273mod tests {
274    use std::sync::Arc;
275
276    use aura_core::{
277        AudioBuffer, AudioConfig, Editor, PluginInfo, PluginLogic, ProcessContext, ProcessStatus,
278    };
279    use aura_params::{
280        FloatParam, ParamFlags, ParamInfo, ParamRange, ParamUnit, ParamValueKind, Params,
281    };
282
283    use super::*;
284
285    struct GainParams {
286        gain: FloatParam,
287    }
288
289    impl aura_params::__private::Sealed for GainParams {}
290
291    impl Default for GainParams {
292        fn default() -> Self {
293            Self {
294                gain: FloatParam::new(
295                    ParamInfo {
296                        id: 1,
297                        name: "Gain",
298                        short_name: "Gain",
299                        group: "",
300                        range: ParamRange::Linear {
301                            min: -24.0,
302                            max: 24.0,
303                        },
304                        default_plain: 0.0,
305                        flags: ParamFlags::AUTOMATABLE,
306                        unit: ParamUnit::Db,
307                        kind: ParamValueKind::Float,
308                        midi_map: None,
309                        midi_channel: None,
310                    },
311                    aura_params::SmoothingStyle::None,
312                ),
313            }
314        }
315    }
316
317    impl Params for GainParams {
318        fn param_infos(&self) -> Vec<ParamInfo> {
319            vec![self.gain.info]
320        }
321        fn count(&self) -> usize {
322            1
323        }
324        fn get_plain(&self, id: u32) -> Option<f64> {
325            (id == 1).then(|| self.gain.raw_target())
326        }
327        fn set_plain(&self, id: u32, value: f64) {
328            if id == 1 {
329                self.gain.set_value(value);
330            }
331        }
332        fn get_normalized(&self, id: u32) -> Option<f64> {
333            self.get_plain(id)
334                .map(|v| self.gain.info.range.normalize(v))
335        }
336        fn set_normalized(&self, id: u32, n: f64) {
337            if id == 1 {
338                let p = self.gain.info.range.denormalize(n);
339                self.gain.set_value(p);
340            }
341        }
342        fn set_sample_rate(&self, _sr: f64) {}
343        fn snap_smoothers(&self) {}
344        fn collect_values(&self) -> (Vec<u32>, Vec<f64>) {
345            (vec![1], vec![self.gain.raw_target()])
346        }
347        fn restore_values(&self, values: &[(u32, f64)]) {
348            for &(id, v) in values {
349                self.set_plain(id, v);
350            }
351        }
352        fn format_value(&self, id: u32, plain: f64) -> Option<String> {
353            (id == 1).then(|| format!("{plain:.1}"))
354        }
355        fn parse_value(&self, id: u32, text: &str) -> Option<f64> {
356            (id == 1).then(|| text.parse().ok()).flatten()
357        }
358    }
359
360    struct GainPlug;
361    struct GainState;
362
363    impl PluginLogic for GainPlug {
364        type Params = GainParams;
365        type DspState = GainState;
366
367        fn info() -> PluginInfo {
368            PluginInfo::new("Gain", "Test", "0.1.0", "gain")
369        }
370
371        fn init(_params: &Self::Params, _sr: f64) -> Self::DspState {
372            GainState
373        }
374
375        fn reset(_s: &mut Self::DspState, _p: &Self::Params, _c: &AudioConfig) {}
376
377        fn process(
378            _s: &mut Self::DspState,
379            params: &Self::Params,
380            buffer: &mut AudioBuffer<'_, f32>,
381            _ctx: &mut ProcessContext,
382        ) -> ProcessStatus {
383            #[allow(clippy::cast_possible_truncation)]
384            let g = 10.0f32.powf(params.gain.raw_target() as f32 / 20.0);
385            let n = buffer.num_samples();
386            let ch = buffer.num_outputs().min(buffer.num_inputs());
387            for c in 0..ch {
388                let input: Vec<f32> = buffer.input(c).to_vec();
389                let out = buffer.output(c);
390                for i in 0..n {
391                    out[i] = input[i] * g;
392                }
393            }
394            ProcessStatus::Continue
395        }
396
397        fn editor(_p: Arc<Self::Params>) -> Option<Box<dyn Editor>> {
398            None
399        }
400    }
401
402    #[test]
403    fn state_round_trip_and_shape() {
404        assert_valid_info::<GainPlug>();
405        assert_no_duplicate_param_ids::<GainPlug>();
406        assert_param_count_matches::<GainPlug>();
407        assert_param_defaults_match::<GainPlug>();
408        assert_state_round_trip::<GainPlug>();
409        assert_corrupt_state_no_crash::<GainPlug>();
410        assert_empty_state_no_crash::<GainPlug>();
411    }
412
413    #[test]
414    fn process_silence_is_finite_and_silent() {
415        let out = process_silence::<GainPlug>(2, 64);
416        assert_eq!(out.len(), 2);
417        assert_no_nans(&out);
418        assert_silence(&out);
419    }
420
421    #[test]
422    fn process_constant_is_nonzero() {
423        let frames = 32;
424        let input = vec![vec![0.5f32; frames]; 2];
425        let out = process_with_input::<GainPlug>(&input, frames);
426        assert_no_nans(&out);
427        assert_nonzero(&out);
428    }
429}