Skip to main content

nautilus_common/
testing.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 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
18#[cfg(feature = "live")]
19use std::future::Future;
20use std::{
21    thread,
22    time::{Duration, Instant},
23};
24
25use nautilus_core::UUID4;
26use nautilus_model::{identifiers::TraderId, stubs::TestDefault};
27
28use crate::logging::{
29    init_logging,
30    logger::{LogGuard, LoggerConfig},
31    writer::FileWriterConfig,
32};
33
34/// # Errors
35///
36/// Returns an error if initializing the logger fails.
37pub fn init_logger_for_testing(stdout_level: Option<log::LevelFilter>) -> anyhow::Result<LogGuard> {
38    let config = LoggerConfig {
39        stdout_level: stdout_level.unwrap_or(log::LevelFilter::Trace),
40        ..Default::default()
41    };
42    init_logging(
43        TraderId::test_default(),
44        UUID4::new(),
45        config,
46        FileWriterConfig::default(),
47    )
48}
49
50/// Repeatedly evaluates a condition with a delay until it becomes true or a timeout occurs.
51///
52/// # Panics
53///
54/// This function panics if the timeout duration is exceeded without the condition being met.
55///
56/// # Examples
57///
58/// ```
59/// use std::{thread, time::Duration};
60///
61/// use nautilus_common::testing::wait_until;
62///
63/// let start_time = std::time::Instant::now();
64/// let timeout = Duration::from_secs(5);
65///
66/// wait_until(
67///     || {
68///         if start_time.elapsed().as_secs() > 2 {
69///             true
70///         } else {
71///             false
72///         }
73///     },
74///     timeout,
75/// );
76/// ```
77///
78/// In the above example, the `wait_until` function will block for at least 2 seconds, as that's how long
79/// it takes for the condition to be met. If the condition was not met within 5 seconds, it would panic.
80pub fn wait_until<F>(mut condition: F, timeout: Duration)
81where
82    F: FnMut() -> bool,
83{
84    let start_time = Instant::now(); // dst-ok: test helper timer; uses real time by design
85
86    loop {
87        if condition() {
88            break;
89        }
90
91        assert!(
92            start_time.elapsed() <= timeout,
93            "Timeout waiting for condition after {:.1}s (limit {:.1}s)",
94            start_time.elapsed().as_secs_f64(),
95            timeout.as_secs_f64(),
96        );
97
98        thread::sleep(Duration::from_millis(100));
99    }
100}
101
102/// # Panics
103///
104/// Panics if the timeout duration is exceeded without the condition being met.
105#[cfg(feature = "live")]
106pub async fn wait_until_async<F, Fut>(mut condition: F, timeout: Duration)
107where
108    F: FnMut() -> Fut,
109    Fut: Future<Output = bool>,
110{
111    let start_time = Instant::now(); // dst-ok: test helper timer; uses real time by design
112
113    loop {
114        if condition().await {
115            break;
116        }
117
118        assert!(
119            start_time.elapsed() <= timeout,
120            "Timeout waiting for condition after {:.1}s (limit {:.1}s)",
121            start_time.elapsed().as_secs_f64(),
122            timeout.as_secs_f64(),
123        );
124
125        tokio::time::sleep(Duration::from_millis(100)).await;
126    }
127}