monkey_test 0.9.2

A property based testing (PBT) tool like QuickCheck, ScalaCheck and similar libraries, for the Rust programming language.
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
//! Module with generators for generic floating point values.
//! For non-generic types `f64` and `f32`, see modules [crate::gens::f64]
//! and [crate::gens::f32] instead, which are specializations of this module.

use super::float_parts::FloatParts;
use crate::gens;
use crate::BoxGen;
use crate::MapWithGen;
use num_traits::Float;
use rand::distr::uniform::SampleUniform;
use rand::Rng;
use rand::SeedableRng;
use std::fmt::Debug;
use std::ops::Bound;
use std::ops::RangeBounds;

/// Generator that return any floating point value, including any
/// finite number, NaN, Inf and -Inf.
pub fn any<F>() -> BoxGen<F>
where
    F: Float + FloatParts + SampleUniform + 'static,
{
    let nans = gens::fixed::constant(F::nan());
    gens::mix_with_ratio(&[(98, number()), (2, nans)])
}

/// Generator that only return finite numbers, `-Inf` and
/// `Inf`. In other words any float value besides `NaN`.
pub fn number<F>() -> BoxGen<F>
where
    F: Float + FloatParts + SampleUniform + 'static,
{
    let infs = gens::pick_evenly(&[F::neg_infinity(), F::infinity()]);
    gens::mix_with_ratio(&[(98, finite()), (2, infs)])
}

/// Generator that only return numbers between 0 and `+Inf`.
pub fn positive<F>() -> BoxGen<F>
where
    F: Float + FloatParts + SampleUniform + 'static,
{
    let infs = gens::fixed::constant(F::infinity());
    let finites = ranged(F::zero()..=F::max_value());
    gens::mix_with_ratio(&[(98, finites), (2, infs)])
}

/// Generator that only return numbers between `-Inf` and -0.
pub fn negative<F>() -> BoxGen<F>
where
    F: Float + FloatParts + SampleUniform + 'static,
{
    let infs = gens::fixed::constant(F::neg_infinity());
    let finites = ranged(F::min_value()..=F::neg_zero());
    gens::mix_with_ratio(&[(98, finites), (2, infs)])
}

/// Generator that only return finite numbers between minimum
/// and maximum finite number.
pub fn finite<F>() -> BoxGen<F>
where
    F: Float + FloatParts + SampleUniform + 'static,
{
    ranged(F::min_value()..=F::max_value())
}

/// Generator that only return finite numbers in the range from 0
/// (inclusive) to 1 (exclusive).
pub fn zero_to_one<F>() -> BoxGen<F>
where
    F: Float + FloatParts + SampleUniform + 'static,
{
    ranged(F::zero()..F::one())
}

/// Generator that only return finite numbers in the given range.
pub fn ranged<F, B>(bound: B) -> BoxGen<F>
where
    F: Float + FloatParts + SampleUniform + 'static,
    B: RangeBounds<F>,
{
    let start: F = from_twos_complement_bits(start(&bound));
    let end: F = from_twos_complement_bits(end(&bound));

    check_bounds_are_finite(start, end);

    let (start, end) = if start > end {
        (end, start)
    } else {
        (start, end)
    };

    let all_special_values = [
        F::zero(),
        F::neg_zero(),
        F::one(),
        F::one().neg(),
        F::min_value(),
        F::max_value(),
        F::min_positive_value(),
        F::min_positive_value().neg(),
        start,
        end,
    ];

    let relevant_special_values = all_special_values
        .iter()
        .filter(|v| {
            // special handling if one f bound extremes happen to be zero. We
            // want to distinguish between -0 and +0.
            let value_has_sign_within_range = v.is_sign_negative()
                && start.is_sign_negative()
                || v.is_sign_positive() && end.is_sign_positive();

            let is_in_range = start <= **v && **v <= end;

            is_in_range && value_has_sign_within_range
        })
        .cloned()
        .collect::<Vec<_>>();

    let special_values = gens::pick_evenly(&relevant_special_values);

    gens::mix_with_ratio(&[
        (90, completely_random_range(bound)),
        (10, special_values),
    ])
}

/// Float generator with completely random distribution. This function has a
/// long name, since `ranged` should be preferred.
pub fn completely_random_range<F, B>(bound: B) -> BoxGen<F>
where
    F: Float + FloatParts + SampleUniform + 'static,
    B: RangeBounds<F>,
{
    let min = start(&bound);
    let max = end(&bound);

    check_bounds_are_finite::<F>(
        from_twos_complement_bits(min),
        from_twos_complement_bits(max),
    );

    let (min, max) = if min > max { (max, min) } else { (min, max) };

    // Generate two's complement bits signed integer representation of finite
    // floats
    gens::from_fn(move |seed, _size| {
        let mut x = rand_chacha::ChaCha8Rng::seed_from_u64(seed);
        std::iter::from_fn(move || Some(x.random_range(min..=max)))
    })
    // Map to actual floats from two's complement bits
    .map(
        |i| from_twos_complement_bits(i),
        |f| to_twos_complement_bits(f),
    )
    .with_shrinker(crate::shrinks::float())
}

fn check_bounds_are_finite<F>(start: F, end: F)
where
    F: Float + Debug + 'static,
{
    assert!(
        start.is_finite(),
        "Given range can not have non-finite value {start:?} as range start"
    );
    assert!(
        end.is_finite(),
        "Given range can not have non-finite value {end:?} as range end"
    );
}

/// Convert floating point to signed bit representation
fn to_twos_complement_bits<F>(f: F) -> i64
where
    F: Float + FloatParts,
{
    let sign_is_negative = f.is_sign_negative();
    let exponent = f.exponent() as i64;
    let fraction = f.fraction() as i64;

    let unsigned_bits = (exponent << F::exponent_bit_position()) | fraction;

    if sign_is_negative {
        // special case for -0.0, which can not be represented by negation only,
        // hence also subtracting one.
        -unsigned_bits - 1
    } else {
        unsigned_bits
    }
}

fn from_twos_complement_bits<F>(i: i64) -> F
where
    F: Float + FloatParts,
{
    let sign_is_negative = i < 0;
    let unsigned_bits = if sign_is_negative { -i - 1 } else { i };

    let fraction_mask = (1 << F::exponent_bit_position()) - 1;
    let fraction = (unsigned_bits & fraction_mask) as u64;
    let exponent = (unsigned_bits >> F::exponent_bit_position()) as u16;

    F::from_bits(F::compose(sign_is_negative, exponent, fraction))
}

fn start<F, B>(bounds: &B) -> i64
where
    F: Float + FloatParts + Copy,
    B: RangeBounds<F>,
{
    match bounds.start_bound() {
        Bound::Included(x) => to_twos_complement_bits(*x),
        Bound::Excluded(x) => to_twos_complement_bits(*x) + 1,
        Bound::Unbounded => to_twos_complement_bits(F::min_value()),
    }
}

fn end<F, B>(bounds: &B) -> i64
where
    F: Float + FloatParts + Copy,
    B: RangeBounds<F>,
{
    match bounds.end_bound() {
        Bound::Included(x) => to_twos_complement_bits(*x),
        Bound::Excluded(x) => to_twos_complement_bits(*x) - 1,
        Bound::Unbounded => to_twos_complement_bits(F::max_value()),
    }
}

#[cfg(test)]
mod test {
    //! In many of the tests, we only test f32, not f64, since expecting the
    //! behaviour to be type agnostic.

    use super::from_twos_complement_bits;
    use super::to_twos_complement_bits;
    use crate::gens;
    use crate::monkey_test;
    use crate::testing::assert_generator_can_shrink;
    use crate::BoxGen;
    use std::ops::RangeBounds;

    #[test]
    fn convert_to_and_from_finite_f64() {
        // For more info on the composition of double precision floats, see
        // https://en.wikipedia.org/wiki/Double-precision_floating-point_format
        let exponent_max: i64 = 0x7fe; // 11 bits
        let fraction_max: i64 = 0xF_FFFF_FFFF_FFFF; // 52 bits
        let max = (exponent_max << 52) | fraction_max;
        let min = -max;

        monkey_test()
            .with_generator(gens::i64::ranged(min..=max))
            .assert_true(|i| {
                let f: f64 = from_twos_complement_bits(i);
                let j = to_twos_complement_bits(f);

                i == j
            });
    }

    #[test]
    fn convert_to_and_from_finite_f32() {
        // For more info on the composition of single precision floats, see
        // https://en.wikipedia.org/wiki/Single-precision_floating-point_format
        let exponent_max: i64 = 0xfe; // 8 bits
        let fraction_max: i64 = 0x7f_ffff; // 23 bits
        let max = (exponent_max << 23) | fraction_max;
        let min = -max;

        monkey_test()
            .with_generator(gens::i64::ranged(min..=max))
            .assert_true(|i| {
                let f: f32 = from_twos_complement_bits(i);
                let j = to_twos_complement_bits(f);

                i == j
            });
    }

    #[test]
    fn sign_is_kept_on_zero_in_conversion() {
        let original = -0.0;
        let bits = to_twos_complement_bits(original);

        let copy: f64 = from_twos_complement_bits(bits);
        assert!(bits < 0, "negative sign is kept in bits representation");
        assert!(
            copy.is_sign_negative(),
            "negative sign is kept in roundtrip float"
        );
        assert!(
            copy == 0.0,
            "value 0 is kept in roundtrip float, got {copy}"
        );
    }

    #[test]
    fn verify_generator_any() {
        let generator = gens::f32::any();

        assert_has_values(
            generator,
            &[
                f32::NAN,
                f32::MAX,
                f32::MIN,
                f32::INFINITY,
                f32::NEG_INFINITY,
                0.0,
                -0.0,
                1.0,
                -1.0,
            ],
        );
    }

    #[test]
    fn verify_generator_number() {
        let generator = gens::f32::number();
        assert_all_values_are_in_range(
            generator.clone(),
            f32::NEG_INFINITY..=f32::INFINITY,
        );
        assert_has_values(generator, &[0.0]);
    }

    #[test]
    fn verify_generator_positive() {
        let generator = gens::f32::positive();
        assert_all_values_are_in_range(generator.clone(), 0.0..=f32::INFINITY);
        assert_does_not_have_value(generator.clone(), -0.0);
        assert_has_values(generator, &[0.0, 1.0, f32::MAX, f32::INFINITY]);
    }

    #[test]
    fn verify_generator_negative() {
        let generator = gens::f32::negative();
        assert_all_values_are_in_range(
            generator.clone(),
            f32::NEG_INFINITY..=-0.0,
        );
        assert_does_not_have_value(generator.clone(), 0.0);
        assert_has_values(
            generator,
            &[-0.0, -1.0, f32::MIN, f32::NEG_INFINITY],
        );
    }

    #[test]
    fn verify_generator_finite() {
        let generator = gens::f32::finite();
        assert_all_values_are_in_range(generator.clone(), f32::MIN..=f32::MAX);
        assert_has_values(
            generator,
            &[-0.0, -1.0, 0.0, 1.0, f32::MIN, f32::MAX],
        );
    }

    #[test]
    fn verify_generator_ranged() {
        // negative range
        let generator = gens::f32::ranged(-555.0..=-72.0);
        assert_all_values_are_in_range(generator.clone(), -555.0..=-72.0);
        assert_has_values(generator, &[-555.0, -72.0]);

        // positive range
        let generator = gens::f32::ranged(72.0..=555.0);
        assert_all_values_are_in_range(generator.clone(), 72.0..=555.0);
        assert_has_values(generator, &[72.0, 555.0]);

        // range inverted. lagest value first in range
        let generator = gens::f32::ranged(555.0..=72.0);
        assert_all_values_are_in_range(generator.clone(), 72.0..=555.0);
        assert_has_values(generator, &[72.0, 555.0]);

        // sign-straddling range
        let generator = gens::f32::ranged(-555.0..=72.0);
        assert_all_values_are_in_range(generator.clone(), -555.0..=72.0);
        assert_has_values(generator, &[-555.0, 72.0, -0.0, 0.0, -1.0, 1.0]);
    }

    #[test]
    fn verify_generator_zero_to_one() {
        let generator = gens::f32::zero_to_one();
        assert_all_values_are_in_range(generator.clone(), 0.0..1.0);
        assert_has_values(generator.clone(), &[0.0]);
        assert_does_not_have_value(generator, -0.0);
    }

    #[test]
    #[should_panic]
    fn let_ranged_panic_on_nan() {
        gens::f32::ranged(f32::NAN..10.0);
    }

    #[test]
    #[should_panic]
    fn let_ranged_panic_on_neg_inf() {
        gens::f32::ranged(f32::NEG_INFINITY..10.0);
    }

    #[test]
    #[should_panic]
    fn let_ranged_panic_on_pos_inf() {
        gens::f32::ranged(10.0..=f32::INFINITY);
    }

    #[test]
    #[should_panic]
    fn let_completely_random_panic_on_nan() {
        gens::f32::completely_random(f32::NAN..10.0);
    }

    #[test]
    #[should_panic]
    fn let_completely_random_panic_on_neg_inf() {
        gens::f32::completely_random(f32::NEG_INFINITY..10.0);
    }

    #[test]
    #[should_panic]
    fn let_completely_random_panic_on_pos_inf() {
        gens::f32::completely_random(10.0..=f32::INFINITY);
    }

    #[test]
    fn should_have_shrinker() {
        assert_generator_can_shrink(gens::f64::any(), std::f64::consts::PI)
    }

    fn assert_all_values_are_in_range<B>(generator: BoxGen<f32>, range: B)
    where
        B: RangeBounds<f32> + std::fmt::Debug,
    {
        generator
            .examples(crate::global_seed(), crate::global_example_size())
            .take(1000)
            .for_each(|v| {
                assert!(
                    range.contains(&v),
                    "Range {range:?} should contain {v}"
                )
            });
    }

    fn assert_has_values(generator: BoxGen<f32>, values: &[f32]) {
        values.iter().for_each(|v| {
            let examples_count = 1000;
            let has_value =
                generator
                .examples(crate::global_seed(), crate::global_example_size())
                .take(examples_count)
                .any(|e| {
                  float_equals(e, *v)
                });

            assert!(
                has_value,
                "Generator did not have {v} in the first {examples_count} examples."
            );
        });
    }

    fn assert_does_not_have_value(generator: BoxGen<f32>, value: f32) {
        let examples_count = 500;
        generator
            .examples(crate::global_seed(), crate::global_example_size())
            .take(examples_count)
            .for_each(|e| {
                let r = float_equals(e, value);

                println!("cmp: {e} == {value}: {r}");

                assert!(
                    !r,
                    "Search for {value} in generator found {e} in \
                    the first {examples_count} examples."
                );
            });
    }

    fn float_equals(a: f32, b: f32) -> bool {
        // NaN never equals anything else, not even other NaN
        let both_are_nan = a.is_nan() && b.is_nan();
        // In these generators +0.0 and -0.0 are not regarded to be equal, even
        // though for normal floats they are regarded to be equal.
        let signums_are_the_same = a.signum() == b.signum();
        // Exact comparison is used on purpose
        both_are_nan || (signums_are_the_same && a == b)
    }
}