netstack3_base/testutil/
misc.rs

1// Copyright 2024 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Miscellaneous test utilities used in netstack3.
6//!
7//! # Note to developers
8//!
9//! Please refrain from adding types to this module, keep this only to
10//! freestanding functions. If you require a new type, create a module for it.
11
12use alloc::vec::Vec;
13use core::fmt::Debug;
14use core::sync::atomic::{self, AtomicBool};
15
16/// Install a logger for tests.
17///
18/// Call this method at the beginning of the test for which logging is desired.
19/// This function sets global program state, so all tests that run after this
20/// function is called will use the logger.
21pub fn set_logger_for_test() {
22    struct Logger;
23
24    impl log::Log for Logger {
25        fn enabled(&self, _metadata: &log::Metadata<'_>) -> bool {
26            true
27        }
28
29        fn log(&self, record: &log::Record<'_>) {
30            teststd::println!("[{}] ({}) {}", record.level(), record.target(), record.args())
31        }
32
33        fn flush(&self) {}
34    }
35
36    static LOGGER_ONCE: AtomicBool = AtomicBool::new(true);
37
38    // log::set_logger will panic if called multiple times.
39    if LOGGER_ONCE.swap(false, atomic::Ordering::AcqRel) {
40        log::set_logger(&Logger).unwrap();
41        log::set_max_level(log::LevelFilter::Trace);
42    }
43}
44
45/// Asserts that an iterable object produces zero items.
46///
47/// `assert_empty` drains `into_iter.into_iter()` and asserts that zero
48/// items are produced. It panics with a message which includes the produced
49/// items if this assertion fails.
50#[track_caller]
51pub fn assert_empty<I: IntoIterator>(into_iter: I)
52where
53    I::Item: Debug,
54{
55    // NOTE: Collecting into a `Vec` is cheap in the happy path because
56    // zero-capacity vectors are guaranteed not to allocate.
57    let vec = into_iter.into_iter().collect::<Vec<_>>();
58    assert!(vec.is_empty(), "vec={vec:?}");
59}