]> git.proxmox.com Git - rustc.git/blob - vendor/tracing/tests/filter_caching_is_lexically_scoped.rs
New upstream version 1.62.1+dfsg1
[rustc.git] / vendor / tracing / tests / filter_caching_is_lexically_scoped.rs
1 // Tests that depend on a count of the number of times their filter is evaluated
2 // can't exist in the same file with other tests that add subscribers to the
3 // registry. The registry was changed so that each time a new dispatcher is
4 // added all filters are re-evaluated. The tests being run only in separate
5 // threads with shared global state lets them interfere with each other
6
7 #[cfg(not(feature = "std"))]
8 extern crate std;
9
10 use tracing::{span, Level};
11 use tracing_mock::*;
12
13 use std::sync::{
14 atomic::{AtomicUsize, Ordering},
15 Arc,
16 };
17
18 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
19 #[test]
20 fn filter_caching_is_lexically_scoped() {
21 pub fn my_great_function() -> bool {
22 span!(Level::TRACE, "emily").in_scope(|| true)
23 }
24
25 pub fn my_other_function() -> bool {
26 span!(Level::TRACE, "frank").in_scope(|| true)
27 }
28
29 let count = Arc::new(AtomicUsize::new(0));
30 let count2 = count.clone();
31
32 let subscriber = subscriber::mock()
33 .with_filter(move |meta| match meta.name() {
34 "emily" | "frank" => {
35 count2.fetch_add(1, Ordering::Relaxed);
36 true
37 }
38 _ => false,
39 })
40 .run();
41
42 // Since this test is in its own file anyway, we can do this. Thus, this
43 // test will work even with no-std.
44 tracing::subscriber::set_global_default(subscriber).unwrap();
45
46 // Call the function once. The filter should be re-evaluated.
47 assert!(my_great_function());
48 assert_eq!(count.load(Ordering::Relaxed), 1);
49
50 // Call the function again. The cached result should be used.
51 assert!(my_great_function());
52 assert_eq!(count.load(Ordering::Relaxed), 1);
53
54 assert!(my_other_function());
55 assert_eq!(count.load(Ordering::Relaxed), 2);
56
57 assert!(my_great_function());
58 assert_eq!(count.load(Ordering::Relaxed), 2);
59
60 assert!(my_other_function());
61 assert_eq!(count.load(Ordering::Relaxed), 2);
62
63 assert!(my_great_function());
64 assert_eq!(count.load(Ordering::Relaxed), 2);
65 }