micromegas_tracing/
test_utils.rs

1//! Test utilities for in-memory tracing in unit tests
2
3use crate::dispatch::{force_uninit, init_event_dispatch, shutdown_dispatch};
4use crate::event::in_memory_sink::InMemorySink;
5use std::collections::HashMap;
6use std::sync::Arc;
7
8/// RAII guard for in-memory tracing that handles cleanup
9///
10/// This guard automatically calls shutdown_dispatch() and force_uninit()
11/// when dropped, ensuring proper cleanup between tests.
12///
13/// # Important
14/// Tests using this guard MUST be marked with `#[serial]` since they
15/// share global state through init_event_dispatch.
16pub struct InMemoryTracingGuard {
17    pub sink: Arc<InMemorySink>,
18}
19
20impl Default for InMemoryTracingGuard {
21    fn default() -> Self {
22        Self::new()
23    }
24}
25
26impl InMemoryTracingGuard {
27    pub fn new() -> Self {
28        let sink = Arc::new(InMemorySink::new());
29        init_event_dispatch(1024, 1024, 1024, sink.clone(), HashMap::new(), true) // Enable CPU tracing for tests
30            .expect("Failed to initialize event dispatch");
31        Self { sink }
32    }
33}
34
35impl Drop for InMemoryTracingGuard {
36    fn drop(&mut self) {
37        shutdown_dispatch();
38        unsafe { force_uninit() };
39    }
40}
41
42/// Initialize in-memory tracing for unit tests
43///
44/// # Important
45/// Tests using this function MUST be marked with `#[serial]` since they
46/// share global state through init_event_dispatch.
47///
48/// # Example
49/// ```rust
50/// use micromegas_tracing::test_utils::init_in_memory_tracing;
51/// use serial_test::serial;
52///
53/// // In your test file:
54/// // #[test]
55/// // #[serial]
56/// fn test_example() {
57///     let guard = init_in_memory_tracing();
58///     // Use tracing macros: info!(), debug!(), span_scope!(), etc.
59///     // Verify results in guard.sink.state
60///     // Automatic cleanup when guard is dropped
61/// }
62/// ```
63pub fn init_in_memory_tracing() -> InMemoryTracingGuard {
64    InMemoryTracingGuard::new()
65}