| 1 | //! `proptest`-powered property-based tests. |
| 2 | |
| 3 | use const_oid::{Error, ObjectIdentifier}; |
| 4 | use proptest::prelude::*; |
| 5 | use regex::Regex; |
| 6 | |
| 7 | prop_compose! { |
| 8 | /// Produce a string of digits and dots, i.e. the component parts of OIDs. |
| 9 | /// |
| 10 | /// Note that this can be any permutation of digits-and-dots and does not necessarily |
| 11 | /// represent a valid OID. |
| 12 | fn oid_like_string()(bytes in any::<Vec<u8>>()) -> String { |
| 13 | // Create a digit or dot from a byte input |
| 14 | fn byte_to_char(byte: u8) -> char { |
| 15 | match byte % 11 { |
| 16 | n @ 0..=9 => (b'0' + n) as char, |
| 17 | 10 => '.', |
| 18 | _ => unreachable!() |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | |
| 23 | let mut ret = String::with_capacity(bytes.len()); |
| 24 | for byte in bytes { |
| 25 | ret.push(byte_to_char(byte)); |
| 26 | } |
| 27 | ret |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | proptest! { |
| 32 | #[test] |
| 33 | fn round_trip(s in oid_like_string()) { |
| 34 | match ObjectIdentifier::new(&s) { |
| 35 | Ok(oid) => { |
| 36 | // Leading zeros won't round trip, so ignore that case |
| 37 | // TODO(tarcieri): disallow leading zeros? |
| 38 | if !s.starts_with("0") && !s.contains(".0") { |
| 39 | let oid_string = oid.to_string(); |
| 40 | prop_assert_eq!(s, oid_string); |
| 41 | } |
| 42 | }, |
| 43 | Err(Error::ArcInvalid { .. }) | Err(Error::ArcTooBig) => (), |
| 44 | Err(e) => { |
| 45 | let re = Regex::new("^([0-2])\\.([0-3]?[0-9])((\\.0)|(\\.[1-9][0-9]*))+$").unwrap(); |
| 46 | |
| 47 | prop_assert!( |
| 48 | re.find(&s).is_none(), |
| 49 | "regex asserts OID `{}` is valid, but `const-oid`failed: {}", |
| 50 | &s, |
| 51 | &e |
| 52 | ); |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | } |