use std::collections::HashMap;
use std::fmt::Write as _;
use proptest::prelude::*;
use super::*;
use crate::parse::Fields;
type Rows = Vec<(String, String)>;
fn rows(out: &Fields<'_>) -> Rows {
out.as_slice()
.iter()
.map(|(k, v)| (k.clone(), String::from_utf8_lossy(&v.bytes).into_owned()))
.collect()
}
fn want(pairs: &[(&str, &str)]) -> Rows {
pairs
.iter()
.map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
.collect()
}
#[test]
fn lines_read_by_the_stateless_parser() {
let table: &[(&str, Result<&[(&str, &str)], usize>)] = &[
("up 1", Ok(&[("name", "up"), ("value", "1")])),
(
r#"http_requests_total{method="post",code="200"} 1027 1395066363000"#,
Ok(&[
("labels.method", "post"),
("labels.code", "200"),
("name", "http_requests_total"),
("value", "1027"),
("timestamp", "1395066363000"),
]),
),
(
" metric_without_timestamp_and_labels\t12.47 ",
Ok(&[
("name", "metric_without_timestamp_and_labels"),
("value", "12.47"),
]),
),
(
r#"msdos_file_access_time_seconds{path="C:\\DIR\\FILE.TXT",error="Cannot find file:\n\"FILE.TXT\""} 1.458255915e9"#,
Ok(&[
("labels.path", r"C:\DIR\FILE.TXT"),
("labels.error", "Cannot find file:\n\"FILE.TXT\""),
("name", "msdos_file_access_time_seconds"),
("value", "1.458255915e9"),
]),
),
(
r#"rpc_duration_seconds{quantile="0.5",} NaN"#,
Ok(&[
("labels.quantile", "0.5"),
("name", "rpc_duration_seconds"),
("value", "NaN"),
]),
),
("x +Inf", Ok(&[("name", "x"), ("value", "+Inf")])),
(
"x -Inf -12",
Ok(&[("name", "x"), ("value", "-Inf"), ("timestamp", "-12")]),
),
("x{} 1\r", Ok(&[("name", "x"), ("value", "1")])),
(
"ns:metric_name 3",
Ok(&[("name", "ns:metric_name"), ("value", "3")]),
),
(
r#"{"my.metric", "my.label"="a", b="c"} 2"#,
Ok(&[
(r#"labels["my.label"]"#, "a"),
("labels.b", "c"),
("name", "my.metric"),
("value", "2"),
]),
),
(
r#"foo_bucket{le="0.5"} 3 1520879607.789 # {trace_id="oHg5SJYRHA0"} 9.8 1520879607.789"#,
Ok(&[
("labels.le", "0.5"),
("name", "foo_bucket"),
("value", "3"),
("timestamp", "1520879607.789"),
("exemplar.labels.trace_id", "oHg5SJYRHA0"),
("exemplar.value", "9.8"),
("exemplar.timestamp", "1520879607.789"),
]),
),
(
r#"foo_total 17 # {id="a"} 1"#,
Ok(&[
("name", "foo_total"),
("value", "17"),
("exemplar.labels.id", "a"),
("exemplar.value", "1"),
]),
),
(
"# HELP http_requests_total The total number\\nof requests \\\\ \\x.",
Ok(&[
("name", "http_requests_total"),
("help", "The total number\nof requests \\ \\x."),
]),
),
(
"# TYPE http_requests_total counter",
Ok(&[("name", "http_requests_total"), ("type", "counter")]),
),
(
"# UNIT foo_seconds seconds",
Ok(&[("name", "foo_seconds"), ("unit", "seconds")]),
),
("# HELP empty", Ok(&[("name", "empty"), ("help", "")])),
(
r#"# TYPE "my.metric" gauge"#,
Ok(&[("name", "my.metric"), ("type", "gauge")]),
),
("", Ok(&[])),
(" \r", Ok(&[])),
("# a comment", Ok(&[])),
("#nospace TYPE x counter", Ok(&[])),
("# EOF", Ok(&[])),
("# TYPE x countre", Err(9)),
("# TYPE", Err(6)),
("# HELP 9x text", Err(7)),
("up", Err(2)),
("up one", Err(3)),
("up 1 2 3", Err(7)),
("up 1 soon", Err(5)),
(r#"up{a="1"b="2"} 1"#, Err(8)),
("up{a=1} 1", Err(5)),
(r#"up{a="1} 1"#, Err(5)),
("up{a} 1", Err(3)),
(r#"up{"q"} 1"#, Err(3)),
(r#"{a="1"} 1"#, Err(0)),
("{} 1", Err(0)),
("9up 1", Err(0)),
(
r#"up{a="\xff"} 1"#,
Ok(&[("labels.a", "\\xff"), ("name", "up"), ("value", "1")]),
),
("up 1 # trace", Err(7)),
("up 1 # {a=\"b\"}", Err(14)),
];
let p = Prometheus::new();
assert_eq!(p.name(), "prometheus");
for (line, expected) in table {
let mut out = Fields::new();
match (p.parse(line.as_bytes(), &mut out), expected) {
(Ok(Parsed::NoMatch), Ok([])) => assert!(out.is_empty(), "{line}"),
(Ok(Parsed::Done), Ok(w)) => assert_eq!(rows(&out), want(w), "{line}"),
(Err(ParseError::Malformed { offset, .. }), Err(at)) => {
assert_eq!(offset, *at, "{line}");
assert!(out.is_empty(), "{line} wrote {:?}", rows(&out));
}
(got, _) => panic!("{line}: {got:?} {:?}", rows(&out)),
}
}
}
#[test]
fn a_label_value_that_is_not_utf8_is_refused() {
let mut out = Fields::new();
let got = Prometheus::new().parse(b"up{a=\"\xff\"} 1", &mut out);
assert!(
matches!(got, Err(ParseError::Malformed { offset: 6, .. })),
"{got:?}"
);
assert!(out.is_empty());
}
#[test]
fn values_borrow_unless_unescaped() {
let mut out = Fields::new();
Prometheus::new()
.parse(br#"up{a="plain",b="x\ny"} 1 2"#, &mut out)
.unwrap();
for (name, borrowed) in [
("labels.a", true),
("labels.b", false),
("name", true),
("value", true),
] {
let value = out.get(name).unwrap();
assert_eq!(matches!(value.bytes, Cow::Borrowed(_)), borrowed, "{name}");
}
assert_eq!(out.get("value").unwrap().hint, Hint::Float);
assert_eq!(out.get("timestamp").unwrap().hint, Hint::Int);
}
#[test]
fn the_reader_types_each_sample_of_its_family() {
let exposition = [
("# HELP rpc_seconds RPC latency.", Line::Directive),
("# TYPE rpc_seconds summary", Line::Directive),
("# UNIT rpc_seconds seconds", Line::Directive),
(r#"rpc_seconds{quantile="0.5"} 4773"#, Line::Sample(4)),
("rpc_seconds_sum 1.7560473e+07", Line::Sample(3)),
("rpc_seconds_count 2693", Line::Sample(3)),
("rpc_seconds_bucket 1", Line::Sample(2)),
("", Line::Comment),
("# TYPE req counter", Line::Directive),
("req_total 3", Line::Sample(3)),
("req_created 1", Line::Sample(3)),
("other 1", Line::Sample(2)),
("# HELP up Whether it's up.", Line::Directive),
("up 1", Line::Sample(2)),
("# EOF", Line::Comment),
];
let mut reader = PrometheusReader::new();
for (line, kind) in exposition {
let mut out = Fields::new();
let got = reader.line(line.as_bytes(), &mut out).unwrap();
assert_eq!(got, kind, "{line}");
if let Line::Sample(n) = got {
assert_eq!(out.len(), n, "{line}");
} else {
assert!(out.is_empty(), "{line}");
}
if line.starts_with("rpc_seconds") && !line.contains("bucket") {
let family = reader.family().unwrap();
assert_eq!(family.help.as_deref(), Some("RPC latency."));
assert_eq!(family.unit.as_deref(), Some("seconds"));
assert_eq!(
out.get("type").map(|v| &*v.bytes),
Some(&b"summary"[..]),
"{line}"
);
}
}
let family = reader.family().unwrap();
assert_eq!((family.name.as_str(), family.kind), ("up", None));
assert_eq!(family.help.as_deref(), Some("Whether it's up."));
}
#[test]
fn a_broken_line_leaves_the_reader_as_it_was() {
let mut reader = PrometheusReader::new();
let mut out = Fields::new();
reader.line(b"# TYPE a gauge", &mut out).unwrap();
let before = reader.clone();
for line in ["# TYPE b nonsense", "a{x=\"1\" 1", "a 1 2 3"] {
assert!(reader.line(line.as_bytes(), &mut out).is_err(), "{line}");
assert!(out.is_empty(), "{line}");
assert_eq!(reader, before, "{line}");
}
}
type Sample = (String, HashMap<String, String>, f64, Option<i64>);
fn ours(text: &str) -> Vec<Sample> {
let mut reader = PrometheusReader::new();
let mut all = Vec::new();
for line in text.lines() {
let mut out = Fields::new();
if let Line::Sample(_) = reader.line(line.as_bytes(), &mut out).unwrap() {
let text = |n: &str| {
out.get(n)
.map(|v| String::from_utf8_lossy(&v.bytes).into_owned())
};
let labels = out
.as_slice()
.iter()
.filter_map(|(k, v)| {
let label = k.strip_prefix("labels.")?;
Some((
label.to_owned(),
String::from_utf8_lossy(&v.bytes).into_owned(),
))
})
.collect();
let value: f64 = text("value").unwrap().to_lowercase().parse().unwrap();
let at = text("timestamp").map(|t| t.parse::<i64>().unwrap());
all.push((text("name").unwrap(), labels, value, at));
}
}
all
}
proptest! {
#[test]
fn samples_read_back_as_written(
samples in prop::collection::vec((
"[a-z_][a-z0-9_]{0,8}",
prop::collection::btree_map("[a-z_][a-z0-9_]{0,5}", "[a-z0-9 ./-]{0,6}", 0..4),
prop::sample::select(&["0", "1", "-3", "1.5", "2e3", "NaN", "+Inf", "-Inf", "0.001"][..]),
prop::option::of(1_i64..2_000_000_000_000),
), 1..8),
) {
let mut text = String::new();
for (name, labels, value, at) in &samples {
text.push_str(name);
if !labels.is_empty() {
let body: Vec<String> = labels.iter().map(|(k, v)| format!("{k}=\"{v}\"")).collect();
text.push('{');
text.push_str(&body.join(","));
text.push('}');
}
text.push(' ');
text.push_str(value);
if let Some(at) = at {
let _ = write!(text, " {at}");
}
text.push('\n');
}
let got = ours(&text);
prop_assert_eq!(got.len(), samples.len());
for (g, (name, labels, value, at)) in got.iter().zip(&samples) {
let want: f64 = value.to_lowercase().parse().unwrap();
let labels: HashMap<String, String> =
labels.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
prop_assert_eq!(&g.0, name);
prop_assert_eq!(&g.1, &labels);
prop_assert_eq!(g.2.to_bits(), want.to_bits());
prop_assert_eq!(g.3, *at);
}
}
#[test]
fn any_line_parses_or_writes_nothing(line in r#"[a-z{}=",# \\.0-9\t]{0,30}"#) {
let mut out = Fields::new();
if Prometheus::new().parse(line.as_bytes(), &mut out).is_err() {
prop_assert!(out.is_empty());
}
}
}