Skip to main content

apache_avro_test_helper/
lib.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18pub mod data;
19pub mod logger;
20
21use core::any::type_name;
22use core::cell::RefCell;
23use core::fmt::{Debug, Display};
24#[cfg(not(target_arch = "wasm32"))]
25use ctor::{ctor, dtor};
26
27thread_local! {
28    // The unit tests run in parallel
29    // We need to keep the log messages in a thread-local variable
30    // and clear them after assertion
31    pub(crate) static LOG_MESSAGES: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
32}
33
34#[cfg(not(target_arch = "wasm32"))]
35#[ctor(unsafe)]
36fn before_all() {
37    // better stacktraces in tests
38    better_panic::Settings::new()
39        .most_recent_first(true)
40        .lineno_suffix(false)
41        .backtrace_first(true)
42        .install();
43
44    // enable logging in tests
45    logger::install();
46}
47
48#[cfg(not(target_arch = "wasm32"))]
49#[dtor(unsafe)]
50fn after_all() {
51    logger::clear_log_messages();
52}
53
54/// A custom error type for tests.
55#[derive(Debug)]
56pub struct TestError;
57
58/// A converter of any error into [`TestError`].
59///
60/// It is used to print better error messages in the tests.
61/// Borrowed from <https://bluxte.net/musings/2023/01/08/improving_failure_messages_rust_tests/>.
62// The Display bound is needed so that the `From` implementation doesn't
63// apply to `TestError` itself.
64impl<Err: Display + Debug> From<Err> for TestError {
65    #[track_caller]
66    fn from(err: Err) -> Self {
67        panic!("{}: {:?}", type_name::<Err>(), err);
68    }
69}
70
71pub type TestResult = Result<(), TestError>;
72
73/// Does nothing. Just loads the crate.
74/// Should be used in the integration tests, because they do not use [dev-dependencies]
75/// and do not auto-load this crate.
76pub const fn init() {}