Skip to main content

quack_rs/testing/
harness.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2026 Tom F. <https://github.com/tomtom215/>
3// My way of giving something small back to the open source community
4// and encouraging more Rust development!
5
6//! [`AggregateTestHarness`] — test aggregate logic without `DuckDB`.
7//!
8//! Simulates the `DuckDB` aggregate lifecycle in pure Rust:
9//! `init → N × update → combine (optional) → finalize`
10
11use crate::aggregate::AggregateState;
12
13/// A test harness that simulates the `DuckDB` aggregate function lifecycle in
14/// pure Rust, without requiring a `DuckDB` instance.
15///
16/// # Usage
17///
18/// ```rust
19/// use quack_rs::testing::AggregateTestHarness;
20/// use quack_rs::aggregate::AggregateState;
21///
22/// #[derive(Default, Debug, PartialEq)]
23/// struct Counter { n: u64 }
24/// impl AggregateState for Counter {}
25///
26/// let mut harness = AggregateTestHarness::<Counter>::new();
27/// harness.update(|c| c.n += 1);
28/// harness.update(|c| c.n += 1);
29/// harness.update(|c| c.n += 1);
30///
31/// let state = harness.finalize();
32/// assert_eq!(state.n, 3);
33/// ```
34pub struct AggregateTestHarness<S: AggregateState> {
35    state: S,
36}
37
38impl<S: AggregateState> AggregateTestHarness<S> {
39    /// Creates a new harness with a fresh `S::default()` state.
40    ///
41    /// # Example
42    ///
43    /// ```rust
44    /// use quack_rs::testing::AggregateTestHarness;
45    /// use quack_rs::aggregate::AggregateState;
46    ///
47    /// #[derive(Default)]
48    /// struct MyState { count: u64 }
49    /// impl AggregateState for MyState {}
50    ///
51    /// let harness = AggregateTestHarness::<MyState>::new();
52    /// ```
53    #[must_use]
54    pub fn new() -> Self {
55        Self {
56            state: S::default(),
57        }
58    }
59
60    /// Creates a harness with an explicit initial state.
61    ///
62    /// Useful for testing `combine` with a pre-populated state.
63    #[must_use]
64    pub const fn with_state(state: S) -> Self {
65        Self { state }
66    }
67
68    /// Applies an update to the current state.
69    ///
70    /// Simulates one row being processed by the aggregate's `update` callback.
71    ///
72    /// # Example
73    ///
74    /// ```rust
75    /// use quack_rs::testing::AggregateTestHarness;
76    /// use quack_rs::aggregate::AggregateState;
77    ///
78    /// #[derive(Default)]
79    /// struct Sum { total: i64 }
80    /// impl AggregateState for Sum {}
81    ///
82    /// let mut h = AggregateTestHarness::<Sum>::new();
83    /// h.update(|s| s.total += 5);
84    /// h.update(|s| s.total += 3);
85    /// ```
86    pub fn update<F>(&mut self, f: F)
87    where
88        F: FnOnce(&mut S),
89    {
90        f(&mut self.state);
91    }
92
93    /// Simulates a `combine` operation: merges the source harness's state into
94    /// this harness's state using the provided combine function.
95    ///
96    /// This tests the correctness of your `combine` implementation, including the
97    /// critical requirement that all configuration fields are propagated from source
98    /// to target (Pitfall L1 / Problem 4).
99    ///
100    /// # Example
101    ///
102    /// ```rust
103    /// use quack_rs::testing::AggregateTestHarness;
104    /// use quack_rs::aggregate::AggregateState;
105    ///
106    /// #[derive(Default, Clone)]
107    /// struct Sum { total: i64 }
108    /// impl AggregateState for Sum {}
109    ///
110    /// let mut h1 = AggregateTestHarness::<Sum>::new();
111    /// h1.update(|s| s.total += 10);
112    ///
113    /// let mut h2 = AggregateTestHarness::<Sum>::new();
114    /// h2.update(|s| s.total += 20);
115    ///
116    /// // Combine h1 into h2
117    /// h2.combine(&h1, |source, target| target.total += source.total);
118    ///
119    /// let result = h2.finalize();
120    /// assert_eq!(result.total, 30);
121    /// ```
122    pub fn combine<F>(&mut self, source: &Self, combine_fn: F)
123    where
124        F: FnOnce(&S, &mut S),
125    {
126        combine_fn(&source.state, &mut self.state);
127    }
128
129    /// Consumes the harness and returns the final state.
130    ///
131    /// Simulates `DuckDB` calling the `finalize` callback.
132    ///
133    /// # Example
134    ///
135    /// ```rust
136    /// use quack_rs::testing::AggregateTestHarness;
137    /// use quack_rs::aggregate::AggregateState;
138    ///
139    /// #[derive(Default, Debug, PartialEq)]
140    /// struct Sum { total: i64 }
141    /// impl AggregateState for Sum {}
142    ///
143    /// let mut h = AggregateTestHarness::<Sum>::new();
144    /// h.update(|s| s.total = 42);
145    /// assert_eq!(h.finalize().total, 42);
146    /// ```
147    #[must_use]
148    pub fn finalize(self) -> S {
149        self.state
150    }
151
152    /// Borrows the current state for inspection without consuming the harness.
153    ///
154    /// Useful for asserting intermediate state during a sequence of updates.
155    ///
156    /// # Example
157    ///
158    /// ```rust
159    /// use quack_rs::testing::AggregateTestHarness;
160    /// use quack_rs::aggregate::AggregateState;
161    ///
162    /// #[derive(Default)]
163    /// struct Sum { total: i64 }
164    /// impl AggregateState for Sum {}
165    ///
166    /// let mut h = AggregateTestHarness::<Sum>::new();
167    /// h.update(|s| s.total += 5);
168    /// assert_eq!(h.state().total, 5);
169    /// h.update(|s| s.total += 3);
170    /// assert_eq!(h.state().total, 8);
171    /// ```
172    #[must_use]
173    pub const fn state(&self) -> &S {
174        &self.state
175    }
176
177    /// Resets the state to `S::default()`.
178    ///
179    /// Useful for running multiple scenarios with a single harness.
180    pub fn reset(&mut self) {
181        self.state = S::default();
182    }
183
184    /// Runs a sequence of updates from an iterator and returns the final state.
185    ///
186    /// This is a convenience method for testing aggregate functions over a
187    /// collection of input values.
188    ///
189    /// # Example
190    ///
191    /// ```rust
192    /// use quack_rs::testing::AggregateTestHarness;
193    /// use quack_rs::aggregate::AggregateState;
194    ///
195    /// #[derive(Default)]
196    /// struct Sum { total: i64 }
197    /// impl AggregateState for Sum {}
198    ///
199    /// let result = AggregateTestHarness::<Sum>::aggregate(
200    ///     [1_i64, 2, 3, 4, 5],
201    ///     |s, v| s.total += v,
202    /// );
203    /// assert_eq!(result.total, 15);
204    /// ```
205    pub fn aggregate<I, T, F>(inputs: I, update_fn: F) -> S
206    where
207        I: IntoIterator<Item = T>,
208        F: Fn(&mut S, T),
209    {
210        let mut harness = Self::new();
211        for input in inputs {
212            harness.update(|s| update_fn(s, input));
213        }
214        harness.finalize()
215    }
216}
217
218impl<S: AggregateState> Default for AggregateTestHarness<S> {
219    fn default() -> Self {
220        Self::new()
221    }
222}
223
224impl<S: AggregateState> core::fmt::Debug for AggregateTestHarness<S> {
225    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
226        f.debug_struct("AggregateTestHarness")
227            .field("state", &core::any::type_name::<S>())
228            .finish_non_exhaustive()
229    }
230}
231
232#[cfg(test)]
233mod tests {
234    use super::*;
235    use crate::aggregate::AggregateState;
236
237    #[derive(Default, Debug, PartialEq, Clone)]
238    struct SumState {
239        total: i64,
240    }
241    impl AggregateState for SumState {}
242
243    #[derive(Default, Debug, PartialEq, Clone)]
244    struct CountConfig {
245        /// Configuration field — must be propagated in combine
246        window_size: i64,
247        count: u64,
248    }
249    impl AggregateState for CountConfig {}
250
251    #[test]
252    fn new_creates_default_state() {
253        let h = AggregateTestHarness::<SumState>::new();
254        assert_eq!(h.state().total, 0);
255    }
256
257    #[test]
258    fn with_state() {
259        let initial = SumState { total: 100 };
260        let h = AggregateTestHarness::with_state(initial);
261        assert_eq!(h.state().total, 100);
262    }
263
264    #[test]
265    fn update_accumulates() {
266        let mut h = AggregateTestHarness::<SumState>::new();
267        h.update(|s| s.total += 10);
268        h.update(|s| s.total += 20);
269        h.update(|s| s.total += 5);
270        assert_eq!(h.finalize().total, 35);
271    }
272
273    #[test]
274    fn finalize_returns_state() {
275        let mut h = AggregateTestHarness::<SumState>::new();
276        h.update(|s| s.total = 42);
277        assert_eq!(h.finalize(), SumState { total: 42 });
278    }
279
280    #[test]
281    fn state_borrow() {
282        let mut h = AggregateTestHarness::<SumState>::new();
283        h.update(|s| s.total = 7);
284        assert_eq!(h.state().total, 7);
285        // Can still update after borrowing
286        h.update(|s| s.total += 1);
287        assert_eq!(h.state().total, 8);
288    }
289
290    #[test]
291    fn reset_clears_state() {
292        let mut h = AggregateTestHarness::<SumState>::new();
293        h.update(|s| s.total = 999);
294        h.reset();
295        assert_eq!(h.state().total, 0);
296    }
297
298    #[test]
299    fn combine_merges_states() {
300        let mut h1 = AggregateTestHarness::<SumState>::new();
301        h1.update(|s| s.total += 10);
302
303        let mut h2 = AggregateTestHarness::<SumState>::new();
304        h2.update(|s| s.total += 20);
305
306        h2.combine(&h1, |src, tgt| tgt.total += src.total);
307        assert_eq!(h2.finalize().total, 30);
308    }
309
310    #[test]
311    fn combine_propagates_config_fields() {
312        // This test demonstrates Pitfall L1: combine must propagate config fields.
313        // If window_size is not propagated, the merged state will have window_size = 0.
314        let mut h1 = AggregateTestHarness::<CountConfig>::new();
315        h1.update(|s| {
316            s.window_size = 3600; // config field
317            s.count += 5;
318        });
319
320        let h2 = AggregateTestHarness::<CountConfig>::new();
321        // h2 holds `CountConfig::default()`, like a target DuckDB creates with `state_init`
322
323        let mut target = h2;
324        target.combine(&h1, |src, tgt| {
325            // Correct: propagate ALL fields including config
326            tgt.window_size = src.window_size;
327            tgt.count += src.count;
328        });
329
330        let result = target.finalize();
331        assert_eq!(
332            result.window_size, 3600,
333            "config field must be propagated in combine"
334        );
335        assert_eq!(result.count, 5);
336    }
337
338    #[test]
339    fn combine_bug_missing_config_propagation() {
340        // This test demonstrates WHAT GOES WRONG if you forget to propagate config fields.
341        let mut h1 = AggregateTestHarness::<CountConfig>::new();
342        h1.update(|s| {
343            s.window_size = 3600;
344            s.count += 5;
345        });
346
347        let h2 = AggregateTestHarness::<CountConfig>::new();
348        let mut target = h2;
349
350        // BUG: only propagate count, forget window_size
351        target.combine(&h1, |src, tgt| {
352            tgt.count += src.count; // forgot: tgt.window_size = src.window_size
353        });
354
355        let result = target.finalize();
356        assert_eq!(
357            result.window_size, 0,
358            "demonstrates the bug: config is lost"
359        );
360        assert_eq!(result.count, 5);
361    }
362
363    #[test]
364    fn aggregate_convenience_method() {
365        let result =
366            AggregateTestHarness::<SumState>::aggregate([1_i64, 2, 3, 4, 5], |s, v| s.total += v);
367        assert_eq!(result.total, 15);
368    }
369
370    #[test]
371    fn aggregate_empty_input() {
372        let result =
373            AggregateTestHarness::<SumState>::aggregate(std::iter::empty::<i64>(), |s, v| {
374                s.total += v;
375            });
376        assert_eq!(result.total, 0);
377    }
378
379    #[test]
380    fn default_impl() {
381        let h = AggregateTestHarness::<SumState>::default();
382        assert_eq!(h.state().total, 0);
383    }
384
385    mod proptest_harness {
386        use super::*;
387        use proptest::prelude::*;
388
389        proptest! {
390            #[test]
391            fn aggregate_sum_matches_iter_sum(values: Vec<i64>) {
392                // Filter values that would overflow
393                let safe_values: Vec<i64> = values.iter().copied()
394                    .filter(|&v| v.abs() < 1_000_000)
395                    .collect();
396
397                let harness_sum = AggregateTestHarness::<SumState>::aggregate(
398                    safe_values.iter().copied(),
399                    |s, v| s.total += v,
400                );
401                let iter_sum: i64 = safe_values.iter().sum();
402                prop_assert_eq!(harness_sum.total, iter_sum);
403            }
404
405            #[test]
406            fn combine_is_associative(a: i64, b: i64, c: i64) {
407                // Test: (a + b) + c == a + (b + c) for SumState
408                let limit = 1_000_000_i64;
409                let (a, b, c) = (a % limit, b % limit, c % limit);
410
411                // (a + b) + c
412                let mut h1 = AggregateTestHarness::<SumState>::new();
413                h1.update(|s| s.total = a);
414                let mut h2 = AggregateTestHarness::<SumState>::new();
415                h2.update(|s| s.total = b);
416                h2.combine(&h1, |src, tgt| tgt.total += src.total);
417                let mut h3 = AggregateTestHarness::<SumState>::new();
418                h3.update(|s| s.total = c);
419                h3.combine(&h2, |src, tgt| tgt.total += src.total);
420                let result1 = h3.finalize().total;
421
422                // a + (b + c)
423                let mut h_b = AggregateTestHarness::<SumState>::new();
424                h_b.update(|s| s.total = b);
425                let mut h_c = AggregateTestHarness::<SumState>::new();
426                h_c.update(|s| s.total = c);
427                h_c.combine(&h_b, |src, tgt| tgt.total += src.total);
428                let mut h_a = AggregateTestHarness::<SumState>::new();
429                h_a.update(|s| s.total = a);
430                h_a.combine(&h_c, |src, tgt| tgt.total += src.total);
431                let result2 = h_a.finalize().total;
432
433                prop_assert_eq!(result1, result2);
434            }
435
436            #[test]
437            fn combine_identity_element(value: i64) {
438                // Combining with an empty (default) state is idempotent
439                let v = value % 1_000_000;
440                let mut h = AggregateTestHarness::<SumState>::new();
441                h.update(|s| s.total = v);
442
443                let empty = AggregateTestHarness::<SumState>::new();
444                h.combine(&empty, |src, tgt| tgt.total += src.total);
445
446                prop_assert_eq!(h.finalize().total, v);
447            }
448        }
449    }
450}