Skip to content

Commit 2d0e075

Browse files
committed
Add test for skip_encoding_if
Signed-off-by: Cristian George ANDREI <[email protected]>
1 parent 4e3a2b2 commit 2d0e075

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

derive-encode/tests/lib.rs

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,61 @@ fn flatten() {
206206
assert_eq!(expected, buffer);
207207
}
208208

209+
#[test]
210+
fn skip_encoding_if() {
211+
fn skip_empty_string(s: &String) -> bool {
212+
s.is_empty()
213+
}
214+
215+
fn skip_zero(n: &u64) -> bool {
216+
*n == 0
217+
}
218+
219+
#[derive(EncodeLabelSet, Hash, Clone, Eq, PartialEq, Debug)]
220+
struct Labels {
221+
method: String,
222+
#[prometheus(skip_encoding_if = "skip_empty_string")]
223+
path: String,
224+
#[prometheus(skip_encoding_if = "skip_zero")]
225+
status_code: u64,
226+
user_id: u64,
227+
}
228+
229+
let mut registry = Registry::default();
230+
let family = Family::<Labels, Counter>::default();
231+
registry.register("my_counter", "This is my counter", family.clone());
232+
233+
family
234+
.get_or_create(&Labels {
235+
method: "GET".to_string(),
236+
path: "".to_string(), // This should be skipped
237+
status_code: 0, // This should be skipped
238+
user_id: 123,
239+
})
240+
.inc();
241+
242+
family
243+
.get_or_create(&Labels {
244+
method: "POST".to_string(),
245+
path: "/api/users".to_string(), // This should not be skipped
246+
status_code: 200, // This should not be skipped
247+
user_id: 456,
248+
})
249+
.inc();
250+
251+
let mut buffer = String::new();
252+
encode(&mut buffer, &registry).unwrap();
253+
254+
assert!(buffer.contains("# HELP my_counter This is my counter."));
255+
assert!(buffer.contains("# TYPE my_counter counter"));
256+
assert!(buffer.contains("my_counter_total{method=\"GET\",user_id=\"123\"} 1"));
257+
assert!(buffer.contains("my_counter_total{method=\"POST\",path=\"/api/users\",status_code=\"200\",user_id=\"456\"} 1"));
258+
assert!(buffer.contains("# EOF"));
259+
260+
assert!(!buffer.contains("path=\"\""));
261+
assert!(!buffer.contains("status_code=\"0\""));
262+
}
263+
209264
#[test]
210265
fn build() {
211266
let t = trybuild::TestCases::new();

0 commit comments

Comments
 (0)