hegeltest 0.34.0

Property-based testing for Rust, built on Hypothesis
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
546
547
548
use crate::pretty::{PrettyPrintable, PrettyPrinter};
use crate::test_case::{TestCase, labels};
use std::marker::PhantomData;
use std::sync::Arc;

/// The core trait for all generators.
///
/// Generators produce values of type `T` by drawing from the engine through
/// the [`TestCase`] passed to [`do_draw`](Self::do_draw).
pub trait Generator<T> {
    /// Produce a value.
    #[doc(hidden)]
    fn do_draw(&self, tc: &TestCase) -> T;

    /// Transform generated values using a function.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hegel::generators::{self as gs, Generator};
    ///
    /// // Generate even integers by doubling
    /// let evens = gs::integers::<i32>().map(|n| n * 2);
    /// ```
    fn map<U, F>(self, f: F) -> Mapped<T, U, F, Self>
    where
        Self: Sized,
        F: Fn(T) -> U + Send + Sync,
    {
        Mapped {
            source: self,
            f: Arc::new(f),
            _phantom: PhantomData,
        }
    }

    /// Generate a value, then use it to choose or configure another generator.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hegel::generators::{self as gs, Generator};
    ///
    /// // Generate a length, then a vec of exactly that length
    /// let generator = gs::integers::<usize>()
    ///     .min_value(1)
    ///     .max_value(10)
    ///     .flat_map(|len| gs::vecs(gs::integers::<i32>())
    ///         .min_size(len)
    ///         .max_size(len));
    /// ```
    fn flat_map<U, G, F>(self, f: F) -> FlatMapped<T, U, G, F, Self>
    where
        Self: Sized,
        G: Generator<U>,
        F: Fn(T) -> G + Send + Sync,
    {
        FlatMapped {
            source: self,
            f,
            _phantom: PhantomData,
        }
    }

    /// Only keep generated values that satisfy the predicate.
    ///
    /// Retries up to 3 times, then calls `assume(false)` to reject the test case.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hegel::generators::{self as gs, Generator};
    ///
    /// // Generate integers, then filter out the even ones
    /// let odds = gs::integers::<i32>().filter(|n| n % 2 != 0);
    /// ```
    fn filter<F>(self, predicate: F) -> Filtered<T, F, Self>
    where
        Self: Sized,
        F: Fn(&T) -> bool + Send + Sync,
    {
        Filtered {
            source: self,
            predicate,
            _phantom: PhantomData,
        }
    }

    /// Convert this generator into a type-erased boxed generator.
    ///
    /// This is needed when you have generators of different concrete types
    /// but the same output type and need to store them together, e.g. in a
    /// `Vec` or when passing to [`one_of()`](super::one_of).
    ///
    /// A `BoxedGenerator` is *not* a [`PrintableGenerator`], even when the
    /// generator it erases is one — box with
    /// [`boxed_printable`](PrintableGenerator::boxed_printable) instead to
    /// keep the result usable with [`draw`](crate::TestCase::draw).
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hegel::generators::{self as gs, Generator};
    ///
    /// // Different generator types producing the same output type —
    /// // boxing lets them be stored in a vec and passed to one_of
    /// let generator = vec![
    ///     gs::integers::<i32>().min_value(0).max_value(10).boxed(),
    ///     gs::integers::<i32>().map(|n| n * 100).boxed(),
    ///     gs::sampled_from(vec![1, 2, 3]).boxed(),
    /// ];
    /// ```
    fn boxed<'a>(self) -> BoxedGenerator<'a, T>
    where
        Self: Sized + Send + Sync + 'a,
    {
        BoxedGenerator {
            inner: Arc::new(self),
        }
    }

    /// Make this generator printable by describing each drawn value with `print`.
    ///
    /// This is the fine-grained control point for printing: the resulting
    /// generator satisfies [`PrintableGenerator`] for any source generator,
    /// with the drawn value's representation produced by `print` instead of
    /// the value's own [`PrettyPrintable`] implementation.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hegel::generators::{self as gs, Generator};
    ///
    /// let masked = gs::text().print_with(|_, printer| printer.text("<secret>"));
    /// ```
    fn print_with<F>(self, print: F) -> PrintedWith<Self, F>
    where
        Self: Sized,
        F: Fn(&T, &mut PrettyPrinter) + Send + Sync,
    {
        PrintedWith {
            source: self,
            print,
        }
    }

    /// Make this generator printable by printing each drawn value's own
    /// [`PrettyPrintable`] representation.
    ///
    /// Useful when a combinator chain loses printability — e.g. a `map` to a
    /// type that does implement [`PrettyPrintable`] but whose source cannot
    /// prove it, or a hand-written [`Generator`] implementation.
    fn print_as_value(self) -> PrintedAsValue<Self>
    where
        Self: Sized,
        T: PrettyPrintable,
    {
        PrintedAsValue { source: self }
    }

    /// Make this generator printable by printing each drawn value's `Debug`
    /// representation.
    ///
    /// This works for any `Debug` type, so it is the escape hatch for types
    /// the orphan rule keeps out of [`PrettyPrintable`] — standard-library
    /// and third-party types alike. Derived-`Debug` output is re-laid-out
    /// through the printer (see
    /// [`print_debug_repr`](crate::pretty::print_debug_repr)), so large
    /// values wrap like natively printed ones.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hegel::generators::{self as gs, Generator};
    /// use std::path::PathBuf;
    ///
    /// let paths = gs::text().map(PathBuf::from).print_as_debug();
    /// ```
    fn print_as_debug(self) -> PrintedAsDebug<Self>
    where
        Self: Sized,
        T: std::fmt::Debug,
    {
        PrintedAsDebug { source: self }
    }
}

/// A [`Generator`] that can print each value's representation as it draws it.
///
/// Only printable generators can be passed to [`TestCase::draw`]; a plain
/// [`Generator`] can still be drawn with [`TestCase::draw_silent`]. Most
/// generators in the library are printable — leaves unconditionally,
/// structural combinators (collections, tuples, `optional`, `one_of!`,
/// `flat_map`, `recursive`) whenever their component generators are, and value-transforming
/// combinators (`map`, `filter`, `just`, `sampled_from`, composites) whenever
/// the produced type implements [`PrettyPrintable`]. For everything else
/// there are [`Generator::print_as_value`], [`Generator::print_as_debug`],
/// and [`Generator::print_with`].
///
/// # Contract
///
/// `do_draw_and_print` must draw **exactly** the same choices as
/// [`Generator::do_draw`] — the engine explores with the silent path and
/// replays failures with the printing path, so any divergence makes failures
/// unreplayable. The reliable way to satisfy this is to write the drawing
/// logic once: implement `do_draw_and_print`, and implement
/// [`Generator::do_draw`] as
/// `self.do_draw_and_print(tc, &mut PrettyPrinter::noop())` — the no-op
/// printer discards all output, so both paths run the same body by
/// construction. Guard any work done purely for printing (formatting a
/// value, say) with [`PrettyPrinter::should_print`] to keep the silent path
/// cheap.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot print the values it draws",
    label = "`{Self}` does not implement `PrintableGenerator<{T}>`",
    note = "make it printable with `.print_as_debug()` (any `Debug` value), `.print_as_value()` (any `PrettyPrintable` value), or `.print_with(..)`",
    note = "or draw without reporting the value via `tc.draw_silent(..)`"
)]
pub trait PrintableGenerator<T>: Generator<T> {
    /// Produce a value, printing its representation to `printer` as it is
    /// drawn.
    ///
    /// A compositional implementation draws each inner generator with
    /// [`TestCase::draw_and_print`], the framework's one entry point for
    /// printed inner draws; a generator that merely forwards to an inner
    /// printable generator without printing or drawing anything itself calls
    /// the inner generator's `do_draw_and_print` directly instead, so the
    /// forwarding layer doesn't register as a second region.
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> T;

    /// Convert this generator into a type-erased boxed printable generator,
    /// as accepted by [`one_of!`](crate::one_of).
    fn boxed_printable<'a>(self) -> BoxedPrintableGenerator<'a, T>
    where
        Self: Sized + Send + Sync + 'a,
    {
        BoxedPrintableGenerator {
            inner: Arc::new(self),
        }
    }
}

/// Draw from `generator` silently, then print the drawn value's own
/// [`PrettyPrintable`] representation. The shared implementation for every
/// generator that prints by value.
pub(crate) fn draw_and_print_value<T: PrettyPrintable>(
    generator: &impl Generator<T>,
    tc: &TestCase,
    printer: &mut PrettyPrinter,
) -> T {
    let value = generator.do_draw(tc);
    value.pretty_print(printer);
    value
}

/// Result of [`Generator::print_with`].
pub struct PrintedWith<G, F> {
    source: G,
    print: F,
}

impl<T, G, F> Generator<T> for PrintedWith<G, F>
where
    G: Generator<T>,
    F: Fn(&T, &mut PrettyPrinter) + Send + Sync,
{
    fn do_draw(&self, tc: &TestCase) -> T {
        self.source.do_draw(tc)
    }
}

impl<T, G, F> PrintableGenerator<T> for PrintedWith<G, F>
where
    G: Generator<T>,
    F: Fn(&T, &mut PrettyPrinter) + Send + Sync,
{
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> T {
        let value = self.source.do_draw(tc);
        (self.print)(&value, printer);
        value
    }
}

/// Result of [`Generator::print_as_value`].
pub struct PrintedAsValue<G> {
    source: G,
}

impl<T, G> Generator<T> for PrintedAsValue<G>
where
    G: Generator<T>,
    T: PrettyPrintable,
{
    fn do_draw(&self, tc: &TestCase) -> T {
        self.source.do_draw(tc)
    }
}

impl<T, G> PrintableGenerator<T> for PrintedAsValue<G>
where
    G: Generator<T>,
    T: PrettyPrintable,
{
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> T {
        draw_and_print_value(&self.source, tc, printer)
    }
}

/// Result of [`Generator::print_as_debug`].
pub struct PrintedAsDebug<G> {
    source: G,
}

impl<T, G> Generator<T> for PrintedAsDebug<G>
where
    G: Generator<T>,
    T: std::fmt::Debug,
{
    fn do_draw(&self, tc: &TestCase) -> T {
        self.source.do_draw(tc)
    }
}

impl<T, G> PrintableGenerator<T> for PrintedAsDebug<G>
where
    G: Generator<T>,
    T: std::fmt::Debug,
{
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> T {
        let value = self.source.do_draw(tc);
        if printer.should_print() {
            crate::pretty::print_debug_repr(&format!("{value:?}"), printer);
        }
        value
    }
}

impl<T, G: Generator<T>> Generator<T> for &G {
    fn do_draw(&self, tc: &TestCase) -> T {
        (*self).do_draw(tc)
    }
}

impl<T, G: PrintableGenerator<T>> PrintableGenerator<T> for &G {
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> T {
        (*self).do_draw_and_print(tc, printer)
    }
}

/// Result of [`Generator::map`].
pub struct Mapped<T, U, F, G> {
    source: G,
    f: Arc<F>,
    _phantom: PhantomData<fn(T) -> U>,
}

impl<T, U, F, G> Generator<U> for Mapped<T, U, F, G>
where
    G: Generator<T>,
    F: Fn(T) -> U + Send + Sync,
{
    fn do_draw(&self, tc: &TestCase) -> U {
        tc.start_span(labels::MAPPED);
        let result = (self.f)(self.source.do_draw(tc));
        tc.stop_span(false);
        result
    }
}

impl<T, U, F, G> PrintableGenerator<U> for Mapped<T, U, F, G>
where
    G: Generator<T>,
    F: Fn(T) -> U + Send + Sync,
    U: PrettyPrintable,
{
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> U {
        draw_and_print_value(self, tc, printer)
    }
}

/// Result of [`Generator::flat_map`].
pub struct FlatMapped<T, U, G2, F, G1> {
    source: G1,
    f: F,
    _phantom: PhantomData<fn(T) -> (U, G2)>,
}

impl<T, U, G2, F, G1> FlatMapped<T, U, G2, F, G1>
where
    G1: Generator<T>,
    F: Fn(T) -> G2 + Send + Sync,
{
    /// The one flat-map body both draw paths run; only how the derived
    /// generator is drawn (silently or printing) is injected.
    fn draw_flat_mapped(&self, tc: &TestCase, draw_next: impl FnOnce(G2, &TestCase) -> U) -> U {
        tc.start_span(labels::FLAT_MAP);
        let intermediate = self.source.do_draw(tc);
        let next_gen = (self.f)(intermediate);
        let result = draw_next(next_gen, tc);
        tc.stop_span(false);
        result
    }
}

impl<T, U, G2, F, G1> Generator<U> for FlatMapped<T, U, G2, F, G1>
where
    G1: Generator<T>,
    G2: Generator<U>,
    F: Fn(T) -> G2 + Send + Sync,
{
    fn do_draw(&self, tc: &TestCase) -> U {
        self.draw_flat_mapped(tc, |next_gen, tc| next_gen.do_draw(tc))
    }
}

impl<T, U, G2, F, G1> PrintableGenerator<U> for FlatMapped<T, U, G2, F, G1>
where
    G1: Generator<T>,
    G2: PrintableGenerator<U>,
    F: Fn(T) -> G2 + Send + Sync,
{
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> U {
        self.draw_flat_mapped(tc, |next_gen, tc| tc.draw_and_print(next_gen, printer))
    }
}

/// Result of [`Generator::filter`].
pub struct Filtered<T, F, G> {
    source: G,
    predicate: F,
    _phantom: PhantomData<fn() -> T>,
}

impl<T, F, G> Filtered<T, F, G>
where
    F: Fn(&T) -> bool + Send + Sync,
{
    /// The one filtering loop both draw paths run: each attempt draws
    /// inside a speculative print region, so a rejected attempt discards
    /// whatever the injected `draw` printed — only the accepted value's
    /// representation survives. The silent path passes the no-op printer
    /// and a print-free `draw`.
    fn draw_filtered(
        &self,
        tc: &TestCase,
        printer: &mut PrettyPrinter,
        draw: impl Fn(&G, &TestCase, &mut PrettyPrinter) -> T,
    ) -> T {
        for _ in 0..3 {
            tc.start_span(labels::FILTER);
            let mut speculation = printer.speculate();
            let value = draw(&self.source, tc, speculation.printer());
            if (self.predicate)(&value) {
                speculation.commit();
                tc.stop_span(false);
                return value;
            }
            speculation.abort();
            tc.stop_span(true);
        }
        tc.assume(false);
        unreachable!()
    }
}

impl<T, F, G> Generator<T> for Filtered<T, F, G>
where
    G: Generator<T>,
    F: Fn(&T) -> bool + Send + Sync,
{
    fn do_draw(&self, tc: &TestCase) -> T {
        self.draw_filtered(tc, &mut PrettyPrinter::noop(), |source, tc, _| {
            source.do_draw(tc)
        })
    }
}

impl<T, F, G> PrintableGenerator<T> for Filtered<T, F, G>
where
    G: PrintableGenerator<T>,
    F: Fn(&T) -> bool + Send + Sync,
{
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> T {
        self.draw_filtered(tc, printer, |source, tc, printer| {
            tc.draw_and_print(source, printer)
        })
    }
}

/// A type-erased generator with a lifetime parameter.
pub struct BoxedGenerator<'a, T> {
    pub(super) inner: Arc<dyn Generator<T> + Send + Sync + 'a>,
}

impl<T> Clone for BoxedGenerator<'_, T> {
    fn clone(&self) -> Self {
        BoxedGenerator {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl<T> Generator<T> for BoxedGenerator<'_, T> {
    fn do_draw(&self, tc: &TestCase) -> T {
        self.inner.do_draw(tc)
    }

    fn boxed<'b>(self) -> BoxedGenerator<'b, T>
    where
        Self: Sized + Send + Sync + 'b,
    {
        BoxedGenerator { inner: self.inner }
    }
}

/// A type-erased printable generator with a lifetime parameter, as produced
/// by [`PrintableGenerator::boxed_printable`] and consumed by
/// [`one_of!`](crate::one_of).
pub struct BoxedPrintableGenerator<'a, T> {
    inner: Arc<dyn PrintableGenerator<T> + Send + Sync + 'a>,
}

impl<T> Clone for BoxedPrintableGenerator<'_, T> {
    fn clone(&self) -> Self {
        BoxedPrintableGenerator {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl<T> Generator<T> for BoxedPrintableGenerator<'_, T> {
    fn do_draw(&self, tc: &TestCase) -> T {
        self.inner.do_draw(tc)
    }
}

impl<T> PrintableGenerator<T> for BoxedPrintableGenerator<'_, T> {
    fn do_draw_and_print(&self, tc: &TestCase, printer: &mut PrettyPrinter) -> T {
        self.inner.do_draw_and_print(tc, printer)
    }

    fn boxed_printable<'b>(self) -> BoxedPrintableGenerator<'b, T>
    where
        Self: Sized + Send + Sync + 'b,
    {
        BoxedPrintableGenerator { inner: self.inner }
    }
}