nautilus_common/
testing.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
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,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Common test related helper functions.
17
18use std::{
19    future::Future,
20    thread,
21    time::{Duration, Instant},
22};
23
24use nautilus_core::UUID4;
25use nautilus_model::identifiers::TraderId;
26
27use crate::logging::{
28    init_logging,
29    logger::{LogGuard, LoggerConfig},
30    writer::FileWriterConfig,
31};
32
33pub fn init_logger_for_testing(stdout_level: Option<log::LevelFilter>) -> anyhow::Result<LogGuard> {
34    let mut config = LoggerConfig::default();
35    config.stdout_level = stdout_level.unwrap_or(log::LevelFilter::Trace);
36    init_logging(
37        TraderId::default(),
38        UUID4::new(),
39        config,
40        FileWriterConfig::default(),
41    )
42}
43
44/// Repeatedly evaluates a condition with a delay until it becomes true or a timeout occurs.
45///
46/// # Panics
47///
48/// This function will panic if the timeout duration is exceeded without the condition being met.
49///
50/// # Examples
51///
52/// ```
53/// use std::time::Duration;
54/// use std::thread;
55/// use nautilus_common::testing::wait_until;
56///
57/// let start_time = std::time::Instant::now();
58/// let timeout = Duration::from_secs(5);
59///
60/// wait_until(|| {
61///     if start_time.elapsed().as_secs() > 2 {
62///         true
63///     } else {
64///         false
65///     }
66/// }, timeout);
67/// ```
68///
69/// In the above example, the `wait_until` function will block for at least 2 seconds, as that's how long
70/// it takes for the condition to be met. If the condition was not met within 5 seconds, it would panic.
71pub fn wait_until<F>(mut condition: F, timeout: Duration)
72where
73    F: FnMut() -> bool,
74{
75    let start_time = Instant::now();
76
77    loop {
78        if condition() {
79            break;
80        }
81
82        assert!(
83            start_time.elapsed() <= timeout,
84            "Timeout waiting for condition"
85        );
86
87        thread::sleep(Duration::from_millis(100));
88    }
89}
90
91pub async fn wait_until_async<F, Fut>(mut condition: F, timeout: Duration)
92where
93    F: FnMut() -> Fut,
94    Fut: Future<Output = bool>,
95{
96    let start_time = Instant::now();
97
98    loop {
99        if condition().await {
100            break;
101        }
102
103        assert!(
104            start_time.elapsed() <= timeout,
105            "Timeout waiting for condition"
106        );
107
108        tokio::time::sleep(Duration::from_millis(100)).await;
109    }
110}