Skip to content

Commit

Permalink
Merge pull request #462 from mirandaconrado/master
Browse files Browse the repository at this point in the history
Detect empty ranges during tree creation
  • Loading branch information
rexmas authored Jun 19, 2024
2 parents 0a53eda + 1426f0f commit ca308b0
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
1 change: 1 addition & 0 deletions proptest/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

- Setting `PROPTEST_MAX_DEFAULT_SIZE_RANGE` now customizes the default `SizeRange`
used by the default strategies for collections (like `Vec`). The default remains 100.
- Empty ranges panic during tree creation instead of during sampling.

### Documentation
- Reference the derive macro in Arbitrary's documentation
Expand Down
77 changes: 77 additions & 0 deletions proptest/src/num.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,13 @@ macro_rules! numeric_api {
type Value = $typ;

fn new_tree(&self, runner: &mut TestRunner) -> NewTree<Self> {
if self.is_empty() {
panic!(
"Invalid use of empty range {}..{}.",
self.start, self.end
);
}

Ok(BinarySearch::new_clamped(
self.start,
$crate::num::sample_uniform::<$sample_typ>(
Expand All @@ -87,6 +94,14 @@ macro_rules! numeric_api {
type Value = $typ;

fn new_tree(&self, runner: &mut TestRunner) -> NewTree<Self> {
if self.is_empty() {
panic!(
"Invalid use of empty range {}..={}.",
self.start(),
self.end()
);
}

Ok(BinarySearch::new_clamped(
*self.start(),
$crate::num::sample_uniform_incl::<$sample_typ>(
Expand Down Expand Up @@ -1390,4 +1405,66 @@ mod test {
}));
}
}

mod panic_on_empty {
macro_rules! panic_on_empty {
($t:tt) => {
mod $t {
use crate::strategy::Strategy;
use crate::test_runner::TestRunner;
use std::panic;
use std::string::String;

const ZERO: $t = 0 as $t;
const ONE: $t = 1 as $t;

#[test]
fn range() {
assert_eq!(
panic::catch_unwind(|| {
let mut runner = TestRunner::deterministic();
let _ = (ZERO..ZERO).new_tree(&mut runner);
})
.err()
.and_then(|a| a
.downcast_ref::<String>()
.map(|s| {
s == "Invalid use of empty range 0..0."
})),
Some(true)
);
}

#[test]
fn range_inclusive() {
assert_eq!(
panic::catch_unwind(|| {
let mut runner = TestRunner::deterministic();
let _ = (ONE..=ZERO).new_tree(&mut runner);
})
.err()
.and_then(|a| a
.downcast_ref::<String>()
.map(|s| {
s == "Invalid use of empty range 1..=0."
})),
Some(true)
);
}
}
};
}
panic_on_empty!(u8);
panic_on_empty!(i8);
panic_on_empty!(u16);
panic_on_empty!(i16);
panic_on_empty!(u32);
panic_on_empty!(i32);
panic_on_empty!(u64);
panic_on_empty!(i64);
panic_on_empty!(usize);
panic_on_empty!(isize);
panic_on_empty!(f32);
panic_on_empty!(f64);
}
}

0 comments on commit ca308b0

Please sign in to comment.