xref: /aosp_15_r20/external/pigweed/pw_log/rust/println_backend_test.rs (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2024 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 // The Rust test framework uses `set_output_capture()` to redirect stdio output.
16 // Since we need to capture stdout in this test, we must use this API as well.
17 #![feature(internal_output_capture)]
18 mod backend_tests;
19 
20 // Runs `action` while capturing `println!` output and returns the
21 // captured output.
22 #[cfg(test)]
run_with_capture<F: FnOnce()>(action: F) -> String23 fn run_with_capture<F: FnOnce()>(action: F) -> String {
24     // Use statements here instead of at the module level to scope them to the
25     // above #[cfg(test)]
26     use std::sync::{Arc, Mutex};
27 
28     let output = Arc::new(Mutex::new(Vec::new()));
29     let old_capture = std::io::set_output_capture(Some(output.clone()));
30 
31     action();
32 
33     std::io::set_output_capture(old_capture);
34     let output_data = output.lock().unwrap();
35     String::from_utf8((*output_data).to_vec()).unwrap()
36 }
37