hegeltest 0.14.21

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
// internal helper code
#![allow(dead_code)]

use std::panic::{UnwindSafe, catch_unwind};
use std::sync::{Arc, Mutex};

use hegel::generators::Generator;
use hegel::{HealthCheck, Hegel, Phase, Settings};
use regex::Regex;
use std::fmt::Debug;

// some of our tests differ in behavior in our nightly rust job.
pub fn is_nightly() -> bool {
    std::env::var("HEGEL_RUNNING_TESTS_WITH_RUST_NIGHTLY").is_ok_and(|v| v == "1")
}

// some of our tests don't work on NixOS
pub fn is_nixos() -> bool {
    std::fs::exists("/etc/NIXOS").unwrap_or_default()
}

pub fn assert_matches_regex(text: &str, pattern: &str) {
    let re = Regex::new(pattern).unwrap_or_else(|e| panic!("invalid regex {pattern:?}: {e}"));
    assert!(
        re.is_match(text),
        "Expected to match pattern: {pattern}\nActual:\n{text}"
    );
}

/// Run `f` and assert it panics with a message matching the `pattern` regex.
pub fn expect_panic<F: FnOnce() + UnwindSafe>(f: F, pattern: &str) {
    let err = catch_unwind(f).expect_err("expected panic, but closure returned normally");
    let msg = err
        .downcast_ref::<&str>()
        .map(|s| s.to_string())
        .or_else(|| err.downcast_ref::<String>().cloned())
        .unwrap_or_default();
    assert_matches_regex(&msg, pattern);
}

#[allow(dead_code)]
pub fn check_can_generate_examples<T, G>(generator: G)
where
    G: Generator<T> + 'static,
    T: Debug,
{
    AssertSimpleProperty::new(generator, |_| true).run();
}

pub fn assert_all_examples<T, G, P>(generator: G, predicate: P)
where
    G: Generator<T> + 'static,
    P: Fn(&T) -> bool + 'static,
    T: Debug,
{
    AssertAllExamples::new(generator, predicate).run();
}

#[allow(dead_code)]
pub struct AssertAllExamples<T, G, P>
where
    G: Generator<T> + 'static,
    P: Fn(&T) -> bool + 'static,
    T: Debug,
{
    generator: G,
    predicate: P,
    test_cases: u64,
    _marker: std::marker::PhantomData<T>,
}

impl<T, G, P> AssertAllExamples<T, G, P>
where
    G: Generator<T> + 'static,
    P: Fn(&T) -> bool + 'static,
    T: Debug,
{
    pub fn new(generator: G, predicate: P) -> Self {
        Self {
            generator,
            predicate,
            test_cases: 100,
            _marker: std::marker::PhantomData,
        }
    }

    #[allow(dead_code)]
    pub fn test_cases(mut self, n: u64) -> Self {
        self.test_cases = n;
        self
    }

    pub fn run(self) {
        self.run_with_health_checks_suppressed(&[]);
    }

    pub fn run_with_health_checks_suppressed(self, checks: &[HealthCheck]) {
        let settings = Settings::new()
            .test_cases(self.test_cases)
            .database(None)
            .suppress_health_check(checks.iter().cloned());
        Hegel::new(move |tc| {
            let value = tc.draw(&self.generator);
            assert!(
                (self.predicate)(&value),
                "Found value that does not match predicate"
            );
        })
        .settings(settings)
        .run();
    }
}

#[allow(dead_code)]
pub fn assert_simple_property<T, G, P>(generator: G, predicate: P)
where
    G: Generator<T> + 'static,
    P: Fn(&T) -> bool + 'static,
    T: Debug,
{
    AssertSimpleProperty::new(generator, predicate).run();
}

#[allow(dead_code)]
pub struct AssertSimpleProperty<T, G, P>
where
    G: Generator<T> + 'static,
    P: Fn(&T) -> bool + 'static,
    T: Debug,
{
    inner: AssertAllExamples<T, G, P>,
}

impl<T, G, P> AssertSimpleProperty<T, G, P>
where
    G: Generator<T> + 'static,
    P: Fn(&T) -> bool + 'static,
    T: Debug,
{
    pub fn new(generator: G, predicate: P) -> Self {
        Self {
            inner: AssertAllExamples::new(generator, predicate).test_cases(15),
        }
    }

    #[allow(dead_code)]
    pub fn test_cases(mut self, n: u64) -> Self {
        self.inner = self.inner.test_cases(n);
        self
    }

    pub fn run(self) {
        // These checks are about "can we generate at all", not speed, and
        // instrumented coverage binaries routinely trip the TooSlow check.
        self.inner
            .run_with_health_checks_suppressed(&[HealthCheck::TooSlow]);
    }
}

pub fn find_any<T, G, P>(generator: G, condition: P) -> T
where
    G: Generator<T> + 'static,
    P: Fn(&T) -> bool + 'static,
    T: Send + Debug + 'static,
{
    FindAny::new(generator, condition).run()
}

#[allow(dead_code)]
pub struct FindAny<T, G, P>
where
    G: Generator<T> + 'static,
    P: Fn(&T) -> bool + 'static,
    T: Send + Debug + 'static,
{
    generator: G,
    condition: P,
    max_attempts: u64,
    suppress_health_checks: Vec<HealthCheck>,
    seed: Option<u64>,
    _marker: std::marker::PhantomData<T>,
}

impl<T, G, P> FindAny<T, G, P>
where
    G: Generator<T> + 'static,
    P: Fn(&T) -> bool + 'static,
    T: Send + Debug + 'static,
{
    pub fn new(generator: G, condition: P) -> Self {
        Self {
            generator,
            condition,
            max_attempts: 5000,
            suppress_health_checks: Vec::new(),
            seed: None,
            _marker: std::marker::PhantomData,
        }
    }

    #[allow(dead_code)]
    pub fn max_attempts(mut self, n: u64) -> Self {
        self.max_attempts = n;
        self
    }

    #[allow(dead_code)]
    pub fn suppress_health_check(mut self, hc: HealthCheck) -> Self {
        self.suppress_health_checks.push(hc);
        self
    }

    /// Pin the RNG seed so probabilistic searches don't flake under
    /// coverage / random scheduling. Use this when the condition is
    /// rare enough that even ~10k attempts on a random seed has a
    /// non-negligible miss rate (NaN sign-bit + mantissa parity, etc.).
    #[allow(dead_code)]
    pub fn seed(mut self, seed: u64) -> Self {
        self.seed = Some(seed);
        self
    }

    pub fn run(self) -> T {
        let found: Arc<Mutex<Option<T>>> = Arc::new(Mutex::new(None));
        let found_clone = Arc::clone(&found);
        let max_attempts = self.max_attempts;
        let suppress_health_checks = self.suppress_health_checks;
        let pinned_seed = self.seed;

        let hegel_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            Hegel::new(move |tc| {
                let value = tc.draw(&self.generator);
                if (self.condition)(&value) {
                    *found_clone.lock().unwrap() = Some(value);
                    panic!("HEGEL_FOUND"); // Early exit marker
                }
            })
            .settings(
                Settings::new()
                    .test_cases(max_attempts)
                    .database(None)
                    .phases([Phase::Reuse, Phase::Generate])
                    .seed(pinned_seed)
                    .suppress_health_check(suppress_health_checks),
            )
            .run();
        }));

        if let Err(e) = hegel_result {
            // If found is None, this panic is not from HEGEL_FOUND — re-propagate
            // the real error (e.g. server crash) instead of swallowing it.
            if found.lock().unwrap().is_none() {
                std::panic::resume_unwind(e);
            }
        }

        let result = found.lock().unwrap().take();
        result.unwrap_or_else(|| {
            panic!(
                "Could not find any examples satisfying the condition after {} attempts",
                max_attempts
            )
        })
    }
}

/// Find the minimal example from a generator that satisfies the given condition.
///
/// This runs a property test where any value satisfying `condition` causes a failure,
/// then lets Hegel shrink the failing case to find the minimal counterexample.
/// Analogous to Hypothesis's `minimal()` test helper.
#[allow(dead_code)]
pub fn minimal<T, G, P>(generator: G, condition: P) -> T
where
    G: Generator<T> + 'static,
    P: Fn(&T) -> bool + 'static,
    T: Send + Debug + 'static,
{
    Minimal::new(generator, condition).run()
}

#[allow(dead_code)]
pub struct Minimal<T, G, P>
where
    G: Generator<T> + 'static,
    P: Fn(&T) -> bool + 'static,
    T: Send + Debug + 'static,
{
    generator: G,
    condition: P,
    test_cases: u64,
    _marker: std::marker::PhantomData<T>,
}

impl<T, G, P> Minimal<T, G, P>
where
    G: Generator<T> + 'static,
    P: Fn(&T) -> bool + 'static,
    T: Send + Debug + 'static,
{
    pub fn new(generator: G, condition: P) -> Self {
        Self {
            generator,
            condition,
            test_cases: 500,
            _marker: std::marker::PhantomData,
        }
    }

    #[allow(dead_code)]
    pub fn test_cases(mut self, n: u64) -> Self {
        self.test_cases = n;
        self
    }

    pub fn run(self) -> T {
        let found: Arc<Mutex<Option<T>>> = Arc::new(Mutex::new(None));
        let found_clone = Arc::clone(&found);
        let test_cases = self.test_cases;

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            Hegel::new(move |tc| {
                let value = tc.draw(&self.generator);
                if (self.condition)(&value) {
                    *found_clone.lock().unwrap() = Some(value);
                    panic!("HEGEL_MINIMAL_FOUND");
                }
            })
            .settings(
                Settings::new()
                    .test_cases(test_cases)
                    .database(None)
                    .derandomize(true),
            )
            .run();
        }));

        if let Err(payload) = result {
            let msg = payload
                .downcast_ref::<&str>()
                .copied()
                .or_else(|| payload.downcast_ref::<String>().map(|s| s.as_str()));
            let is_expected = msg.is_some_and(|s| s == "Property test failed: HEGEL_MINIMAL_FOUND");
            if !is_expected {
                std::panic::resume_unwind(payload);
            }
        }

        let result = found.lock().unwrap().take();
        result.unwrap_or_else(|| {
            panic!(
                "Could not find any examples satisfying the condition after {} attempts",
                test_cases
            )
        })
    }
}

#[allow(dead_code)]
pub fn assert_no_examples<T, G, P>(generator: G, condition: P)
where
    G: Generator<T> + 'static,
    P: Fn(&T) -> bool + 'static,
    T: Debug,
{
    AssertNoExamples::new(generator, condition).run();
}

#[allow(dead_code)]
pub struct AssertNoExamples<T, G, P>
where
    G: Generator<T> + 'static,
    P: Fn(&T) -> bool + 'static,
    T: Debug,
{
    generator: G,
    condition: P,
    test_cases: u64,
    _marker: std::marker::PhantomData<T>,
}

impl<T, G, P> AssertNoExamples<T, G, P>
where
    G: Generator<T> + 'static,
    P: Fn(&T) -> bool + 'static,
    T: Debug,
{
    pub fn new(generator: G, condition: P) -> Self {
        Self {
            generator,
            condition,
            test_cases: 100,
            _marker: std::marker::PhantomData,
        }
    }

    #[allow(dead_code)]
    pub fn test_cases(mut self, n: u64) -> Self {
        self.test_cases = n;
        self
    }

    pub fn run(self) {
        // Matches Python's `assert_no_examples`, which catches Unsatisfiable:
        // if the strategy only produces invalid inputs, the assertion holds
        // vacuously. Suppress FilterTooMuch so the run completes instead of
        // panicking on excess rejections.
        let condition = self.condition;
        Hegel::new(move |tc| {
            let value = tc.draw(&self.generator);
            assert!(
                !condition(&value),
                "Found value that does not match predicate"
            );
        })
        .settings(
            Settings::new()
                .test_cases(self.test_cases)
                .database(None)
                .suppress_health_check([HealthCheck::FilterTooMuch]),
        )
        .run();
    }
}