Skip to content

Commit

Permalink
tests(fuzz): Add parse_duration fuzzing target (#1129)
Browse files Browse the repository at this point in the history
Add a fuzzing target for parsing into a Duration.
  • Loading branch information
caspermeijn committed Aug 23, 2024
1 parent 52046b9 commit 0c79864
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
7 changes: 7 additions & 0 deletions fuzz/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,10 @@ path = "fuzzers/parse_date.rs"
test = false
doc = false
bench = false

[[bin]]
name = "parse_duration"
path = "fuzzers/parse_duration.rs"
test = false
doc = false
bench = false
31 changes: 31 additions & 0 deletions fuzz/fuzzers/parse_duration.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#![no_main]

use libfuzzer_sys::fuzz_target;

fuzz_target!(|data: &[u8]| test_parse_duration(data));

pub fn test_parse_duration(data: &[u8]) {
use std::str::from_utf8;
use std::str::FromStr;

// input must be text
let Ok(original_text) = from_utf8(data) else {
return;
};

// parse input as a duration
let Ok(duration) = prost_types::Duration::from_str(original_text) else {
if original_text.ends_with("s") {
assert!(
original_text.parse::<f64>().is_err(),
"prost failed to parse duration, but it seems to be a valid number: {}",
original_text
);
}
return;
};

// roundtrip to and from string
let roundtrip_text = format!("{duration}");
assert_eq!(Ok(&duration), roundtrip_text.parse().as_ref());
}

0 comments on commit 0c79864

Please sign in to comment.