Skip to main content

micromegas_tracing/
test_utils.rs

1//! Test utilities for in-memory tracing in unit tests
2
3use crate::dispatch::flush_log_buffer;
4use crate::dispatch::{force_uninit, init_event_dispatch, shutdown_dispatch};
5use crate::event::in_memory_sink::InMemorySink;
6use crate::logs::LogMsgQueueAny;
7use micromegas_transit::HeterogeneousQueue;
8use std::collections::HashMap;
9use std::sync::Arc;
10
11/// RAII guard for in-memory tracing that handles cleanup
12///
13/// This guard automatically calls shutdown_dispatch() and force_uninit()
14/// when dropped, ensuring proper cleanup between tests.
15///
16/// # Important
17/// Tests using this guard MUST be marked with `#[serial]` since they
18/// share global state through init_event_dispatch.
19pub struct InMemoryTracingGuard {
20    pub sink: Arc<InMemorySink>,
21}
22
23impl Default for InMemoryTracingGuard {
24    fn default() -> Self {
25        Self::new()
26    }
27}
28
29impl InMemoryTracingGuard {
30    pub fn new() -> Self {
31        let sink = Arc::new(InMemorySink::new());
32        init_event_dispatch(1024, 1024, 1024, sink.clone(), HashMap::new(), true) // Enable CPU tracing for tests
33            .expect("Failed to initialize event dispatch");
34        Self { sink }
35    }
36}
37
38impl Drop for InMemoryTracingGuard {
39    fn drop(&mut self) {
40        shutdown_dispatch();
41        unsafe { force_uninit() };
42    }
43}
44
45/// Initialize in-memory tracing for unit tests
46///
47/// # Important
48/// Tests using this function MUST be marked with `#[serial]` since they
49/// share global state through init_event_dispatch.
50///
51/// # Example
52/// ```rust
53/// use micromegas_tracing::test_utils::init_in_memory_tracing;
54/// use serial_test::serial;
55///
56/// // In your test file:
57/// // #[test]
58/// // #[serial]
59/// fn test_example() {
60///     let guard = init_in_memory_tracing();
61///     // Use tracing macros: info!(), debug!(), span_scope!(), etc.
62///     // Verify results in guard.sink.state
63///     // Automatic cleanup when guard is dropped
64/// }
65/// ```
66pub fn init_in_memory_tracing() -> InMemoryTracingGuard {
67    InMemoryTracingGuard::new()
68}
69
70/// A log line read back from an [`InMemorySink`].
71pub struct CapturedLog {
72    pub msg: String,
73    /// Dynamic properties of a tagged log; empty for untagged lines.
74    pub properties: Vec<(String, String)>,
75}
76
77impl CapturedLog {
78    /// First property named `name`.
79    pub fn property(&self, name: &str) -> Option<&str> {
80        self.properties
81            .iter()
82            .find(|(k, _)| k == name)
83            .map(|(_, v)| v.as_str())
84    }
85}
86
87/// Flushes the log buffer, then returns every static-string, formatted and tagged log recorded
88/// in `sink`, in emission order. Template events are not covered.
89pub fn collect_logs(sink: &InMemorySink) -> Vec<CapturedLog> {
90    flush_log_buffer();
91    let state = sink.state.lock().expect("sink lock");
92    let mut out = vec![];
93    for block in &state.log_blocks {
94        for event in block.events.iter() {
95            let (msg, set_id) = match event {
96                LogMsgQueueAny::LogStaticStrEvent(e) => (e.desc.fmt_str.to_owned(), None),
97                LogMsgQueueAny::LogStringEvent(e) => (e.msg.0.clone(), None),
98                LogMsgQueueAny::TaggedLogStaticStrEvent(e) => {
99                    (e.desc.fmt_str.to_owned(), Some(e.properties))
100                }
101                LogMsgQueueAny::TaggedLogString(e) => (e.msg.0.clone(), Some(e.properties)),
102                _ => continue,
103            };
104            let properties = set_id
105                .map(|id| {
106                    block
107                        .dyn_deps
108                        .set_properties(id)
109                        .into_iter()
110                        .map(|(k, v)| (k.to_owned(), v.to_owned()))
111                        .collect()
112                })
113                .unwrap_or_default();
114            out.push(CapturedLog { msg, properties });
115        }
116    }
117    out
118}