kitsune2_test_utils/
lib.rs

1#![deny(missing_docs)]
2//! Test utilities to help with testing Kitsune2.
3
4use rand::RngCore;
5
6pub mod agent;
7pub mod bootstrap;
8pub mod id;
9pub mod noop_bootstrap;
10pub mod space;
11
12/// Enable tracing with the RUST_LOG environment variable.
13///
14/// This is intended to be used in tests, so it defaults to DEBUG level.
15pub fn enable_tracing() {
16    enable_tracing_with_default_level(tracing::Level::DEBUG);
17}
18
19/// Enable tracing with the RUST_LOG environment variable.
20pub fn enable_tracing_with_default_level(level: tracing::Level) {
21    let _ = tracing_subscriber::fmt()
22        .with_test_writer()
23        .with_env_filter(
24            tracing_subscriber::EnvFilter::builder()
25                .with_default_directive(level.into())
26                .from_env_lossy(),
27        )
28        .try_init();
29}
30
31/// Create random bytes of a specified length.
32pub fn random_bytes(length: u16) -> Vec<u8> {
33    let mut rng = rand::thread_rng();
34    let mut bytes = vec![0; length as usize];
35    rng.fill_bytes(&mut bytes);
36    bytes
37}
38
39/// Repeat a code block after a pause until a timeout has elapsed.
40/// The default timeout is 100 ms.
41#[macro_export]
42macro_rules! iter_check {
43    ($timeout_ms:literal, $sleep_ms:literal, $code:block) => {
44        tokio::time::timeout(
45            std::time::Duration::from_millis($timeout_ms),
46            async {
47                loop {
48                    tokio::time::sleep(std::time::Duration::from_millis(
49                        $sleep_ms,
50                    ))
51                    .await;
52                    $code
53                }
54            },
55        )
56        .await
57        .unwrap();
58    };
59
60    ($timeout_ms:literal, $code:block) => {
61        iter_check!($timeout_ms, 1, $code)
62    };
63
64    ($code:block) => {
65        iter_check!(100, $code)
66    };
67}