rvtest 0.2.0

A Next Level Testing Library for Rust — BDD specs, property-based testing, parametrized tests, rich reporting, and code coverage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
use std::fmt::Debug;
use std::marker::PhantomData;

use rand::rngs::StdRng;
use rand::{Rng, RngExt, SeedableRng};

const DEFAULT_NUM_TESTS: u64 = 100;
const DEFAULT_SHRINKS: u64 = 1000;

/// A strategy for generating random values of type `T`.
///
/// Implement this trait to define how values are produced and optionally
/// shrunk when a failing counterexample is found.
///
/// # Shrinking
///
/// Shrinking tries to simplify a counterexample to its minimal form,
/// making failures easier to diagnose. The default implementation returns
/// an empty vector (no shrinking).
pub trait Strategy<T>: Send + Sync {
    /// Generate a random value of type `T`.
    fn generate(&self, rng: &mut dyn Rng) -> T;

    /// Produce a list of simpler candidates from a given value, used for
    /// shrinking counterexamples.
    fn shrink(&self, _value: &T) -> Vec<T> {
        Vec::new()
    }
}

// ---------------------------------------------------------------------------
// Built-in strategies for common types
// ---------------------------------------------------------------------------

macro_rules! impl_range_strategy {
    ($ty:ty, $range:expr) => {
        impl Strategy<$ty> for RangeStrategy<$ty> {
            fn generate(&self, rng: &mut dyn Rng) -> $ty {
                rng.random_range($range)
            }
        }
    };
}

/// Strategy that produces values in a given range.
#[derive(Debug, Clone)]
pub struct RangeStrategy<T> {
    _marker: PhantomData<T>,
}

impl_range_strategy!(i8, i8::MIN..=i8::MAX);
impl_range_strategy!(i16, i16::MIN..=i16::MAX);
impl_range_strategy!(i32, i32::MIN..=i32::MAX);
impl_range_strategy!(i64, i64::MIN..=i64::MAX);
impl_range_strategy!(u8, u8::MIN..=u8::MAX);
impl_range_strategy!(u16, u16::MIN..=u16::MAX);
impl_range_strategy!(u32, u32::MIN..=u32::MAX);
impl_range_strategy!(u64, u64::MIN..=u64::MAX);
impl_range_strategy!(usize, usize::MIN..=usize::MAX);

impl Strategy<bool> for RangeStrategy<bool> {
    fn generate(&self, rng: &mut dyn Rng) -> bool {
        rng.random_bool(0.5)
    }

    fn shrink(&self, value: &bool) -> Vec<bool> {
        if *value { vec![false] } else { vec![] }
    }
}

/// Return a strategy for any value of type `T`.
///
/// Supported types: all standard integer types, `bool`, and types composed
/// via combinators.
///
/// # Example
///
/// ```ignore
/// use rvtest::property::{check, any};
///
/// check("addition is commutative", any::<i32>(), |v: &i32| true);
/// ```
pub fn any<T: StrategyProvider>() -> T::Strategy {
    T::strategy()
}

/// Trait mapping a type to its default `Strategy`.
///
/// Types that implement [`StrategyProvider`] can be used with [`any`] to
/// obtain a default strategy for property-based testing.
pub trait StrategyProvider: Sized {
    /// The strategy type used to generate values of `Self`.
    type Strategy: Strategy<Self> + Default + Send + Sync;

    /// Returns the default strategy for this type.
    fn strategy() -> Self::Strategy {
        Self::Strategy::default()
    }
}

macro_rules! impl_provider {
    ($ty:ty) => {
        impl StrategyProvider for $ty {
            type Strategy = RangeStrategy<$ty>;

            fn strategy() -> Self::Strategy {
                RangeStrategy { _marker: PhantomData }
            }
        }

        impl Default for RangeStrategy<$ty> {
            fn default() -> Self {
                RangeStrategy { _marker: PhantomData }
            }
        }
    };
}

impl_provider!(i8);
impl_provider!(i16);
impl_provider!(i32);
impl_provider!(i64);
impl_provider!(u8);
impl_provider!(u16);
impl_provider!(u32);
impl_provider!(u64);
impl_provider!(usize);
impl_provider!(bool);

// ---------------------------------------------------------------------------
// Vec strategy
// ---------------------------------------------------------------------------

/// Strategy for generating `Vec<T>` values.
#[derive(Debug, Clone)]
pub struct VecStrategy<S> {
    element_strategy: S,
    min_len: usize,
    max_len: usize,
}

impl<T, S> Strategy<Vec<T>> for VecStrategy<S>
where
    S: Strategy<T> + Send + Sync,
    T: Send + Clone,
{
    fn generate(&self, rng: &mut dyn Rng) -> Vec<T> {
        let len = rng.random_range(self.min_len..=self.max_len);
        (0..len).map(|_| self.element_strategy.generate(rng)).collect()
    }

    fn shrink(&self, value: &Vec<T>) -> Vec<Vec<T>> {
        let mut candidates = Vec::new();
        if !value.is_empty() {
            let mut smaller = (*value).clone();
            smaller.pop();
            candidates.push(smaller);
        }
        candidates
    }
}

/// Create a strategy that generates `Vec<T>`s with elements from `strategy`.
///
/// The vector length ranges from `min_len` to `max_len` (inclusive).
pub fn vec<T, S>(strategy: S, min_len: usize, max_len: usize) -> VecStrategy<S>
where
    S: Strategy<T>,
{
    VecStrategy { element_strategy: strategy, min_len, max_len }
}

// ---------------------------------------------------------------------------
// Mapping combinator
// ---------------------------------------------------------------------------

/// A strategy that transforms generated values with a mapping function.
pub struct MapStrategy<S, F, T, U> {
    inner: S,
    f: F,
    _phantom: PhantomData<(T, U)>,
}

impl<S: Clone, F: Clone, T, U> Clone for MapStrategy<S, F, T, U> {
    fn clone(&self) -> Self {
        MapStrategy {
            inner: self.inner.clone(),
            f: self.f.clone(),
            _phantom: PhantomData,
        }
    }
}

impl<S: Debug, F, T, U> Debug for MapStrategy<S, F, T, U> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MapStrategy").field("inner", &self.inner).finish()
    }
}

impl<T, U, S, F> Strategy<U> for MapStrategy<S, F, T, U>
where
    S: Strategy<T>,
    F: Fn(T) -> U + Send + Sync,
    T: Send + Sync,
    U: Send + Sync,
{
    fn generate(&self, rng: &mut dyn Rng) -> U {
        (self.f)(self.inner.generate(rng))
    }

    fn shrink(&self, value: &U) -> Vec<U> {
        // Mapping makes shrinking complex; skip for now.
        let _ = value;
        Vec::new()
    }
}

/// Transform a strategy's output with a mapping function.
pub fn map<T, U, S, F>(strategy: S, f: F) -> MapStrategy<S, F, T, U>
where
    S: Strategy<T>,
    F: Fn(T) -> U,
{
    MapStrategy { inner: strategy, f, _phantom: PhantomData }
}

// ---------------------------------------------------------------------------
// Filter combinator
// ---------------------------------------------------------------------------

/// A strategy that only produces values satisfying a predicate.
pub struct FilterStrategy<S, P, T> {
    inner: S,
    predicate: P,
    max_attempts: u32,
    _phantom: PhantomData<T>,
}

impl<S: Clone, P: Clone, T> Clone for FilterStrategy<S, P, T> {
    fn clone(&self) -> Self {
        FilterStrategy {
            inner: self.inner.clone(),
            predicate: self.predicate.clone(),
            max_attempts: self.max_attempts,
            _phantom: PhantomData,
        }
    }
}

impl<S: Debug, P, T> Debug for FilterStrategy<S, P, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FilterStrategy").field("inner", &self.inner).finish()
    }
}

impl<T, S, P> Strategy<T> for FilterStrategy<S, P, T>
where
    S: Strategy<T>,
    P: Fn(&T) -> bool + Send + Sync,
    T: Send + Sync,
{
    fn generate(&self, rng: &mut dyn Rng) -> T {
        for _ in 0..self.max_attempts {
            let value = self.inner.generate(rng);
            if (self.predicate)(&value) {
                return value;
            }
        }
        self.inner.generate(rng)
    }

    fn shrink(&self, value: &T) -> Vec<T> {
        self.inner
            .shrink(value)
            .into_iter()
            .filter(|v| (self.predicate)(v))
            .collect()
    }
}

/// Create a strategy that only generates values satisfying a predicate.
pub fn filter<T, S, P>(strategy: S, predicate: P) -> FilterStrategy<S, P, T>
where
    S: Strategy<T>,
    P: Fn(&T) -> bool,
{
    FilterStrategy { inner: strategy, predicate, max_attempts: 100, _phantom: PhantomData }
}

// ---------------------------------------------------------------------------
// Property check
// ---------------------------------------------------------------------------

/// Configuration for property-based test execution.
#[derive(Debug, Clone)]
pub struct PropertyConfig {
    /// How many random test cases to generate.
    pub num_tests: u64,
    /// Maximum number of shrink steps per failing case.
    pub max_shrinks: u64,
    /// Seed for deterministic replay.
    pub seed: Option<u64>,
}

impl Default for PropertyConfig {
    fn default() -> Self {
        PropertyConfig { num_tests: DEFAULT_NUM_TESTS, max_shrinks: DEFAULT_SHRINKS, seed: None }
    }
}

/// Run a property-based test.
///
/// Generates random inputs using the given `strategy`, passing each to
/// `property`. If the property returns `false` for any input, the function
/// attempts to shrink the counterexample and then panics with a descriptive
/// message.
///
/// # Example
///
/// ```ignore
/// use rvtest::property::{check, any};
///
/// check("reversal is involutive", any::<Vec<i32>>(), |v: &Vec<i32>| {
///     let rev: Vec<_> = v.iter().rev().copied().collect();
///     let revrev: Vec<_> = rev.iter().rev().copied().collect();
///     revrev == **v
/// });
/// ```
pub fn check<T, S>(
    _name: &str,
    strategy: S,
    property: impl Fn(&T) -> bool,
) where
    T: Debug,
    S: Strategy<T>,
{
    check_with(_name, strategy, property, PropertyConfig::default());
}

/// Run a property-based test with a custom configuration.
///
/// Same as [`check`] but accepts a [`PropertyConfig`] for fine-grained
/// control over the number of tests, shrinking, and seeding.
pub fn check_with<T, S>(
    _name: &str,
    strategy: S,
    property: impl Fn(&T) -> bool,
    config: PropertyConfig,
) where
    T: Debug,
    S: Strategy<T>,
{
    let seed = config.seed.unwrap_or_else(rand::random);
    let mut rng = StdRng::seed_from_u64(seed);

    for _ in 0..config.num_tests {
        let value = strategy.generate(&mut rng);
        if !property(&value) {
            let shrunk = shrink_counterexample(&value, &strategy, &property, config.max_shrinks);
            panic!(
                "property falsified after {} test(s)\n\
                 seed: {seed}\n\
                 counterexample: {value:?}\n\
                 shrunk to: {shrunk:?}",
                config.num_tests,
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn any_bool_generates() {
        let strategy = any::<bool>();
        let mut rng = &mut StdRng::seed_from_u64(42);
        let val = strategy.generate(&mut rng);
        // Just verify it's a bool
        let _: bool = val;
    }

    #[test]
    fn any_i32_generates() {
        let strategy = any::<i32>();
        let mut rng = &mut StdRng::seed_from_u64(42);
        for _ in 0..100 {
            let val = strategy.generate(&mut rng);
            assert!(val >= i32::MIN && val <= i32::MAX);
        }
    }

    #[test]
    fn any_u64_generates() {
        let strategy = any::<u64>();
        let mut rng = &mut StdRng::seed_from_u64(99);
        for _ in 0..10 {
            let _val = strategy.generate(&mut rng);
        }
    }

    #[test]
    fn any_is_strategy_provider() {
        // Compile-time check: types with StrategyProvider work
        let _s: RangeStrategy<i32> = any::<i32>();
        let _s: RangeStrategy<bool> = any::<bool>();
    }

    #[test]
    fn check_passes_for_valid_property() {
        check("identity", any::<i32>(), |a: &i32| *a + 0 == *a);
    }

    #[test]
    fn check_panics_on_false_property() {
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            check("false", any::<i32>(), |_: &i32| false);
        }));
        assert!(result.is_err());
    }

    #[test]
    fn check_with_custom_config() {
        let config = PropertyConfig { num_tests: 5, max_shrinks: 10, seed: Some(12345) };
        check_with("custom", any::<u32>(), |_: &u32| true, config);
    }

    #[test]
    fn bool_shrink_true_to_false() {
        let strategy = any::<bool>();
        let shrunk = strategy.shrink(&true);
        assert_eq!(shrunk, vec![false]);
    }

    #[test]
    fn bool_shrink_false_empty() {
        let strategy = any::<bool>();
        let shrunk = strategy.shrink(&false);
        assert!(shrunk.is_empty());
    }

    #[test]
    fn map_transforms_output() {
        let strategy = map(any::<i32>(), |x| x.to_string());
        let mut rng = &mut StdRng::seed_from_u64(7);
        let val = strategy.generate(&mut rng);
        // Result should be a String representation of an i32
        let _parsed: i32 = val.parse().expect("should be a valid i32 string");
    }

    #[test]
    fn filter_rejects_bad_values() {
        let strategy = filter(any::<i32>(), |x| x % 2 == 0);
        let mut rng = &mut StdRng::seed_from_u64(42);
        for _ in 0..50 {
            let val = strategy.generate(&mut rng);
            assert!(val % 2 == 0, "filter should only produce even numbers, got {val}");
        }
    }

    #[test]
    fn vec_strategy_generates() {
        let strategy = vec(any::<i32>(), 0, 5);
        let mut rng = &mut StdRng::seed_from_u64(1);
        for _ in 0..20 {
            let v = strategy.generate(&mut rng);
            assert!(v.len() <= 5, "vec len {} > max 5", v.len());
        }
    }

    #[test]
    fn vec_strategy_shrink_pops() {
        let strategy = vec(any::<i32>(), 0, 10);
        let candidates = strategy.shrink(&vec![1, 2, 3]);
        assert_eq!(candidates, vec![vec![1, 2]]);
    }

    #[test]
    fn vec_strategy_shrink_empty() {
        let strategy = vec(any::<i32>(), 0, 10);
        let candidates: Vec<Vec<i32>> = strategy.shrink(&vec![]);
        assert!(candidates.is_empty());
    }

    #[test]
    fn strategy_provider_for_all_int_types() {
        // Compile-time checks
        let _: RangeStrategy<i8> = any::<i8>();
        let _: RangeStrategy<i16> = any::<i16>();
        let _: RangeStrategy<i64> = any::<i64>();
        let _: RangeStrategy<u8> = any::<u8>();
        let _: RangeStrategy<u16> = any::<u16>();
        let _: RangeStrategy<u32> = any::<u32>();
        let _: RangeStrategy<u64> = any::<u64>();
        let _: RangeStrategy<usize> = any::<usize>();
    }

    #[test]
    fn default_property_config() {
        let cfg = PropertyConfig::default();
        assert_eq!(cfg.num_tests, DEFAULT_NUM_TESTS);
        assert_eq!(cfg.max_shrinks, DEFAULT_SHRINKS);
        assert!(cfg.seed.is_none());
    }

    mod map_strategy {
        use super::*;

        #[test]
        fn cloned_works() {
            let s = map(any::<i32>(), |x| x * 2);
            let _ = s.clone();
        }
    }
}

/// Attempt to shrink a counterexample to its minimal form.
fn shrink_counterexample<T, S>(
    value: &T,
    strategy: &S,
    property: &impl Fn(&T) -> bool,
    max_shrinks: u64,
) -> String
where
    T: Debug,
    S: Strategy<T>,
{
    let mut best_repr = format!("{:?}", value);
    let mut candidates = strategy.shrink(value);
    let mut iterations = 0u64;

    while !candidates.is_empty() && iterations < max_shrinks {
        match candidates.into_iter().find(|c| !property(c)) {
            Some(candidate) => {
                best_repr = format!("{:?}", candidate);
                candidates = strategy.shrink(&candidate);
            }
            None => break,
        }
        iterations += 1;
    }

    best_repr
}