mithril_common/test_utils/
mod.rs

1//! Test utilities
2//!
3//! They contains:
4//! * A Open Api Spec tester
5//! * Some precomputed fake data and keys
6//! * A builder of [MithrilFixture] to generate signers alongside a stake distribution
7//!
8
9#[cfg(feature = "apispec")]
10#[cfg_attr(docsrs, doc(cfg(feature = "apispec")))]
11pub mod apispec;
12
13pub mod fake_data;
14pub mod fake_keys;
15
16mod cardano_transactions_builder;
17mod certificate_chain_builder;
18mod dir_eq;
19mod fixture_builder;
20mod memory_logger;
21mod mithril_fixture;
22mod precomputed_kes_key;
23mod temp_dir;
24
25#[cfg(feature = "test_http_server")]
26#[cfg_attr(docsrs, doc(cfg(feature = "test_http_server")))]
27pub mod test_http_server;
28
29pub use cardano_transactions_builder::CardanoTransactionsBuilder;
30pub use certificate_chain_builder::{
31    CertificateChainBuilder, CertificateChainBuilderContext, CertificateChainingMethod,
32};
33pub use dir_eq::*;
34pub use fixture_builder::{MithrilFixtureBuilder, StakeDistributionGenerationMethod};
35pub use memory_logger::*;
36pub use mithril_fixture::{MithrilFixture, SignerFixture};
37pub use temp_dir::*;
38#[cfg(test)]
39pub(crate) use utils::*;
40
41/// Compare two json strings ignoring keys order
42#[macro_export]
43macro_rules! assert_same_json {
44    ( $expected:expr, $actual:expr ) => {
45        assert_eq!(
46            serde_json::from_str::<serde_json::Value>($expected).unwrap(),
47            serde_json::from_str::<serde_json::Value>($actual).unwrap()
48        )
49    };
50}
51pub use assert_same_json;
52
53/// Compare two iterators ignoring the order
54pub fn equivalent_to<T, I1, I2>(a: I1, b: I2) -> bool
55where
56    T: PartialEq + Ord,
57    I1: IntoIterator<Item = T> + Clone,
58    I2: IntoIterator<Item = T> + Clone,
59{
60    let a = as_sorted_vec(a);
61    let b = as_sorted_vec(b);
62    a == b
63}
64
65/// Assert that two iterators are equivalent
66pub fn assert_equivalent<T, I1, I2>(a: I1, b: I2)
67where
68    T: PartialEq + Ord + std::fmt::Debug,
69    I1: IntoIterator<Item = T> + Clone,
70    I2: IntoIterator<Item = T> + Clone,
71{
72    let a = as_sorted_vec(a);
73    let b = as_sorted_vec(b);
74    assert_eq!(a, b);
75}
76
77fn as_sorted_vec<T: Ord, I: IntoIterator<Item = T> + Clone>(iter: I) -> Vec<T> {
78    let mut list: Vec<T> = iter.clone().into_iter().collect();
79    list.sort();
80    list
81}
82
83/// Return the path of the given function.
84/// If the last function is `f`, it is removed.
85/// The last `{{closure}}` is also removed.
86pub fn format_current_function_module<T>(f: T) -> &'static str {
87    fn type_name_of<T>(_: T) -> &'static str {
88        std::any::type_name::<T>()
89    }
90
91    let name = type_name_of(f);
92    let name = name.strip_suffix("::f").unwrap_or(name);
93    name.strip_suffix("::{{closure}}").unwrap_or(name)
94}
95
96/// Return a string representing the path of the given function.
97pub fn format_current_function_path<T>(f: T) -> String {
98    let name = format_current_function_module(f);
99    name.replace("::", "/")
100}
101
102/// Returns the name of the function that called this macro.
103#[macro_export]
104macro_rules! current_function {
105    () => {{
106        fn f() {}
107        let name = $crate::test_utils::format_current_function_module(f);
108        // The index found is the beginning of the '..', this is why we add 2.
109        let function_name_index = name.rfind("::").map(|index| index + 2).unwrap_or(0);
110
111        &name[function_name_index..]
112    }};
113}
114pub use current_function;
115
116/// Returns the path of the function that called this macro.
117#[macro_export]
118macro_rules! current_function_path {
119    () => {{
120        fn f() {}
121
122        std::path::PathBuf::from($crate::test_utils::format_current_function_path(f))
123    }};
124}
125pub use current_function_path;
126
127#[cfg(test)]
128mod utils {
129    use std::io;
130    use std::sync::Arc;
131    use std::{collections::HashSet, path::Path};
132
133    use slog::{Drain, Logger};
134    use slog_async::Async;
135    use slog_term::{CompactFormat, PlainDecorator};
136
137    use super::*;
138
139    pub struct TestLogger;
140
141    #[cfg(test)]
142    impl TestLogger {
143        fn from_writer<W: io::Write + Send + 'static>(writer: W) -> Logger {
144            let decorator = PlainDecorator::new(writer);
145            let drain = CompactFormat::new(decorator).build().fuse();
146            let drain = Async::new(drain).build().fuse();
147            Logger::root(Arc::new(drain), slog::o!())
148        }
149
150        pub fn stdout() -> Logger {
151            Self::from_writer(slog_term::TestStdoutWriter)
152        }
153
154        pub fn memory() -> (Logger, MemoryDrainForTestInspector) {
155            let (drain, inspector) = MemoryDrainForTest::new();
156            (Logger::root(drain.fuse(), slog::o!()), inspector)
157        }
158    }
159
160    #[test]
161    fn test_equivalent_to() {
162        assert!(equivalent_to(vec![1, 2, 3], vec![3, 2, 1]));
163        assert!(equivalent_to(vec![1, 2, 3], vec![2, 1, 3]));
164        assert!(!equivalent_to(vec![1, 2, 3], vec![3, 2, 1, 4]));
165        assert!(!equivalent_to(vec![1, 2, 3], vec![3, 2]));
166
167        assert!(equivalent_to([1, 2, 3], vec![3, 2, 1]));
168        assert!(equivalent_to(&[1, 2, 3], &vec![3, 2, 1]));
169        assert!(equivalent_to([1, 2, 3], HashSet::from([3, 2, 1])));
170        assert!(equivalent_to(vec![1, 2, 3], HashSet::from([3, 2, 1])));
171        assert!(equivalent_to(&vec![1, 2, 3], &HashSet::from([3, 2, 1])));
172
173        assert_equivalent(vec![1, 2, 3], vec![3, 2, 1]);
174        assert_equivalent(vec![1, 2, 3], vec![2, 1, 3]);
175
176        assert_equivalent([1, 2, 3], vec![3, 2, 1]);
177        assert_equivalent(&[1, 2, 3], &vec![3, 2, 1]);
178        assert_equivalent([1, 2, 3], HashSet::from([3, 2, 1]));
179        assert_equivalent(vec![1, 2, 3], HashSet::from([3, 2, 1]));
180        assert_equivalent(&vec![1, 2, 3], &HashSet::from([3, 2, 1]));
181    }
182
183    #[test]
184    fn test_current_function_extract_function_name() {
185        let name = current_function!();
186
187        assert_eq!("test_current_function_extract_function_name", name);
188    }
189
190    #[tokio::test]
191    async fn test_current_function_extract_async_function_name() {
192        let name = current_function!();
193
194        assert_eq!("test_current_function_extract_async_function_name", name);
195    }
196
197    #[test]
198    fn test_format_function_path_from_given_function() {
199        assert_eq!(
200            "mithril_common/test_utils/utils/test_format_function_path_from_given_function",
201            format_current_function_path(test_format_function_path_from_given_function)
202        );
203    }
204
205    #[test]
206    fn test_format_function_path_from_given_pseudo_function_f() {
207        fn f() {}
208        assert_eq!(
209            "mithril_common/test_utils/utils/test_format_function_path_from_given_pseudo_function_f",
210            format_current_function_path(f)
211        );
212    }
213
214    #[tokio::test]
215    async fn test_format_function_path_from_given_async_function_f() {
216        fn f() {}
217        assert_eq!(
218            "mithril_common/test_utils/utils/test_format_function_path_from_given_async_function_f",
219            format_current_function_path(f)
220        );
221    }
222
223    #[test]
224    fn test_build_current_function_path_using_macros() {
225        assert_eq!(
226            Path::new("mithril_common")
227                .join("test_utils")
228                .join("utils")
229                .join("test_build_current_function_path_using_macros"),
230            current_function_path!()
231        );
232    }
233
234    #[tokio::test]
235    async fn test_build_current_async_function_path_using_macros() {
236        assert_eq!(
237            Path::new("mithril_common")
238                .join("test_utils")
239                .join("utils")
240                .join("test_build_current_async_function_path_using_macros"),
241            current_function_path!()
242        );
243    }
244}