Skip to main content

tor_netdoc/
test_support.rs

1//! Support functions for testing, also expoeted
2// @@ begin test lint list maintained by maint/add_warning @@
3#![allow(clippy::bool_assert_comparison)]
4#![allow(clippy::clone_on_copy)]
5#![allow(clippy::dbg_macro)]
6#![allow(clippy::mixed_attributes_style)]
7#![allow(clippy::print_stderr)]
8#![allow(clippy::print_stdout)]
9#![allow(clippy::single_char_pattern)]
10#![allow(clippy::unwrap_used)]
11#![allow(clippy::unchecked_time_subtraction)]
12#![allow(clippy::useless_vec)]
13#![allow(clippy::needless_pass_by_value)]
14#![allow(clippy::string_slice)] // See arti#2571
15//! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
16
17use crate::doc::netstatus::vote::NetworkStatusUnverified as NetworkStatusVoteUnverified;
18use crate::parse2::{
19    NetdocParseable, NetdocParseableFields, NetdocParseableUnverified as _, ParseInput,
20    parse_netdoc, parse_netdoc_multiple_with_offsets,
21};
22use derive_deftly::Deftly;
23use itertools::chain;
24use std::any::{Any, TypeId};
25use std::collections::HashMap;
26use std::fmt::Display;
27use std::sync::Mutex;
28
29/// Assert that `$a = $b`; if not, panic with a unidiff
30//
31// implementation is in fn assert_eq_or_diff, at the bottom of the file
32#[macro_export]
33macro_rules! assert_eq_or_diff {
34    { $a:expr, $b:expr $(,)? } => {
35        assert_eq_or_diff!($a, $b, "")
36    };
37    { $a:expr, $b:expr , $($message:tt)*} => {
38        $crate::assert_eq_or_diff(
39            &$a,
40            stringify!($a),
41            &$b,
42            stringify!($b),
43            &format_args!($($message)*),
44        )
45    };
46}
47
48/// Assert that `a = b`; if not, panic with a unidiff mentioning `a_what`, `b_what` and `message`
49///
50/// Normally it is more convenient to use the [`assert_eq_or_diff!`] macro.
51pub fn assert_eq_or_diff(a: &str, a_what: &str, b: &str, b_what: &str, message: &dyn Display) {
52    use imara_diff::{Algorithm, BasicLineDiffPrinter, Diff, InternedInput, UnifiedDiffConfig};
53
54    if a == b {
55        return;
56    }
57    let input = InternedInput::new(a, b);
58    let mut diff = Diff::compute(Algorithm::Histogram, &input);
59    diff.postprocess_lines(&input);
60    panic!(
61        // rustdoc insists on this unhelpful formatting
62        "===== document {a_what} =====
63{a}
64===== document {b_what} =====
65{b}
66===== diff ====
67{}
68===== documents differ: {a_what} != {b_what} =====
69{message}
70",
71        diff.unified_diff(
72            &BasicLineDiffPrinter(&input.interner),
73            UnifiedDiffConfig::default(),
74            &input,
75        ),
76    );
77}
78
79/// Substitute all `re` in `update` with `repl`
80///
81/// **Note** that `re` is processed in "multiple lines mode"
82/// (`(?m)` is prepended.)
83///
84/// Convenience wrapper around [`regex::Regex::replace_all`].
85pub fn regsub(update: &mut String, re: &str, repl: impl regex::Replacer) {
86    *update = regex::Regex::new(&format!("(?m){re}"))
87        .expect(re)
88        .replace_all(update, repl)
89        .to_string();
90}
91
92/// Parse a test case from a netdoc-style test case string
93///
94/// `T` must be `NetdocParseableFields`.
95/// (a surrounding document type with an intro item will be used internally.)
96///
97/// The input string is preprocessed:
98///
99///  - `#`-comments are stripped
100///  - each line is trimmed (so the input can be inden ted)
101///  - blank lines are removed
102pub fn parse_testcase_from_netdoc<T: NetdocParseableFields>(input_doc: &str) -> T {
103    #[derive(Deftly)]
104    #[derive_deftly(NetdocParseable)]
105    struct Document<T: NetdocParseableFields> {
106        /// Intro item, not present in test case doc strings
107        #[allow(unused)]
108        parse_testcase_from_netdoc_intro: (),
109
110        #[deftly(netdoc(flatten))]
111        fields: T,
112    }
113
114    eprintln!("\n&&&&&&& input test case\n{input_doc}");
115    let doc = chain!(
116        ["parse-testcase-from-netdoc-intro\n"],
117        input_doc
118            .lines()
119            .map(|l| l.split_once('#').map(|(l, _)| l).unwrap_or(l).trim())
120            .filter(|l| !l.is_empty())
121            .flat_map(|l| [l, "\n"]),
122    )
123    .collect::<String>();
124
125    eprintln!(
126        "---- tidied \n{}----",
127        doc.split_inclusive('\n')
128            // show line numbers in case of parse errors, what a faff
129            .enumerate()
130            .map(|(lno, l)| format!("| {:5} {l}", lno + 1))
131            .collect::<String>()
132    );
133
134    let pinput = ParseInput::new(&doc, "<input doc>");
135    let case: Document<T> = parse_netdoc(&pinput).expect("parse failed");
136
137    case.fields
138}
139
140/// Parse `text` as document type `D`, for use in testing
141///
142/// Parses with retain unknown values enabled, iff the corresponding cargo feature is enabled.
143///
144/// Memoises the parsing (so, leaking the parsed document),
145/// so that we don't reparse these documents once for each test case that uses them.
146///
147/// # Panics
148///
149/// Panics if the parsing fails.
150pub fn parse_test_document<D>(text: &'static str) -> &'static D
151where
152    D: NetdocParseable + Sync,
153{
154    /// Keys in the memo table
155    type MemoKey = (&'static str, TypeId);
156
157    /// Memo table
158    static MEMO: Mutex<Option<HashMap<MemoKey, &'static (dyn Any + Sync)>>> = Mutex::new(None);
159
160    // With this locking strategy, we can run only one actual parser at once.
161    // That seems fine for testing.
162    let mut memo = MEMO.lock().unwrap_or_else(|poison| poison.into_inner());
163    let key = (text, TypeId::of::<D>());
164
165    let map_entry = memo.get_or_insert_default().entry(key).or_insert_with(|| {
166        let input = ParseInput::new(text, "<test document>");
167
168        #[cfg(feature = "retain-unknown")]
169        let input = input.retain_unknown_values();
170
171        let doc = parse_netdoc::<D>(&input).expect(text);
172
173        Box::leak(Box::new(doc))
174    });
175
176    (*map_entry as &dyn Any)
177        .downcast_ref::<D>()
178        .expect("wrong type is impossible")
179}
180
181/// Regex for the start of the item with keyword `kw` in a raw document
182pub fn raw_item_start_regex(kw: &str) -> regex::Regex {
183    regex::Regex::new(&format!(r#"(?m)^{kw}[ \n]"#)).expect(kw)
184}
185
186/// Finds the item with keyword `kw` in a raw document, using raw strings, not the parser
187///
188/// Returns the keyword line, and the rest of the doc.
189///
190/// If there are several items, finds the first.
191pub fn raw_item_count<'d>(doc: &'d str, kw: &str) -> usize {
192    raw_item_start_regex(kw).find_iter(doc).count()
193}
194
195/// Finds the item with keyword `kw` in a raw document, using raw strings, not the parser
196///
197/// Returns the keyword line, and the rest of the doc.
198pub fn raw_find_item<'d>(doc: &'d str, kw: &str) -> (&'d str, &'d str) {
199    let p = raw_item_start_regex(kw).find(doc).expect(kw).start();
200
201    doc[p..].split_once('\n').expect(kw)
202}
203
204/// Finds the arguments to keyword `kw`, using raw strings, not the parser
205pub fn raw_find_item_rhs<'d>(doc: &'d str, kw: &str) -> &'d str {
206    let l = raw_find_item(doc, kw).0;
207    let a = l.strip_prefix(kw).expect(l);
208
209    let b = a.trim_start();
210    assert!(a.is_empty() || a != b);
211    b
212}
213/// Finds the object after keyword `kw`, using raw strings, not the parser
214pub fn raw_find_object<'d>(doc: &'d str, kw: &str) -> &'d str {
215    let l = raw_find_item(doc, kw).1;
216    let r = l
217        .split_once("\n-----END")
218        .expect("END not found")
219        .1
220        .split_once("\n")
221        .expect("no newline after END")
222        .1;
223    &l[0..(l.len() - r.len())]
224}
225
226/// Given a file of votes, find the vote for a specific authority
227///
228/// Returns the parsed form, and the raw vote text.
229///
230/// Useful to pick a particular vote out of [`crate::testdata2::V3_STATUS_VOTES`].
231/// (The ordering there isn't stable, so `V3_STATUS_VOTES__1` is often not suitable.)
232pub fn find_vote_by_authority_id<'t>(
233    input: &ParseInput<'t>,
234    authority_id: tor_llcrypto::pk::rsa::RsaIdentity,
235) -> (NetworkStatusVoteUnverified, &'t str) {
236    let (doc, start, end) =
237        parse_netdoc_multiple_with_offsets::<NetworkStatusVoteUnverified>(input)
238            .expect("parse")
239            .into_iter()
240            .find(|(doc, _, _)| {
241                *doc.inspect_unverified()
242                    .0
243                    .authority
244                    .authority
245                    .dir_source
246                    .identity
247                    == authority_id
248            })
249            .expect("missing");
250    (doc, &input.input()[start..end])
251}