prop_check_rs/prop.rs
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
use crate::gen::{Gen, SGen};
use crate::rng::RNG;
use anyhow::*;
use itertools::Unfold;
use std::cell::RefCell;
use std::fmt::Debug;
use std::rc::Rc;
pub type MaxSize = u32;
pub type TestCases = u32;
pub type FailedCase = String;
pub type SuccessCount = u32;
/// The trait to return the failure of the property.<br/>
/// プロパティの失敗を返すためのトレイト.
pub trait IsFalsified {
fn is_falsified(&self) -> bool;
fn non_falsified(&self) -> bool {
!self.is_falsified()
}
}
/// Represents the result of the property.<br/>
/// プロパティの結果を表す.
#[derive(Clone)]
pub enum PropResult {
/// The property is passed.
Passed {
/// The number of test cases.
test_cases: TestCases,
},
/// The property is falsified.
Falsified {
/// The failure of the property.
failure: FailedCase,
/// The number of successes.
successes: SuccessCount,
},
Proved,
}
impl PropResult {
/// The `map` method can change the number of test cases.<br/>
/// mapメソッドはテストケースの数を変更することができる.
///
/// # Arguments
/// - `f` - The function to change the number of test cases.
///
/// # Returns
/// - `PropResult` - The new PropResult.
pub fn map<F>(self, f: F) -> PropResult
where
F: FnOnce(u32) -> u32, {
match self {
PropResult::Passed { test_cases } => PropResult::Passed {
test_cases: f(test_cases),
},
PropResult::Proved => PropResult::Proved,
other => other,
}
}
/// The `flat_map` method can change the number of test cases.<br/>
/// flat_mapメソッドはテストケースの数を変更することができる.
///
/// # Arguments
/// - `f` - The function to change the number of test cases.
///
/// # Returns
/// - `PropResult` - The new PropResult.
pub fn flat_map<F>(self, f: F) -> PropResult
where
F: FnOnce(Option<u32>) -> PropResult, {
match self {
PropResult::Passed { test_cases } => f(Some(test_cases)),
PropResult::Proved => f(None),
other => other,
}
}
/// The `to_result` method can convert the PropResult to Result.<br/>
/// to_resultメソッドはPropResultをResultに変換することができる.
///
/// # Returns
/// - `Result<String>` - The result of the PropResult.
pub fn to_result(self) -> Result<String> {
match self {
p @ PropResult::Passed { .. } => Ok(p.message()),
p @ PropResult::Proved => Ok(p.message()),
f @ PropResult::Falsified { .. } => Err(anyhow!(f.message())),
}
}
/// The `to_result_unit` method can convert the PropResult to Result with the message.<br/>
/// to_result_unitメソッドはPropResultをResultに変換することができる.
///
/// # Returns
/// - `Result<()>` - The result without the message of the PropResult
pub fn to_result_unit(self) -> Result<()> {
self
.to_result()
.map(|msg| {
log::info!("{}", msg);
()
})
.map_err(|err| {
log::error!("{}", err);
err
})
}
/// The `message` method can return the message of the PropResult.<br/>
/// messageメソッドはPropResultのメッセージを返すことができる。
///
/// # Returns
/// - `String` - The message of the PropResult.
pub fn message(&self) -> String {
match self {
PropResult::Passed { test_cases } => format!("OK, passed {} tests", test_cases),
PropResult::Proved => "OK, proved property".to_string(),
PropResult::Falsified { failure, successes } => {
format!("Falsified after {} passed tests: {}", failure, successes)
}
}
}
}
impl IsFalsified for PropResult {
fn is_falsified(&self) -> bool {
match self {
PropResult::Passed { .. } => false,
PropResult::Falsified { .. } => true,
PropResult::Proved => false,
}
}
}
fn random_stream<A>(g: Gen<A>, rng: RNG) -> Unfold<RNG, Box<dyn FnMut(&mut RNG) -> Option<A>>>
where
A: Clone + 'static, {
itertools::unfold(
rng,
Box::new(move |rng| {
let (a, s) = g.clone().run(rng.clone());
*rng = s;
Some(a)
}),
)
}
/// Returns a Prop that executes a function to evaluate properties using SGen.<br/>
/// SGenを利用してプロパティを評価するため関数を実行するPropを返す。
///
/// # Arguments
/// - `sgen` - The SGen.
/// - `test` - The function to evaluate the properties.
///
/// # Returns
/// - `Prop` - The new Prop.
pub fn for_all_sgen<A, F, FF>(sgen: SGen<A>, mut test: FF) -> Prop
where
F: FnMut(A) -> bool + 'static,
FF: FnMut() -> F + 'static,
A: Clone + Debug + 'static, {
match sgen {
SGen::Unsized(g) => for_all_gen(g, test()),
s @ SGen::Sized(..) => for_all_gen_for_size(move |i| s.run(Some(i)), test),
}
}
/// Returns a Prop that executes a function to evaluate properties using Gen with size.<br/>
/// サイズを与えたGenを利用してプロパティを評価するため関数を実行するPropを返す。
///
/// # Arguments
/// - `gf` - The function to create a Gen with size.
/// - `f` - The function to evaluate the properties.
///
/// # Returns
/// - `Prop` - The new Prop.
pub fn for_all_gen_for_size<A, GF, F, FF>(gf: GF, mut test: FF) -> Prop
where
GF: Fn(u32) -> Gen<A> + 'static,
F: FnMut(A) -> bool + 'static,
FF: FnMut() -> F + 'static,
A: Clone + Debug + 'static, {
Prop {
run_f: Rc::new(RefCell::new(move |max, n, rng| {
let cases_per_size = n / max;
let props = itertools::iterate(0, |i| *i + 1)
.map(|i| for_all_gen(gf(i), test()))
.take(max as usize)
.collect::<Vec<_>>();
let p = props
.into_iter()
.map(|p| Prop::new(move |max, _, rng| p.run(max, cases_per_size, rng)))
.reduce(|l, r| l.and(r))
.unwrap();
p.run(max, n, rng).flat_map(|_| PropResult::Proved)
})),
}
}
/// Returns a Prop that executes a function to evaluate properties using Gen.<br/>
/// Genを利用してプロパティを評価するため関数を実行するPropを返す
///
/// # Arguments
/// - `g` - The Gen.
/// - `test` - The function to evaluate the properties.
///
/// # Returns
/// - `Prop` - The new Prop.
pub fn for_all_gen<A, F>(g: Gen<A>, mut test: F) -> Prop
where
F: FnMut(A) -> bool + 'static,
A: Clone + Debug + 'static, {
Prop {
run_f: Rc::new(RefCell::new(move |_, n, rng| {
let success_counter = itertools::iterate(1, |&i| i + 1).into_iter();
random_stream(g.clone(), rng)
.zip(success_counter)
.take(n as usize)
.map(|(test_value, success_count)| {
if test(test_value.clone()) {
PropResult::Passed { test_cases: n }
} else {
PropResult::Falsified {
failure: format!("{:?}", test_value),
successes: success_count,
}
}
})
.find(move |e| e.is_falsified())
.unwrap_or(PropResult::Passed { test_cases: n })
})),
}
}
/// Execute the Prop.
///
/// # Arguments
/// - `max_size` - The maximum size of the generated value.
/// - `test_cases` - The number of test cases.
/// - `rng` - The random number generator.
///
/// # Returns
/// - `Result<String>` - The result of the Prop.
pub fn run_with_prop(p: Prop, max_size: MaxSize, test_cases: TestCases, rng: RNG) -> Result<String> {
p.run(max_size, test_cases, rng).to_result()
}
/// Execute the Prop.
///
/// # Arguments
/// - `max_size` - The maximum size of the generated value.
/// - `test_cases` - The number of test cases.
/// - `rng` - The random number generator.
///
/// # Returns
/// - `Result<()>` - The result of the Prop.
pub fn test_with_prop(p: Prop, max_size: MaxSize, test_cases: TestCases, rng: RNG) -> Result<()> {
p.run(max_size, test_cases, rng).to_result_unit()
}
/// Represents the property.<br/>
/// プロパティを表す。
pub struct Prop {
run_f: Rc<RefCell<dyn FnMut(MaxSize, TestCases, RNG) -> PropResult>>,
}
impl Clone for Prop {
fn clone(&self) -> Self {
Self {
run_f: self.run_f.clone(),
}
}
}
impl Prop {
/// Create a new Prop.
///
/// # Arguments
/// - `f` - The function to evaluate the properties.
///
/// # Returns
/// - `Prop` - The new Prop.
pub fn new<F>(f: F) -> Prop
where
F: Fn(MaxSize, TestCases, RNG) -> PropResult + 'static, {
Prop {
run_f: Rc::new(RefCell::new(f)),
}
}
/// Execute the Prop.
///
/// # Arguments
/// - `max_size` - The maximum size of the generated value.
/// - `test_cases` - The number of test cases.
/// - `rng` - The random number generator.
///
/// # Returns
/// - `PropResult` - The result of the Prop.
pub fn run(&self, max_size: MaxSize, test_cases: TestCases, rng: RNG) -> PropResult {
let mut f = self.run_f.borrow_mut();
f(max_size, test_cases, rng)
}
/// The `tag` method can add a message to the PropResult.
///
/// # Arguments
/// - `msg` - The message.
///
/// # Returns
/// - `Prop` - The tagged Prop.
pub fn tag(self, msg: String) -> Prop {
Prop::new(move |max, n, rng| match self.run(max, n, rng) {
PropResult::Falsified {
failure: e,
successes: c,
} => PropResult::Falsified {
failure: format!("{}\n{}", msg, e),
successes: c,
},
x => x,
})
}
/// The `and` method can combine a other Prop.
/// If the first Prop is passed, the second Prop is executed.
///
/// # Arguments
/// - `other` - The other Prop.
///
/// # Returns
/// - `Prop` - The combined Prop.
pub fn and(self, other: Self) -> Prop {
Self::new(
move |max: MaxSize, n: TestCases, rng: RNG| match self.run(max, n, rng.clone()) {
PropResult::Passed { .. } | PropResult::Proved => other.run(max, n, rng),
x => x,
},
)
}
/// The 'or' method can combine a other Prop.
/// If the first Prop is falsified, the second Prop is executed.
///
/// # Arguments
/// - `other` - The other Prop.
///
/// # Returns
/// - `Prop` - The combined Prop.
pub fn or(self, other: Self) -> Prop {
Self::new(move |max, n, rng: RNG| match self.run(max, n, rng.clone()) {
PropResult::Falsified { failure: msg, .. } => other.clone().tag(msg).run(max, n, rng),
x => x,
})
}
}
#[cfg(test)]
mod tests {
use crate::gen::Gens;
use super::*;
use anyhow::Result;
use std::env;
fn init() {
env::set_var("RUST_LOG", "info");
let _ = env_logger::builder().is_test(true).try_init();
}
fn new_rng() -> RNG {
RNG::new()
}
#[test]
fn test_one_of() -> Result<()> {
init();
let gen = Gens::one_of_values(['a', 'b', 'c', 'x', 'y', 'z']);
let prop = for_all_gen(gen, move |a| {
log::info!("value = {}", a);
true
});
test_with_prop(prop, 1, 100, new_rng())
}
#[test]
fn test_one_of_2() -> Result<()> {
init();
let mut counter = 0;
let gen = Gens::one_of_values(['a', 'b', 'c', 'x', 'y', 'z']);
let prop = for_all_gen_for_size(
move |size| Gens::list_of_n(size as usize, gen.clone()),
move || {
move |a| {
counter += 1;
log::info!("value = {},{:?}", counter, a);
true
}
},
);
test_with_prop(prop, 10, 100, new_rng())
}
}