mz_ore/test.rs
1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License in the LICENSE file at the
6// root of this repository, or online at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Test utilities.
17
18use std::sync::Once;
19use std::sync::mpsc::{self, RecvTimeoutError};
20use std::thread;
21use std::time::Duration;
22
23use anyhow::bail;
24use tracing_subscriber::{EnvFilter, FmtSubscriber};
25
26static LOG_INIT: Once = Once::new();
27
28/// Initialize global logger, using the [`tracing_subscriber`] crate, with
29/// sensible defaults.
30///
31/// It is safe to call `init_logging` multiple times. Since `cargo test` does
32/// not run tests in any particular order, each must call `init_logging`.
33pub fn init_logging() {
34 init_logging_default("info");
35}
36
37/// Initialize global logger, using the [`tracing_subscriber`] crate.
38///
39/// The default log level will be set to the value passed in.
40///
41/// It is safe to call `init_logging_level` multiple times. Since `cargo test` does
42/// not run tests in any particular order, each must call `init_logging`.
43pub fn init_logging_default(level: &str) {
44 LOG_INIT.call_once(|| {
45 let filter = EnvFilter::try_from_env("MZ_TEST_LOG_FILTER")
46 .or_else(|_| EnvFilter::try_new(level))
47 .unwrap();
48 FmtSubscriber::builder()
49 .with_env_filter(filter)
50 .with_test_writer()
51 .init();
52 });
53}
54
55/// Runs a function with a timeout.
56///
57/// The provided closure is invoked on a thread. If the thread completes
58/// normally within the provided `duration`, its result is returned. If the
59/// thread panics within the provided `duration`, the panic is propagated to the
60/// thread calling `timeout`. Otherwise, a timeout error is returned.
61///
62/// Note that if the invoked function does not complete in the timeout, it is
63/// not killed; it is left to wind down normally. Therefore this function is
64/// only appropriate in tests, where the resource leak doesn't matter.
65pub fn timeout<F, T>(duration: Duration, f: F) -> Result<T, anyhow::Error>
66where
67 F: FnOnce() -> Result<T, anyhow::Error> + Send + 'static,
68 T: Send + 'static,
69{
70 // Use the drop of `tx` to indicate that the thread is finished. This
71 // ensures that `tx` is dropped even if `f` panics. No actual value is ever
72 // sent on `tx`.
73 let (tx, rx) = mpsc::channel();
74 let thread = thread::spawn(|| {
75 let _tx = tx;
76 f()
77 });
78 match rx.recv_timeout(duration) {
79 Ok(()) => unreachable!(),
80 Err(RecvTimeoutError::Disconnected) => thread.join().unwrap(),
81 Err(RecvTimeoutError::Timeout) => bail!("thread timed out"),
82 }
83}