├── .github └── workflows │ └── ci.yaml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples └── regex.rs ├── rustfmt.toml ├── src └── lib.rs └── xtask ├── Cargo.toml ├── src └── main.rs └── tests └── tidy.rs /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | pull_request: 4 | push: 5 | branches: ["master", "staging", "trying"] 6 | 7 | env: 8 | CARGO_INCREMENTAL: 0 9 | CARGO_NET_RETRY: 10 10 | CI: 1 11 | RUST_BACKTRACE: short 12 | RUSTFLAGS: -D warnings 13 | RUSTUP_MAX_RETRIES: 10 14 | 15 | jobs: 16 | test: 17 | name: Rust 18 | runs-on: ubuntu-latest 19 | 20 | steps: 21 | - uses: actions/checkout@v2 22 | with: 23 | fetch-depth: 0 # fetch tags for publish 24 | - uses: actions-rs/toolchain@v1 25 | with: 26 | toolchain: stable 27 | profile: minimal 28 | override: true 29 | 30 | - run: cargo run --package xtask 31 | env: 32 | CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "arbtest" 3 | version = "0.3.3" 4 | description = "A minimalist property-based testing library based on arbitrary" 5 | categories = ["development-tools::testing"] 6 | license = "MIT OR Apache-2.0" 7 | repository = "https://github.com/matklad/arbtest" 8 | authors = ["Aleksey Kladov "] 9 | edition = "2021" 10 | 11 | exclude = [".github/", "rustfmt.toml"] 12 | 13 | [workspace] 14 | members = ["xtask"] 15 | 16 | [dependencies] 17 | arbitrary = "1.3.0" 18 | 19 | [dev-dependencies] 20 | arbitrary = { version = "1.3.0", features = ["derive" ] } 21 | regex = { version = "0.1.5", package = "regex-lite" } 22 | -------------------------------------------------------------------------------- /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 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # arbtest 2 | 3 | A powerful property-based testing library with a tiny API and a small implementation. 4 | 5 | ```rust 6 | use arbtest::arbtest; 7 | 8 | #[test] 9 | fn all_numbers_are_even() { 10 | arbtest(|u| { 11 | let number: u32 = u.arbitrary()?; 12 | assert!(number % 2 == 0); 13 | Ok(()) 14 | }); 15 | } 16 | ``` 17 | -------------------------------------------------------------------------------- /examples/regex.rs: -------------------------------------------------------------------------------- 1 | //! This example uses `arbtest` to find a minimal regex which matches `abba` but 2 | //! not `baab`. 3 | //! 4 | //! With the given seed, we get the following sequence of minimizations: 5 | //! 6 | //! ``` 7 | //! (a)|(((a)|(b))|((a(a)|((b)|(((b)*)|(((a)|(b))|((ab)|(((b)*)|(((((a)|(a))|(a))*)|(a))))))))*))a 8 | //! ((b)|(ab)((b)|((a)|(a)))*)|(a) 9 | //! ((((((b)*)|(a))|(a))*)*a)|(a) 10 | //! ((b)|(a))*a 11 | //! ((b)|(a))*a 12 | //! ((b)*a)* 13 | //! ``` 14 | 15 | use arbtest::{arbitrary, arbtest}; 16 | use regex::Regex; 17 | 18 | fn arb_regex(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result { 19 | let choices: &[fn(&mut arbitrary::Unstructured<'_>) -> arbitrary::Result] = &[ 20 | |_u| Ok("a".to_string()), 21 | |_u| Ok("b".to_string()), 22 | |u| arb_regex(u).map(|r| format!("({r})*")), 23 | |u| { 24 | let l = arb_regex(u)?; 25 | let r = arb_regex(u)?; 26 | Ok(format!("{l}{r}")) 27 | }, 28 | |u| { 29 | let l = arb_regex(u)?; 30 | let r = arb_regex(u)?; 31 | Ok(format!("({l})|({r})")) 32 | }, 33 | ]; 34 | u.choose(choices)?(u) 35 | } 36 | 37 | fn main() { 38 | arbtest(|u| { 39 | let r = arb_regex(u)?; 40 | if let Ok(regex) = Regex::new(&format!("^({r})$")) { 41 | if regex.is_match("abba") && !regex.is_match("baab") { 42 | eprintln!("{r}"); 43 | panic!() 44 | } 45 | } 46 | Ok(()) 47 | }) 48 | .budget_ms(10_000) 49 | .seed(0x7abcb62800000020) 50 | .minimize(); 51 | } 52 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | reorder_modules = false 2 | use_small_heuristics = "Max" 3 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A powerful property-based testing library with a tiny API and a small implementation. 2 | //! 3 | //! ```rust 4 | //! use arbtest::arbtest; 5 | //! 6 | //! #[test] 7 | //! fn all_numbers_are_even() { 8 | //! arbtest(|u| { 9 | //! let number: u32 = u.arbitrary()?; 10 | //! assert!(number % 2 == 0); 11 | //! Ok(()) 12 | //! }); 13 | //! } 14 | //! ``` 15 | //! 16 | //! Features: 17 | //! 18 | //! - single-function public API, 19 | //! - no macros, 20 | //! - automatic minimization, 21 | //! - time budgeting, 22 | //! - fuzzer-compatible tests. 23 | //! 24 | //! The entry point is the [`arbtest`] function. It accepts a single argument --- a property to 25 | //! test. A property is a function with the following signature: 26 | //! 27 | //! ``` 28 | //! /// Panics if the property does not hold. 29 | //! fn property(u: &mut arbitrary::Unstructured) -> arbitrary::Result<()> 30 | //! # { Ok(drop(u)) } 31 | //! ``` 32 | //! 33 | //! The `u` argument is a finite random number generator from the [`arbitrary`] crate. You can use 34 | //! `u` to generate pseudo-random structured data: 35 | //! 36 | //! ``` 37 | //! # fn property(u: &mut arbitrary::Unstructured) -> arbitrary::Result<()> { 38 | //! let ints: Vec = u.arbitrary()?; 39 | //! let fruit: &str = u.choose(&["apple", "banana", "cherimoya"])?; 40 | //! # Ok(()) } 41 | //! ``` 42 | //! 43 | //! Or use the derive feature of the arbitrary crate to automatically generate arbitrary types: 44 | //! 45 | //! ``` 46 | //! # fn property(u: &mut arbitrary::Unstructured) -> arbitrary::Result<()> { 47 | //! #[derive(arbitrary::Arbitrary)] 48 | //! struct Color { r: u8, g: u8, b: u8 } 49 | //! 50 | //! let random_color = u.arbitrary::()?; 51 | //! # Ok(()) } 52 | //! ``` 53 | //! Property function should use randomly generated data to assert some interesting behavior of the 54 | //! implementation, which should hold for _any_ values. For example, converting a color to string 55 | //! and then parsing it back should result in the same color: 56 | //! 57 | //! ``` 58 | //! # type Color = u8; // lol 59 | //! #[test] 60 | //! fn parse_is_display_inverted() { 61 | //! arbtest(|u| { 62 | //! let c1: Color = u.arbitrary(); 63 | //! let c2: Color = c1.to_string().parse().unwrap(); 64 | //! assert_eq!(c1, c2); 65 | //! Ok(()) 66 | //! }) 67 | //! } 68 | //! ``` 69 | //! 70 | //! After you have supplied the property function, arbtest repeatedly runs it in a loop, passing 71 | //! more and more [`arbitrary::Unstructured`] bytes until the property panics. Upon a failure, a 72 | //! seed is printed. The seed can be used to deterministically replay the failure. 73 | //! 74 | //! ```text 75 | //! thread 'all_numbers_are_even' panicked at src/lib.rs:116:9: 76 | //! assertion failed: number % 2 == 0 77 | //! note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace 78 | //! 79 | //! arbtest failed! 80 | //! Seed: 0xa88e234400000020 81 | //! ``` 82 | //! 83 | //! More features are available with builder-style API on the returned [`ArbTest`] object. 84 | //! 85 | //! ## Time Budgeting 86 | //! 87 | //! ``` 88 | //! # use arbtest::arbtest; use std::time::Duration; 89 | //! # fn property(_: &mut arbitrary::Unstructured) -> arbitrary::Result<()> { Ok(()) } 90 | //! arbtest(property).budget_ms(1_000); 91 | //! arbtest(property).budget(Duration::from_secs(1)); 92 | //! ``` 93 | //! 94 | //! The [`budget`](ArbTest::budget) function controls how long the search loop runs, default is one 95 | //! hundred milliseconds. This default can be overridden with the `ARBTEST_BUDGET_MS` environment 96 | //! variable. 97 | //! 98 | //! ## Size Constraint 99 | //! 100 | //! ``` 101 | //! # use arbtest::arbtest; 102 | //! # fn property(_: &mut arbitrary::Unstructured) -> arbitrary::Result<()> { Ok(()) } 103 | //! arbtest(property) 104 | //! .size_min(1 << 4) 105 | //! .size_max(1 << 16); 106 | //! ``` 107 | //! 108 | //! Internally, [`arbitrary::Unstructured`] is just an `&[u8]` --- a slice of random bytes. The 109 | //! length of this slice determines how much randomness your tests gets to use. A shorter slice 110 | //! contains less entropy and leads to a simpler test case. 111 | //! 112 | //! The [`size_min`](ArbTest::size_min) and [`size_max`](ArbTest::size_max) parameters control the 113 | //! length of this slice: when looking for a failure, `arbtest` progressively increases the size 114 | //! from `size_min` to `size_max`. 115 | //! 116 | //! Note when trying to minimize a known failure, `arbtest` will try to go even smaller than 117 | //! `size_min`. 118 | //! 119 | //! ## Replay and Minimization 120 | //! 121 | //! ``` 122 | //! # use arbtest::arbtest; 123 | //! # let property = |_: &mut arbitrary::Unstructured| -> arbitrary::Result<()> { Ok(()) }; 124 | //! arbtest(property).seed(0x92); 125 | //! # let property = |_: &mut arbitrary::Unstructured| -> arbitrary::Result<()> { panic!() }; 126 | //! arbtest(property).seed(0x92).minimize(); 127 | //! ``` 128 | //! 129 | //! When a [`seed`](ArbTest::seed) is specified or provided via the `ARBTEST_SEED` environment 130 | //! variable, `arbtest` uses the seed to generate a fixed `Unstructured` and runs the property 131 | //! function once. This is useful to debug a test failure after a failing seed is found through 132 | //! search. 133 | //! 134 | //! If in addition to `seed` [`minimize`](ArbTest::minimize) is set, then `arbtest` will try to find 135 | //! a smaller seed which still triggers a failure. You could use [`budget`](ArbTest::budget) to 136 | //! control how long the minimization runs. 137 | //! 138 | //! ## When the Code Gets Run 139 | //! 140 | //! The [`arbtest`] function doesn't immediately run the code. Instead, it returns an [`ArbTest`] 141 | //! builder object that can be used to further tweak the behavior. The actual execution is triggered 142 | //! from the [`ArbTest::drop`]. If panicking in `drop` is not your thing, you can trigger 143 | //! the execution explicitly using [`ArbTest::run`] method: 144 | //! 145 | //! ``` 146 | //! # use arbtest::arbtest; 147 | //! # fn property(_: &mut arbitrary::Unstructured) -> arbitrary::Result<()> { Ok(()) } 148 | //! let builder = arbtest(property); 149 | //! drop(builder); // This line actually runs the tests. 150 | //! 151 | //! arbtest(property).run(); // Request the run explicitly. 152 | //! ``` 153 | //! 154 | //! ## Errors 155 | //! 156 | //! Property failures should be reported via a panic, for example, using `assert_eq!` macros. 157 | //! Returning an `Err(arbitrary::Error)` doesn't signal a test failure, it just means that there 158 | //! isn't enough entropy left to complete the test. Instead of returning an [`arbitrary::Error`], a 159 | //! test might choose to continue in a non-random way. For example, when testing a distributed 160 | //! system you might use the following template: 161 | //! 162 | //! ```text 163 | //! while !u.is_empty() && network.has_messages_in_flight() { 164 | //! network.drop_and_permute_messages(u); 165 | //! network.deliver_next_message(); 166 | //! } 167 | //! while network.has_messages_in_flight() { 168 | //! network.deliver_next_message(); 169 | //! } 170 | //! ``` 171 | //! 172 | //! ## Imports 173 | //! 174 | //! Recommended way to import: 175 | //! 176 | //! ```toml 177 | //! [dev-dependencies] 178 | //! arbtest = "0.3" 179 | //! ``` 180 | //! 181 | //! ``` 182 | //! #[cfg(test)] 183 | //! mod tests { 184 | //! use arbtest::{arbtest, arbitrary}; 185 | //! 186 | //! fn my_property(u: &mut arbitrary::Unstructured) -> arbitrary::Result<()> { Ok(()) } 187 | //! } 188 | //! ``` 189 | //! 190 | //! If you want to `#[derive(Arbitrary)]`, you need to explicitly add Cargo.toml dependency for the 191 | //! [`arbitrary`] crate: 192 | //! 193 | //! ```toml 194 | //! [dependencies] 195 | //! arbitrary = { version = "1", features = ["derive"] } 196 | //! 197 | //! [dev-dependencies] 198 | //! arbtest = "0.3" 199 | //! ``` 200 | //! 201 | //! ``` 202 | //! #[derive(arbitrary::Arbitrary)] 203 | //! struct Color { r: u8, g: u8, b: u8 } 204 | //! 205 | //! #[cfg(test)] 206 | //! mod tests { 207 | //! use arbtest::arbtest; 208 | //! 209 | //! #[test] 210 | //! fn display_parse_identity() { 211 | //! arbtest(|u| { 212 | //! let c1: Color = u.arbitrary()?; 213 | //! let c2: Color = c1.to_string().parse(); 214 | //! assert_eq!(c1, c2); 215 | //! Ok(()) 216 | //! }); 217 | //! } 218 | //! } 219 | //! ``` 220 | //! 221 | //! Note that `arbitrary` is a non-dev dependency. This is not strictly required, but is helpful to 222 | //! allow downstream crates to run their tests with arbitrary values of `Color`. 223 | //! 224 | //! ## Design 225 | //! 226 | //! Most of the heavy lifting is done by the [`arbitrary`] crate. Its [`arbitrary::Unstructured`] is 227 | //! a brilliant abstraction which works both for coverage-guided fuzzing as well as for automated 228 | //! minimization. That is, you can plug `arbtest` properties directly into `cargo fuzz`, API is 229 | //! fully compatible. 230 | //! 231 | //! Property function uses `&mut Unstructured` as an argument instead of `T: Arbitrary`, allowing 232 | //! the user to generate any `T` they want imperatively. The smaller benefit here is implementation 233 | //! simplicity --- the property type is not generic. The bigger benefit is that this API is more 234 | //! expressive, as it allows for _interactive_ properties. For example, a network simulation for a 235 | //! distributed system doesn't have to generate "failure plan" upfront, it can use `u` during the 236 | //! test run to make _dynamic_ decisions about which existing network packets to drop! 237 | //! 238 | //! A "seed" is an `u64`, by convention specified in hexadecimal. The low 32 bits of the seed 239 | //! specify the length of the underlying `Unstructured`. The high 32 bits are the random seed 240 | //! proper, which is feed into a simple xor-shift to generate `Unstructured` of the specified 241 | //! length. 242 | //! 243 | //! If you like this crate, you might enjoy as well. 244 | #![deny(missing_docs)] 245 | 246 | use std::{ 247 | collections::hash_map::RandomState, 248 | fmt, 249 | hash::{BuildHasher, Hasher}, 250 | panic::AssertUnwindSafe, 251 | time::{Duration, Instant}, 252 | }; 253 | 254 | #[doc(no_inline)] 255 | pub use arbitrary; 256 | 257 | /// Repeatedly test `property` with different random seeds. 258 | /// 259 | /// Return value is an [`ArbTest`] builder object which can be used to tweak behavior. 260 | pub fn arbtest

(property: P) -> ArbTest

261 | where 262 | P: FnMut(&mut arbitrary::Unstructured<'_>) -> arbitrary::Result<()>, 263 | { 264 | let options = 265 | Options { size_min: 32, size_max: 65_536, budget: None, seed: None, minimize: false }; 266 | ArbTest { property, options, done: false } 267 | } 268 | 269 | /// A builder for a property-based test. 270 | /// 271 | /// This builder allows customizing various aspects of the test, such as the 272 | /// initial random seed, the amount of iterations to try, or the amount of 273 | /// random numbers (entropy) each test run gets. 274 | /// 275 | /// For convenience, `ArbTest` automatically runs the test on drop. You can use [`ArbTest::run`] 276 | /// to run the test explicitly. 277 | pub struct ArbTest

278 | where 279 | P: FnMut(&mut arbitrary::Unstructured<'_>) -> arbitrary::Result<()>, 280 | { 281 | property: P, 282 | options: Options, 283 | done: bool, 284 | } 285 | 286 | struct Options { 287 | size_min: u32, 288 | size_max: u32, 289 | budget: Option, 290 | seed: Option, 291 | minimize: bool, 292 | } 293 | 294 | impl

ArbTest

295 | where 296 | P: FnMut(&mut arbitrary::Unstructured<'_>) -> arbitrary::Result<()>, 297 | { 298 | /// Sets the lower bound on the amount of random bytes each test run gets. 299 | /// 300 | /// Defaults to 32. 301 | /// 302 | /// Each randomized test gets an [arbitrary::Unstructured] as a source of 303 | /// randomness. `Unstructured` can be thought of as a *finite* pseudo random 304 | /// number generator, or, alternatively, as a finite sequence of random 305 | /// numbers. The intuition here is that _shorter_ sequences lead to simpler 306 | /// test cases. 307 | /// 308 | /// The `size` parameter controls the length of the initial random sequence. 309 | /// More specifically, `arbtest` will run the test function multiple times, 310 | /// increasing the amount of entropy from `size_min` to `size_max`. 311 | pub fn size_min(mut self, size: u32) -> Self { 312 | self.options.size_min = size; 313 | self 314 | } 315 | 316 | /// Sets the upper bound on the amount of random bytes each test run gets. 317 | /// 318 | /// Defaults to 65 536. 319 | /// 320 | /// See [`ArbTest::size_min`]. 321 | pub fn size_max(mut self, size: u32) -> Self { 322 | self.options.size_max = size; 323 | self 324 | } 325 | 326 | /// Sets the approximate duration for the tests. 327 | /// 328 | /// Defaults to 100ms, can be overridden via the `ARBTEST_BUDGET_MS` environment variable. 329 | /// 330 | /// `arbtest` will re-run the test function until the time runs out or until it panics. 331 | pub fn budget(mut self, value: Duration) -> Self { 332 | self.options.budget = Some(value); 333 | self 334 | } 335 | 336 | /// Sets the approximate duration for the tests, in milliseconds. 337 | pub fn budget_ms(self, value: u64) -> Self { 338 | self.budget(Duration::from_millis(value)) 339 | } 340 | 341 | /// Fixes the random seed. 342 | /// 343 | /// Can also be set explicitly via the `ARBTEST_SEED` environment variable. 344 | /// 345 | /// Normally, `arbtest` runs the test function multiple times, picking a 346 | /// fresh random seed of an increased complexity every time. 347 | /// 348 | /// If the `seed` is set explicitly, the `test` function is run only once. 349 | pub fn seed(mut self, seed: u64) -> Self { 350 | self.options.seed = Some(Seed::new(seed)); 351 | self 352 | } 353 | 354 | /// Whether to try to minimize the seed after failure. 355 | pub fn minimize(mut self) -> Self { 356 | self.options.minimize = true; 357 | self 358 | } 359 | 360 | /// Runs the test. 361 | /// 362 | /// This is equivalent to just dropping `ArbTest`. 363 | pub fn run(mut self) { 364 | self.context().run(); 365 | } 366 | 367 | fn context(&mut self) -> Context<'_, '_> { 368 | assert!(!self.done); 369 | self.done = true; 370 | Context { property: &mut self.property, options: &self.options, buffer: Vec::new() } 371 | } 372 | } 373 | 374 | impl

Drop for ArbTest

375 | where 376 | P: FnMut(&mut arbitrary::Unstructured<'_>) -> arbitrary::Result<()>, 377 | { 378 | /// Runs property test. 379 | /// 380 | /// See [`ArbTest::run`]. 381 | fn drop(&mut self) { 382 | if !self.done { 383 | self.context().run(); 384 | } 385 | } 386 | } 387 | 388 | type DynProperty<'a> = &'a mut dyn FnMut(&mut arbitrary::Unstructured<'_>) -> arbitrary::Result<()>; 389 | 390 | struct Context<'a, 'b> { 391 | property: DynProperty<'a>, 392 | options: &'b Options, 393 | buffer: Vec, 394 | } 395 | 396 | impl<'a, 'b> Context<'a, 'b> { 397 | fn run(&mut self) { 398 | let budget = { 399 | let default = Duration::from_millis(100); 400 | self.options.budget.or_else(env_budget).unwrap_or(default) 401 | }; 402 | 403 | match (self.options.seed.or_else(env_seed), self.options.minimize) { 404 | (None, false) => self.run_search(budget), 405 | (None, true) => panic!("can't minimize without a seed"), 406 | (Some(seed), false) => self.run_reproduce(seed), 407 | (Some(seed), true) => self.run_minimize(seed, budget), 408 | } 409 | } 410 | 411 | fn run_search(&mut self, budget: Duration) { 412 | let t = Instant::now(); 413 | 414 | let mut last_result = Ok(()); 415 | let mut seen_success = false; 416 | 417 | let mut size = self.options.size_min; 418 | 'search: loop { 419 | for _ in 0..3 { 420 | if t.elapsed() > budget { 421 | break 'search; 422 | } 423 | 424 | let seed = Seed::gen(size); 425 | { 426 | let guard = PrintSeedOnPanic::new(seed); 427 | last_result = self.try_seed(seed); 428 | seen_success = seen_success || last_result.is_ok(); 429 | guard.defuse() 430 | } 431 | } 432 | 433 | let bigger = (size as u64).saturating_mul(5) / 4; 434 | size = bigger.clamp(0, self.options.size_max as u64) as u32; 435 | } 436 | 437 | if !seen_success { 438 | let error = last_result.unwrap_err(); 439 | panic!("no fitting seeds, last error: {error}"); 440 | } 441 | } 442 | 443 | fn run_reproduce(&mut self, seed: Seed) { 444 | let guard = PrintSeedOnPanic::new(seed); 445 | self.try_seed(seed).unwrap_or_else(|error| panic!("{error}")); 446 | guard.defuse() 447 | } 448 | 449 | fn run_minimize(&mut self, seed: Seed, budget: Duration) { 450 | let old_hook = std::panic::take_hook(); 451 | std::panic::set_hook(Box::new(|_| ())); 452 | 453 | if !self.try_seed_panics(seed) { 454 | std::panic::set_hook(old_hook); 455 | panic!("seed {seed} did not panic") 456 | } 457 | 458 | let mut seed = seed; 459 | let t = std::time::Instant::now(); 460 | 461 | let minimizers = [|s| s / 2, |s| s * 9 / 10, |s| s - 1]; 462 | let mut minimizer = 0; 463 | 464 | let mut last_minimization = Instant::now(); 465 | 'search: loop { 466 | let size = seed.size(); 467 | eprintln!("seed {seed}, seed size {size}, search time {:0.2?}", t.elapsed()); 468 | if size == 0 { 469 | break; 470 | } 471 | loop { 472 | if t.elapsed() > budget { 473 | break 'search; 474 | } 475 | if last_minimization.elapsed() > budget / 5 && minimizer < minimizers.len() - 1 { 476 | minimizer += 1; 477 | } 478 | let size = minimizers[minimizer](size); 479 | let candidate_seed = Seed::gen(size); 480 | if self.try_seed_panics(candidate_seed) { 481 | seed = candidate_seed; 482 | last_minimization = Instant::now(); 483 | continue 'search; 484 | } 485 | } 486 | } 487 | std::panic::set_hook(old_hook); 488 | let size = seed.size(); 489 | eprintln!("minimized"); 490 | eprintln!("seed {seed}, seed size {size}, search time {:0.2?}", t.elapsed()); 491 | panic!("minimization failed successfully!"); 492 | } 493 | 494 | fn try_seed(&mut self, seed: Seed) -> arbitrary::Result<()> { 495 | seed.fill(&mut self.buffer); 496 | let mut u = arbitrary::Unstructured::new(&self.buffer); 497 | (self.property)(&mut u) 498 | } 499 | 500 | fn try_seed_panics(&mut self, seed: Seed) -> bool { 501 | let mut me = AssertUnwindSafe(self); 502 | std::panic::catch_unwind(move || { 503 | let _ = me.try_seed(seed); 504 | }) 505 | .is_err() 506 | } 507 | } 508 | 509 | fn env_budget() -> Option { 510 | let var = std::env::var("ARBTEST_BUDGET_MS").ok()?; 511 | let ms = var.parse::().ok()?; 512 | Some(Duration::from_millis(ms)) 513 | } 514 | 515 | fn env_seed() -> Option { 516 | let var = std::env::var("ARBTEST_SEED").ok()?; 517 | // Check if it starts with "0x" and stip it if necessary before parsing as hex. 518 | let repr = u64::from_str_radix( 519 | if let Some(stripped_var) = var.strip_prefix("0x") { stripped_var } else { &var }, 520 | 16, 521 | ) 522 | .ok()?; 523 | Some(Seed { repr }) 524 | } 525 | 526 | /// Random seed used to generated an `[u8]` underpinning the `Unstructured` 527 | /// instance we pass to user's code. 528 | /// 529 | /// The seed is two `u32` mashed together. Low half defines the *length* of the 530 | /// sequence, while the high bits are the random seed proper. 531 | /// 532 | /// The reason for this encoding is to be able to print a seed as a single 533 | /// copy-pastable number. 534 | #[derive(Clone, Copy)] 535 | struct Seed { 536 | repr: u64, 537 | } 538 | 539 | impl fmt::Display for Seed { 540 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 541 | write!(f, "\x1b[1m0x{:016x}\x1b[0m", self.repr) 542 | } 543 | } 544 | 545 | impl Seed { 546 | fn new(repr: u64) -> Seed { 547 | Seed { repr } 548 | } 549 | fn gen(size: u32) -> Seed { 550 | let raw = RandomState::new().build_hasher().finish(); 551 | let repr = size as u64 | (raw << u32::BITS); 552 | Seed { repr } 553 | } 554 | fn size(self) -> u32 { 555 | self.repr as u32 556 | } 557 | fn rand(self) -> u32 { 558 | (self.repr >> u32::BITS) as u32 559 | } 560 | fn fill(self, buf: &mut Vec) { 561 | buf.clear(); 562 | buf.reserve(self.size() as usize); 563 | let mut random = self.rand(); 564 | let mut rng = std::iter::repeat_with(move || { 565 | random ^= random << 13; 566 | random ^= random >> 17; 567 | random ^= random << 5; 568 | random 569 | }); 570 | while buf.len() < self.size() as usize { 571 | buf.extend(rng.next().unwrap().to_le_bytes()); 572 | } 573 | } 574 | } 575 | 576 | struct PrintSeedOnPanic { 577 | seed: Seed, 578 | active: bool, 579 | } 580 | 581 | impl PrintSeedOnPanic { 582 | fn new(seed: Seed) -> PrintSeedOnPanic { 583 | PrintSeedOnPanic { seed, active: true } 584 | } 585 | fn defuse(mut self) { 586 | self.active = false 587 | } 588 | } 589 | 590 | impl Drop for PrintSeedOnPanic { 591 | fn drop(&mut self) { 592 | if self.active { 593 | eprintln!("\narbtest failed!\n Seed: {}\n\n", self.seed) 594 | } 595 | } 596 | } 597 | -------------------------------------------------------------------------------- /xtask/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "xtask" 3 | version = "0.0.0" 4 | publish = false 5 | edition = "2021" 6 | 7 | [dependencies] 8 | xshell = "0.2.1" 9 | -------------------------------------------------------------------------------- /xtask/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::time::Instant; 2 | 3 | use xshell::{cmd, Shell}; 4 | 5 | fn main() -> xshell::Result<()> { 6 | let sh = Shell::new()?; 7 | 8 | { 9 | let _s = section("BUILD"); 10 | cmd!(sh, "cargo test --workspace --no-run").run()?; 11 | } 12 | 13 | { 14 | let _s = section("TEST"); 15 | cmd!(sh, "cargo test --workspace -- --nocapture").run()?; 16 | } 17 | 18 | { 19 | let _s = section("PUBLISH"); 20 | 21 | let version = cmd!(sh, "cargo pkgid").read()?.rsplit_once('#').unwrap().1.to_string(); 22 | let tag = format!("v{version}"); 23 | 24 | let current_branch = cmd!(sh, "git branch --show-current").read()?; 25 | let has_tag = cmd!(sh, "git tag --list").read()?.lines().any(|it| it.trim() == tag); 26 | let dry_run = sh.var("CI").is_err() || has_tag || current_branch != "master"; 27 | eprintln!("Publishing{}!", if dry_run { " (dry run)" } else { "" }); 28 | 29 | let dry_run_arg = if dry_run { Some("--dry-run") } else { None }; 30 | cmd!(sh, "cargo publish {dry_run_arg...}").run()?; 31 | if dry_run { 32 | eprintln!("{}", cmd!(sh, "git tag {tag}")); 33 | eprintln!("{}", cmd!(sh, "git push --tags")); 34 | } else { 35 | cmd!(sh, "git tag {tag}").run()?; 36 | cmd!(sh, "git push --tags").run()?; 37 | } 38 | } 39 | Ok(()) 40 | } 41 | 42 | fn section(name: &'static str) -> impl Drop { 43 | println!("::group::{name}"); 44 | let start = Instant::now(); 45 | defer(move || { 46 | let elapsed = start.elapsed(); 47 | eprintln!("{name}: {elapsed:.2?}"); 48 | println!("::endgroup::"); 49 | }) 50 | } 51 | 52 | fn defer(f: F) -> impl Drop { 53 | struct D(Option); 54 | impl Drop for D { 55 | fn drop(&mut self) { 56 | if let Some(f) = self.0.take() { 57 | f() 58 | } 59 | } 60 | } 61 | D(Some(f)) 62 | } 63 | -------------------------------------------------------------------------------- /xtask/tests/tidy.rs: -------------------------------------------------------------------------------- 1 | use xshell::{cmd, Shell}; 2 | 3 | #[test] 4 | fn test_formatting() { 5 | let sh = Shell::new().unwrap(); 6 | cmd!(sh, "cargo fmt --all -- --check").run().unwrap() 7 | } 8 | --------------------------------------------------------------------------------