#arbitrary #testing

arbitrary

The trait for generating structured data from unstructured data

21 releases (4 stable)

1.0.3 Nov 15, 2021
1.0.1 May 20, 2021
1.0.0 Feb 24, 2021
1.0.0-rc1 Nov 26, 2020
0.1.0 May 8, 2017

#3 in Testing

Download history 21268/week @ 2021-08-15 23829/week @ 2021-08-22 22362/week @ 2021-08-29 20173/week @ 2021-09-05 28149/week @ 2021-09-12 26697/week @ 2021-09-19 25882/week @ 2021-09-26 26884/week @ 2021-10-03 34511/week @ 2021-10-10 33048/week @ 2021-10-17 30021/week @ 2021-10-24 34301/week @ 2021-10-31 34571/week @ 2021-11-07 34528/week @ 2021-11-14 28784/week @ 2021-11-21 31604/week @ 2021-11-28

132,117 downloads per month
Used in 164 crates (98 directly)

MIT/Apache

71KB
1.5K SLoC

Arbitrary

The trait for generating structured data from arbitrary, unstructured input.

GitHub Actions Status

About

The Arbitrary crate lets you construct arbitrary instances of a type.

This crate is primarily intended to be combined with a fuzzer like libFuzzer and cargo-fuzz or AFL, and to help you turn the raw, untyped byte buffers that they produce into well-typed, valid, structured values. This allows you to combine structure-aware test case generation with coverage-guided, mutation-based fuzzers.

Documentation

Read the API documentation on docs.rs!

Example

Say you're writing a color conversion library, and you have an Rgb struct to represent RGB colors. You might want to implement Arbitrary for Rgb so that you could take arbitrary Rgb instances in a test function that asserts some property (for example, asserting that RGB converted to HSL and converted back to RGB always ends up exactly where we started).

Automatically Deriving Arbitrary

Automatically deriving the Arbitrary trait is the recommended way to implement Arbitrary for your types.

Automatically deriving Arbitrary requires you to enable the "derive" cargo feature:

# Cargo.toml

[dependencies]
arbitrary = { version = "1", features = ["derive"] }

And then you can simply add #[derive(Arbitrary)] annotations to your types:

// rgb.rs

use arbitrary::Arbitrary;

#[derive(Arbitrary)]
pub struct Rgb {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

Implementing Arbitrary By Hand

Alternatively, you can write an Arbitrary implementation by hand:

// rgb.rs

use arbitrary::{Arbitrary, Result, Unstructured};

#[derive(Copy, Clone, Debug)]
pub struct Rgb {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

impl<'a> Arbitrary<'a> for Rgb {
    fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
        let r = u8::arbitrary(u)?;
        let g = u8::arbitrary(u)?;
        let b = u8::arbitrary(u)?;
        Ok(Rgb { r, g, b })
    }
}

License

Licensed under dual MIT or Apache-2.0 at your choice.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this project by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~110KB

ba