Skip to main content

examples/
z_ignore_test_common.rs

1#[cfg(feature = "std")]
2extern crate std;
3
4extern crate alloc;
5use alloc::sync::Arc;
6
7use std::sync::Mutex;
8
9#[cfg(feature = "flecs_nightly_tests")]
10pub use capture_stdio::*;
11#[cfg(feature = "flecs_nightly_tests")]
12use std::io::{Error, set_output_capture};
13
14/// Wrap `std::io::set_output_capture`
15#[cfg(feature = "flecs_nightly_tests")]
16pub struct OutputCapture {
17    local_stream: Arc<Mutex<Vec<u8>>>,
18    original: Option<Arc<Mutex<Vec<u8>>>>,
19    restored: bool,
20}
21
22#[cfg(feature = "flecs_nightly_tests")]
23impl Capture for OutputCapture {
24    fn capture() -> Result<Self, Error> {
25        let local_stream = Arc::new(Mutex::new(vec![]));
26        let original = set_output_capture(Some(local_stream.clone()));
27        Ok(Self {
28            local_stream,
29            original,
30            restored: false,
31        })
32    }
33
34    fn restore(&mut self) {
35        assert!(!self.restored, "cannot restore it twice");
36
37        set_output_capture(self.original.clone());
38        self.restored = true;
39    }
40}
41
42#[cfg(feature = "flecs_nightly_tests")]
43impl OutputCapture {
44    /// Get the captured output
45    pub fn output(&self) -> Arc<Mutex<Vec<u8>>> {
46        self.local_stream.clone()
47    }
48
49    pub fn output_string(&self) -> String {
50        String::from_utf8(self.output().lock().unwrap().clone()).unwrap()
51    }
52
53    pub fn test(&self, name: String) {
54        let str_output = String::from_utf8(self.output().lock().unwrap().clone()).unwrap();
55        let mut settings = insta::Settings::clone_current();
56        #[allow(clippy::double_parens)]
57        settings._private_inner_mut().filters(
58            (vec![
59                (r"id:\s?(\d+)", "[ID]"),
60                (r"#(\d+)\s?", "#[ID] "),
61                (
62                    r#"Group deleted: \\"([^\\"]+)\\""#,
63                    "group deleted: redacted",
64                ),
65                // Redact JSON "id": number
66                (r#"\\"id\\":\s?\d+"#, r#""id": "[ID]""#),
67                // Redact (Identifier, Name)
68                (
69                    r#"- \(Identifier, Name\) ?: ?\d+"#,
70                    r#"- (Identifier, Name) : #[ID] "#,
71                ),
72            ]),
73        );
74        settings.set_prepend_module_to_snapshot(false);
75        settings.set_snapshot_suffix(name);
76        settings.set_snapshot_path("z_ignore_test_snapshots");
77        settings.bind(|| {
78            insta::assert_yaml_snapshot!(str_output);
79        });
80    }
81}
82
83#[cfg(feature = "flecs_nightly_tests")]
84impl Drop for OutputCapture {
85    fn drop(&mut self) {
86        if !self.restored {
87            self.restore();
88        }
89    }
90}