about summary refs log tree commit diff
path: root/src/tools/rust-analyzer/crates/query-group-macro/tests/logger_db.rs
blob: 71af63a0d3b8b20c08ff69869bb4f3edd04b6ec0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use std::sync::{Arc, Mutex};

#[salsa_macros::db]
#[derive(Clone)]
pub(crate) struct LoggerDb {
    storage: salsa::Storage<Self>,
    logger: Logger,
}

impl Default for LoggerDb {
    fn default() -> Self {
        let logger = Logger::default();
        Self {
            storage: salsa::Storage::new(Some(Box::new({
                let logger = logger.clone();
                move |event| match event.kind {
                    salsa::EventKind::WillExecute { .. }
                    | salsa::EventKind::WillCheckCancellation
                    | salsa::EventKind::DidValidateMemoizedValue { .. }
                    | salsa::EventKind::WillDiscardStaleOutput { .. }
                    | salsa::EventKind::DidDiscard { .. } => {
                        logger.logs.lock().unwrap().push(format!("salsa_event({:?})", event.kind));
                    }
                    _ => {}
                }
            }))),
            logger,
        }
    }
}

#[derive(Default, Clone)]
struct Logger {
    logs: Arc<Mutex<Vec<String>>>,
}

#[salsa_macros::db]
impl salsa::Database for LoggerDb {}

impl LoggerDb {
    /// Log an event from inside a tracked function.
    pub(crate) fn push_log(&self, string: String) {
        self.logger.logs.lock().unwrap().push(string);
    }

    /// Asserts what the (formatted) logs should look like,
    /// clearing the logged events. This takes `&mut self` because
    /// it is meant to be run from outside any tracked functions.
    pub(crate) fn assert_logs(&self, expected: expect_test::Expect) {
        let logs = std::mem::take(&mut *self.logger.logs.lock().unwrap());
        expected.assert_eq(&format!("{logs:#?}"));
    }
}

/// Test the logger database.
///
/// This test isn't very interesting, but it *does* remove a dead code warning.
#[test]
fn test_logger_db() {
    let db = LoggerDb::default();
    db.push_log("test".to_string());
    db.assert_logs(expect_test::expect![
        r#"
        [
            "test",
        ]"#
    ]);
}