├── .gitignore ├── .gitattributes ├── Cargo.toml ├── LICENSE-MIT ├── src ├── shrink.rs ├── shrinker.rs ├── checker.rs └── lib.rs ├── .github ├── workflows │ └── ci.yaml ├── CONTRIBUTING.md └── CODE_OF_CONDUCT.md ├── tests └── test.rs ├── README.md └── LICENSE-APACHE /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | tmp/ 3 | Cargo.lock 4 | .DS_Store 5 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "heckcheck" 3 | version = "2.0.1" 4 | license = "MIT OR Apache-2.0" 5 | repository = "https://github.com/yoshuawuyts/heckcheck" 6 | documentation = "https://docs.rs/heckcheck" 7 | description = "A heckin small test case generator" 8 | readme = "README.md" 9 | edition = "2018" 10 | keywords = [] 11 | categories = [] 12 | authors = [ 13 | "Yosh Wuyts " 14 | ] 15 | 16 | [features] 17 | 18 | [dependencies] 19 | arbitrary = "1.0.1" 20 | rand = "0.8.4" 21 | base64 = "0.13.0" 22 | 23 | [dev-dependencies] 24 | arbitrary = { version = "1.0.1", features = ["derive"] } 25 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020 Yoshua Wuyts 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/shrink.rs: -------------------------------------------------------------------------------- 1 | /// Test case shrinking. 2 | pub trait Shrink { 3 | /// Start shrinking the provided data. 4 | fn shrink(source: Vec) -> Self; 5 | 6 | /// Get the next test case. 7 | fn next(&mut self) -> &[u8]; 8 | 9 | /// Report to the shrinker whether the last shrunk case passed or failed. 10 | /// 11 | /// Returns the final shrinkage case if no more cases are left to report. 12 | #[must_use = "The shrunk test case must be handled"] 13 | fn report(&mut self, report: ShrinkReport) -> Option<&[u8]>; 14 | } 15 | 16 | /// The result of a shrinking pass. 17 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] 18 | pub enum ShrinkReport { 19 | /// The last test passed. 20 | Pass, 21 | /// The last test failed. 22 | Fail, 23 | } 24 | 25 | impl ShrinkReport { 26 | /// Returns `true` if the shrink_result is [`Pass`]. 27 | /// 28 | /// [`Pass`]: ShrinkReport::Pass 29 | pub fn is_pass(&self) -> bool { 30 | matches!(self, Self::Pass) 31 | } 32 | 33 | /// Returns `true` if the shrink_result is [`Fail`]. 34 | /// 35 | /// [`Fail`]: ShrinkReport::Fail 36 | pub fn is_fail(&self) -> bool { 37 | matches!(self, Self::Fail) 38 | } 39 | } 40 | 41 | impl From> for ShrinkReport { 42 | fn from(res: std::thread::Result) -> Self { 43 | match res { 44 | Ok(_) => ShrinkReport::Pass, 45 | Err(_) => ShrinkReport::Fail, 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - staging 8 | - trying 9 | 10 | env: 11 | RUSTFLAGS: -Dwarnings 12 | 13 | jobs: 14 | build_and_test: 15 | name: Build and test 16 | runs-on: ${{ matrix.os }} 17 | strategy: 18 | matrix: 19 | os: [ubuntu-latest, windows-latest, macOS-latest] 20 | rust: [stable] 21 | 22 | steps: 23 | - uses: actions/checkout@master 24 | 25 | - name: Install ${{ matrix.rust }} 26 | uses: actions-rs/toolchain@v1 27 | with: 28 | toolchain: ${{ matrix.rust }} 29 | override: true 30 | 31 | - name: check 32 | uses: actions-rs/cargo@v1 33 | with: 34 | command: check 35 | args: --all --bins --examples 36 | 37 | - name: check unstable 38 | uses: actions-rs/cargo@v1 39 | with: 40 | command: check 41 | args: --all --benches --bins --examples --tests 42 | 43 | - name: tests 44 | uses: actions-rs/cargo@v1 45 | with: 46 | command: test 47 | args: --all 48 | 49 | check_fmt_and_docs: 50 | name: Checking fmt and docs 51 | runs-on: ubuntu-latest 52 | steps: 53 | - uses: actions/checkout@master 54 | - uses: actions-rs/toolchain@v1 55 | with: 56 | toolchain: nightly 57 | components: rustfmt, clippy 58 | override: true 59 | 60 | - name: fmt 61 | run: cargo fmt --all -- --check 62 | 63 | - name: Docs 64 | run: cargo doc 65 | -------------------------------------------------------------------------------- /tests/test.rs: -------------------------------------------------------------------------------- 1 | use heckcheck::prelude::*; 2 | 3 | #[test] 4 | fn smoke() { 5 | #[derive(Clone, Debug, Arbitrary, PartialEq)] 6 | pub struct Rgb { 7 | pub r: u8, 8 | pub g: u8, 9 | pub b: u8, 10 | } 11 | 12 | impl Rgb { 13 | pub fn to_hex(&self) -> String { 14 | format!("#{:02X}{:02X}{:02X}", self.r, self.g, self.b) 15 | } 16 | pub fn from_hex(s: String) -> Self { 17 | let s = s.strip_prefix('#').unwrap(); 18 | Rgb { 19 | r: u8::from_str_radix(&s[0..2], 16).unwrap(), 20 | g: u8::from_str_radix(&s[2..4], 16).unwrap(), 21 | b: u8::from_str_radix(&s[4..6], 16).unwrap(), 22 | } 23 | } 24 | } 25 | 26 | heckcheck::check(|rgb: Rgb| { 27 | let hex = rgb.to_hex(); 28 | let res = Rgb::from_hex(hex); 29 | assert_eq!(rgb, res); 30 | Ok(()) 31 | }); 32 | } 33 | 34 | #[test] 35 | #[should_panic] 36 | fn panics_on_bug() { 37 | #[derive(Arbitrary, Debug, PartialEq)] 38 | pub struct Rgb { 39 | pub r: u8, 40 | pub g: u8, 41 | pub b: u8, 42 | } 43 | 44 | impl Rgb { 45 | pub fn to_hex(&self) -> String { 46 | format!("#{:02X}{:2X}{:02X}", self.r, self.g, self.b) 47 | // NOTE: ^ bug is here; should be :02X 48 | } 49 | pub fn from_hex(s: String) -> Self { 50 | let s = s.strip_prefix('#').unwrap(); 51 | Rgb { 52 | r: u8::from_str_radix(&s[0..2], 16).unwrap(), 53 | g: u8::from_str_radix(&s[2..4], 16).unwrap(), 54 | b: u8::from_str_radix(&s[4..6], 16).unwrap(), 55 | } 56 | } 57 | } 58 | 59 | heckcheck::check(|rgb: Rgb| { 60 | let hex = rgb.to_hex(); 61 | let res = Rgb::from_hex(hex); 62 | assert_eq!(rgb, res); 63 | Ok(()) 64 | }); 65 | } 66 | -------------------------------------------------------------------------------- /src/shrinker.rs: -------------------------------------------------------------------------------- 1 | use crate::{Shrink, ShrinkReport}; 2 | 3 | /// The default test case shrinker. 4 | #[derive(Debug)] 5 | pub struct Shrinker { 6 | offset_start: usize, 7 | source: Vec, 8 | } 9 | 10 | impl Shrink for Shrinker { 11 | fn shrink(source: Vec) -> Self { 12 | Self { 13 | source, 14 | offset_start: 0, 15 | } 16 | } 17 | 18 | fn next(&mut self) -> &[u8] { 19 | &self.source[..self.offset_start] 20 | } 21 | 22 | fn report(&mut self, report: ShrinkReport) -> Option<&[u8]> { 23 | match report { 24 | ShrinkReport::Pass => { 25 | self.offset_start += 1; 26 | None 27 | } 28 | ShrinkReport::Fail => Some(&self.source[..self.offset_start]), 29 | } 30 | } 31 | } 32 | 33 | use std::ops::Div; 34 | 35 | /// Shrinker that keeps "reducing" bytes (get them closer to Zero) until they 36 | /// stop triggering the bug. 37 | #[derive(Debug)] 38 | struct ZeroShrinker { 39 | source: Vec, 40 | index: usize, 41 | value: u8, 42 | } 43 | 44 | impl ZeroShrinker { 45 | /// Find the next index to alter, skipping indices that already contain zeroes. 46 | fn find_next_index_to_zeroify(&mut self) { 47 | while self.index < self.source.len() && self.source[self.index] == 0 { 48 | self.index += 1; 49 | } 50 | } 51 | } 52 | 53 | impl Shrink for ZeroShrinker { 54 | fn shrink(source: Vec) -> Self { 55 | let mut shrinker = Self { 56 | source, 57 | index: 0, 58 | value: 0, 59 | }; 60 | shrinker.find_next_index_to_zeroify(); 61 | shrinker 62 | } 63 | 64 | fn next(&mut self) -> &[u8] { 65 | if self.index < self.source.len() { 66 | assert_ne!(self.source[self.index], 0); 67 | self.value = self.source[self.index]; 68 | self.source[self.index] = self.source[self.index].div(2); 69 | assert_ne!(self.source[self.index], self.value); 70 | } 71 | &self.source 72 | } 73 | 74 | fn report(&mut self, report: ShrinkReport) -> Option<&[u8]> { 75 | if report == ShrinkReport::Pass { 76 | // The test case doesn't trigger the bug anymore, revert to the 77 | // previous value and move on. 78 | self.source[self.index] = self.value; 79 | self.index += 1; 80 | } 81 | 82 | self.find_next_index_to_zeroify(); 83 | 84 | if self.index >= self.source.len() { 85 | Some(&self.source) 86 | } else { 87 | None 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | Contributions include code, documentation, answering user questions, running the 3 | project's infrastructure, and advocating for all types of users. 4 | 5 | The project welcomes all contributions from anyone willing to work in good faith 6 | with other contributors and the community. No contribution is too small and all 7 | contributions are valued. 8 | 9 | This guide explains the process for contributing to the project's GitHub 10 | Repository. 11 | 12 | - [Code of Conduct](#code-of-conduct) 13 | - [Bad Actors](#bad-actors) 14 | 15 | ## Code of Conduct 16 | The project has a [Code of Conduct](./CODE_OF_CONDUCT.md) that *all* 17 | contributors are expected to follow. This code describes the *minimum* behavior 18 | expectations for all contributors. 19 | 20 | As a contributor, how you choose to act and interact towards your 21 | fellow contributors, as well as to the community, will reflect back not only 22 | on yourself but on the project as a whole. The Code of Conduct is designed and 23 | intended, above all else, to help establish a culture within the project that 24 | allows anyone and everyone who wants to contribute to feel safe doing so. 25 | 26 | Should any individual act in any way that is considered in violation of the 27 | [Code of Conduct](./CODE_OF_CONDUCT.md), corrective actions will be taken. It is 28 | possible, however, for any individual to *act* in such a manner that is not in 29 | violation of the strict letter of the Code of Conduct guidelines while still 30 | going completely against the spirit of what that Code is intended to accomplish. 31 | 32 | Open, diverse, and inclusive communities live and die on the basis of trust. 33 | Contributors can disagree with one another so long as they trust that those 34 | disagreements are in good faith and everyone is working towards a common 35 | goal. 36 | 37 | ## Bad Actors 38 | All contributors to tacitly agree to abide by both the letter and 39 | spirit of the [Code of Conduct](./CODE_OF_CONDUCT.md). Failure, or 40 | unwillingness, to do so will result in contributions being respectfully 41 | declined. 42 | 43 | A *bad actor* is someone who repeatedly violates the *spirit* of the Code of 44 | Conduct through consistent failure to self-regulate the way in which they 45 | interact with other contributors in the project. In doing so, bad actors 46 | alienate other contributors, discourage collaboration, and generally reflect 47 | poorly on the project as a whole. 48 | 49 | Being a bad actor may be intentional or unintentional. Typically, unintentional 50 | bad behavior can be easily corrected by being quick to apologize and correct 51 | course *even if you are not entirely convinced you need to*. Giving other 52 | contributors the benefit of the doubt and having a sincere willingness to admit 53 | that you *might* be wrong is critical for any successful open collaboration. 54 | 55 | Don't be a bad actor. 56 | -------------------------------------------------------------------------------- /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of 9 | experience, 10 | education, socio-economic status, nationality, personal appearance, race, 11 | religion, or sexual identity and orientation. 12 | 13 | ## Our Standards 14 | 15 | Examples of behavior that contributes to creating a positive environment 16 | include: 17 | 18 | - Using welcoming and inclusive language 19 | - Being respectful of differing viewpoints and experiences 20 | - Gracefully accepting constructive criticism 21 | - Focusing on what is best for the community 22 | - Showing empathy towards other community members 23 | 24 | Examples of unacceptable behavior by participants include: 25 | 26 | - The use of sexualized language or imagery and unwelcome sexual attention or 27 | advances 28 | - Trolling, insulting/derogatory comments, and personal or political attacks 29 | - Public or private harassment 30 | - Publishing others' private information, such as a physical or electronic 31 | address, without explicit permission 32 | - Other conduct which could reasonably be considered inappropriate in a 33 | professional setting 34 | 35 | 36 | ## Our Responsibilities 37 | 38 | Project maintainers are responsible for clarifying the standards of acceptable 39 | behavior and are expected to take appropriate and fair corrective action in 40 | response to any instances of unacceptable behavior. 41 | 42 | Project maintainers have the right and responsibility to remove, edit, or 43 | reject comments, commits, code, wiki edits, issues, and other contributions 44 | that are not aligned to this Code of Conduct, or to ban temporarily or 45 | permanently any contributor for other behaviors that they deem inappropriate, 46 | threatening, offensive, or harmful. 47 | 48 | ## Scope 49 | 50 | This Code of Conduct applies both within project spaces and in public spaces 51 | when an individual is representing the project or its community. Examples of 52 | representing a project or community include using an official project e-mail 53 | address, posting via an official social media account, or acting as an appointed 54 | representative at an online or offline event. Representation of a project may be 55 | further defined and clarified by project maintainers. 56 | 57 | ## Enforcement 58 | 59 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 60 | reported by contacting the project team at yoshuawuyts@gmail.com, or through 61 | IRC. All complaints will be reviewed and investigated and will result in a 62 | response that is deemed necessary and appropriate to the circumstances. The 63 | project team is obligated to maintain confidentiality with regard to the 64 | reporter of an incident. 65 | Further details of specific enforcement policies may be posted separately. 66 | 67 | Project maintainers who do not follow or enforce the Code of Conduct in good 68 | faith may face temporary or permanent repercussions as determined by other 69 | members of the project's leadership. 70 | 71 | ## Attribution 72 | 73 | This Code of Conduct is adapted from the Contributor Covenant, version 1.4, 74 | available at 75 | https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

heckcheck

2 |
3 | 4 | A heckin small test case generator 5 | 6 |
7 | 8 |
9 | 10 |
11 | 12 | 13 | Crates.io version 15 | 16 | 17 | 18 | Download 20 | 21 | 22 | 23 | docs.rs docs 25 | 26 |
27 | 28 | 43 | 44 | ## Installation 45 | ```sh 46 | $ cargo add heckcheck 47 | ``` 48 | 49 | ## Examples 50 | 51 | This is a basic roundtrip test for an RGB serializer and parser, which ensures 52 | that the output matches the original input. 53 | 54 | ```rust 55 | use heckcheck::prelude::*; 56 | 57 | /// A color value encoded as Red-Green-Blue 58 | #[derive(Clone, Debug, Arbitrary, PartialEq)] 59 | pub struct Rgb { 60 | pub r: u8, 61 | pub g: u8, 62 | pub b: u8, 63 | } 64 | 65 | impl Rgb { 66 | /// Convert from RGB to Hexadecimal. 67 | pub fn to_hex(&self) -> String { 68 | format!("#{:02X}{:02X}{:02X}", self.r, self.g, self.b) 69 | } 70 | 71 | /// Convert from Hexadecimal to RGB. 72 | pub fn from_hex(s: String) -> Self { 73 | let s = s.strip_prefix('#').unwrap(); 74 | Rgb { 75 | r: u8::from_str_radix(&s[0..2], 16).unwrap(), 76 | g: u8::from_str_radix(&s[2..4], 16).unwrap(), 77 | b: u8::from_str_radix(&s[4..6], 16).unwrap(), 78 | } 79 | } 80 | } 81 | 82 | // Validate values can be converted from RGB to Hex and back. 83 | heckcheck::check(|rgb: Rgb| { 84 | let hex = rgb.to_hex(); 85 | let res = Rgb::from_hex(hex); 86 | assert_eq!(rgb, res); 87 | Ok(()) 88 | }); 89 | ``` 90 | 91 | ## Safety 92 | This crate uses ``#![deny(unsafe_code)]`` to ensure everything is implemented in 93 | 100% Safe Rust. 94 | 95 | ## Contributing 96 | Want to join us? Check out our ["Contributing" guide][contributing] and take a 97 | look at some of these issues: 98 | 99 | - [Issues labeled "good first issue"][good-first-issue] 100 | - [Issues labeled "help wanted"][help-wanted] 101 | 102 | [contributing]: https://github.com/yoshuawuyts/heckcheck/blob/master.github/CONTRIBUTING.md 103 | [good-first-issue]: https://github.com/yoshuawuyts/heckcheck/labels/good%20first%20issue 104 | [help-wanted]: https://github.com/yoshuawuyts/heckcheck/labels/help%20wanted 105 | 106 | ## License 107 | 108 | 109 | Licensed under either of Apache License, Version 110 | 2.0 or MIT license at your option. 111 | 112 | 113 |
114 | 115 | 116 | Unless you explicitly state otherwise, any contribution intentionally submitted 117 | for inclusion in this crate by you, as defined in the Apache-2.0 license, shall 118 | be dual licensed as above, without any additional terms or conditions. 119 | 120 | -------------------------------------------------------------------------------- /src/checker.rs: -------------------------------------------------------------------------------- 1 | use arbitrary::{Arbitrary, Unstructured}; 2 | use rand::prelude::*; 3 | use rand::rngs::StdRng; 4 | use std::panic::{self, AssertUnwindSafe}; 5 | 6 | use crate::{Shrink, Shrinker}; 7 | 8 | /// The base number of iterations performed to find an error using `heckcheck`. 9 | const MAX_PASSES: u64 = 100; 10 | 11 | /// The amount of data we initially allocate. 12 | const INITIAL_VEC_LEN: usize = 1024; 13 | 14 | /// The main test checker. 15 | #[derive(Debug)] 16 | pub struct HeckCheck { 17 | bytes: Vec, 18 | max_count: u64, 19 | seed: u64, 20 | rng: StdRng, 21 | } 22 | 23 | impl Default for HeckCheck { 24 | fn default() -> Self { 25 | Self::new() 26 | } 27 | } 28 | 29 | impl HeckCheck { 30 | /// Create a new instance. 31 | pub fn new() -> Self { 32 | let seed = rand::random(); 33 | Self::from_seed(seed) 34 | } 35 | 36 | /// Create a new instance from a seed. 37 | pub fn from_seed(seed: u64) -> Self { 38 | let rng = StdRng::seed_from_u64(seed); 39 | Self { 40 | seed, 41 | rng, 42 | bytes: vec![0u8; INITIAL_VEC_LEN], 43 | max_count: MAX_PASSES, 44 | } 45 | } 46 | 47 | /// Check the target. 48 | pub fn check(&mut self, f: F) 49 | where 50 | A: for<'b> Arbitrary<'b>, 51 | F: FnMut(A) -> arbitrary::Result<()>, 52 | { 53 | self.check_with_shrinker::<_, _, Shrinker>(f) 54 | } 55 | 56 | /// Check the target with the specified shrinker. 57 | pub fn check_with_shrinker(&mut self, mut f: F) 58 | where 59 | A: for<'b> Arbitrary<'b>, 60 | F: FnMut(A) -> arbitrary::Result<()>, 61 | S: Shrink, 62 | { 63 | // Make sure we have enough bytes in our buffer before we start testing. 64 | if self.bytes.len() < A::size_hint(0).0 { 65 | self.grow_vec(Some(A::size_hint(0).0)); 66 | } 67 | 68 | let hook = panic::take_hook(); 69 | panic::set_hook(Box::new(|_| {})); 70 | 71 | for _ in 0..self.max_count { 72 | self.rng.fill_bytes(&mut self.bytes); 73 | let mut u = Unstructured::new(&self.bytes); 74 | let instance = A::arbitrary(&mut u).unwrap(); 75 | 76 | // Track whether we should allocate more data for a future loop. 77 | let mut more_data = false; 78 | 79 | // Call the closure. Handle the return type from `Arbitrary`, and 80 | // handle possible panics from the closure. 81 | let res = std::panic::catch_unwind(AssertUnwindSafe(|| { 82 | if let Err(arbitrary::Error::NotEnoughData) = f(instance) { 83 | more_data = true; 84 | } 85 | })); 86 | 87 | let u_len = u.len(); 88 | if more_data { 89 | self.grow_vec(None); 90 | } 91 | 92 | // If the test panicked we start reducing the test case. 93 | if res.is_err() { 94 | let upper = self.bytes.len() - u_len; 95 | let mut shrinker = S::shrink(self.bytes[0..upper].to_owned()); 96 | loop { 97 | let mut u = Unstructured::new(shrinker.next()); 98 | let instance = A::arbitrary(&mut u).unwrap(); 99 | 100 | let res = std::panic::catch_unwind(AssertUnwindSafe(|| { 101 | f(instance).unwrap(); 102 | })); 103 | if let Some(case) = shrinker.report(res.into()) { 104 | panic::set_hook(hook); 105 | let sequence = base64::encode(case); 106 | match sequence.len() { 107 | 0 => panic!("The failing base64 sequence is: ``. Pass an empty string to `heckcheck::replay` to create a permanent reproduction."), 108 | _ => panic!("The failing base64 sequence is: `{}`. Pass this to `heckcheck::replay` to create a permanent reproduction.", sequence), 109 | } 110 | } 111 | } 112 | } 113 | } 114 | } 115 | 116 | fn grow_vec(&mut self, target: Option) { 117 | match target { 118 | Some(target) => { 119 | if target.checked_sub(self.bytes.len()).is_some() { 120 | self.bytes.resize_with(target, || 0); 121 | } 122 | } 123 | None => self.bytes.resize_with(self.bytes.len() * 2, || 0), 124 | }; 125 | } 126 | 127 | /// Access the value of `seed`. 128 | pub fn seed(&self) -> u64 { 129 | self.seed 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A heckin small test case generator. 2 | //! 3 | //! # What is test case generation? 4 | //! 5 | //! A test case generator is a program which writes programs to test other programs. 6 | //! The idea is that we can find more bugs if we test more paths in a program, 7 | //! and the best way to do that is to provide a wide range of inputs to our 8 | //! programs. And the best way to do _that_ is to write a program designed to 9 | //! generate inputs. You may have heard this being referred to as "fuzzing" or 10 | //! "property testing" as well. 11 | //! 12 | //! # Examples 13 | //! 14 | //! This is a basic roundtrip test for an RGB serializer and parser, which ensures 15 | //! that the output matches the original input. 16 | //! 17 | //! ``` 18 | //! use heckcheck::prelude::*; 19 | //! 20 | //! /// A color value encoded as Red-Green-Blue 21 | //! #[derive(Clone, Debug, Arbitrary, PartialEq)] 22 | //! pub struct Rgb { 23 | //! pub r: u8, 24 | //! pub g: u8, 25 | //! pub b: u8, 26 | //! } 27 | //! 28 | //! impl Rgb { 29 | //! /// Convert from RGB to Hexadecimal. 30 | //! pub fn to_hex(&self) -> String { 31 | //! format!("#{:02X}{:02X}{:02X}", self.r, self.g, self.b) 32 | //! } 33 | //! 34 | //! /// Convert from Hexadecimal to RGB. 35 | //! pub fn from_hex(s: String) -> Self { 36 | //! let s = s.strip_prefix('#').unwrap(); 37 | //! Rgb { 38 | //! r: u8::from_str_radix(&s[0..2], 16).unwrap(), 39 | //! g: u8::from_str_radix(&s[2..4], 16).unwrap(), 40 | //! b: u8::from_str_radix(&s[4..6], 16).unwrap(), 41 | //! } 42 | //! } 43 | //! } 44 | //! 45 | //! // Validate values can be converted from RGB to Hex and back. 46 | //! heckcheck::check(|rgb: Rgb| { 47 | //! let hex = rgb.to_hex(); 48 | //! let res = Rgb::from_hex(hex); 49 | //! assert_eq!(rgb, res); 50 | //! Ok(()) 51 | //! }); 52 | //! ``` 53 | //! 54 | //! # Philosophy 55 | //! 56 | //! We believe that test case generation is an *essential* tool in modern 57 | //! programmer's toolboxes, and both fuzzing and property testing play a role in 58 | //! this. Just like [`cargo-fuzz`](https://github.com/rust-fuzz/cargo-fuzz), 59 | //! `heckcheck` relies on the stable `Arbitrary` trait to modify structured 60 | //! data. This means that all code in a crate can just implement `Arbitrary` in 61 | //! order to be hooked up to a variety of different test case generation tools. 62 | //! 63 | //! Unlike some other tools, `heckcheck` is also *extensible*. The built-in 64 | //! shrinker and permutation algorithms aren't necessarily the best in class. 65 | //! But they can be modified in order to be improved. The end vision would be to 66 | //! see something like `Arbitrary`, `cargo-fuzz`, and `heckcheck` provided out 67 | //! of the box by the `::test` module. 68 | //! 69 | //! # Replaying tests 70 | //! 71 | //! When a test generated by `heckcheck` fails, we print a `base64` string of 72 | //! the input data as part of the panic message. You can pass this string 73 | //! together with the failing code to `heckcheck::replay` to create a 74 | //! reproduction. This makes it quick to go from finding a failing test to 75 | //! having a reproduction available. 76 | //! 77 | //! # Conditional derives 78 | //! 79 | //! If you only want to only derive `Default` when the code is being tested, you 80 | //! can use `cfg_attr(test)` to only compile it when code is being tested. 81 | //! 82 | //! ```rust 83 | //! #[cfg_attr(test, derive(Arbitrary))] 84 | //! #[derive(Clone, Debug, PartialEq)] 85 | //! pub struct Rgb { 86 | //! pub r: u8, 87 | //! pub g: u8, 88 | //! pub b: u8, 89 | //! } 90 | //! ``` 91 | //! 92 | //! # Acknowledgements 93 | //! 94 | //! This crate was built thanks to the work of the [`cargo-fuzz`](https://github.com/rust-fuzz/cargo-fuzz) team on the 95 | //! [`arbitrary`](https://docs.rs/arbitrary/1.0.1/arbitrary/) crate. It has been 96 | //! heavily inspired by burntsushi's work on 97 | //! [`quickcheck`](https://docs.rs/quickcheck/1.0.3/quickcheck/). And we would like to thank 98 | //! [Boxy](https://twitter.com/EllenNyan0214/status/1418730276440707079) who 99 | //! solved a critical bug that almost made us give up. 100 | //! 101 | 102 | #![forbid(unsafe_code, future_incompatible, rust_2018_idioms)] 103 | #![deny(missing_debug_implementations, nonstandard_style)] 104 | #![warn(missing_docs, unreachable_pub)] 105 | 106 | pub use arbitrary; 107 | 108 | use arbitrary::Arbitrary; 109 | 110 | mod checker; 111 | mod shrink; 112 | mod shrinker; 113 | 114 | pub use checker::HeckCheck; 115 | pub use shrink::{Shrink, ShrinkReport}; 116 | pub use shrinker::Shrinker; 117 | 118 | /// The `heckcheck` prelude 119 | pub mod prelude { 120 | pub use arbitrary::Arbitrary; 121 | } 122 | 123 | /// Check a target. 124 | /// 125 | /// This is a shorthand for calling `HeckCheck::new` and `HeckCheck::check`. 126 | pub fn check(f: F) 127 | where 128 | A: for<'b> Arbitrary<'b>, 129 | F: FnMut(A) -> arbitrary::Result<()>, 130 | { 131 | let mut checker = HeckCheck::new(); 132 | checker.check(f); 133 | } 134 | 135 | /// Replay a failing test from a base64 string. 136 | /// 137 | /// When a call to `check` fails, a base64-encoded string is printed 138 | /// representing the failing input data. You can pass this string together with 139 | /// the failing test code to `heckcheck::replay` to create a permanent 140 | /// reproduction of the error. 141 | pub fn replay(bytes: &str, mut f: F) 142 | where 143 | A: for<'b> Arbitrary<'b>, 144 | F: FnMut(A) -> arbitrary::Result<()>, 145 | { 146 | let bytes = base64::decode(bytes).unwrap(); 147 | let mut u = arbitrary::Unstructured::new(&bytes); 148 | let instance = A::arbitrary(&mut u).unwrap(); 149 | f(instance).unwrap(); 150 | } 151 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | Copyright 2020 Yoshua Wuyts 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | --------------------------------------------------------------------------------