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

            
17
use crate::doc::netstatus::vote::NetworkStatusUnverified as NetworkStatusVoteUnverified;
18
use crate::parse2::{
19
    NetdocParseable, NetdocParseableFields, NetdocParseableUnverified as _, ParseInput,
20
    parse_netdoc, parse_netdoc_multiple_with_offsets,
21
};
22
use derive_deftly::Deftly;
23
use itertools::chain;
24
use std::any::{Any, TypeId};
25
use std::collections::HashMap;
26
use std::fmt::Display;
27
use 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]
33
macro_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.
51
285
pub 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
285
    if a == b {
55
285
        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
285
}
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`].
85
98
pub fn regsub(update: &mut String, re: &str, repl: impl regex::Replacer) {
86
98
    *update = regex::Regex::new(&format!("(?m){re}"))
87
98
        .expect(re)
88
98
        .replace_all(update, repl)
89
98
        .to_string();
90
98
}
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
102
17
pub 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
17
    eprintln!("\n&&&&&&& input test case\n{input_doc}");
115
17
    let doc = chain!(
116
17
        ["parse-testcase-from-netdoc-intro\n"],
117
17
        input_doc
118
17
            .lines()
119
106
            .map(|l| l.split_once('#').map(|(l, _)| l).unwrap_or(l).trim())
120
106
            .filter(|l| !l.is_empty())
121
75
            .flat_map(|l| [l, "\n"]),
122
    )
123
    .collect::<String>();
124

            
125
17
    eprintln!(
126
        "---- tidied \n{}----",
127
17
        doc.split_inclusive('\n')
128
17
            // show line numbers in case of parse errors, what a faff
129
17
            .enumerate()
130
92
            .map(|(lno, l)| format!("| {:5} {l}", lno + 1))
131
            .collect::<String>()
132
    );
133

            
134
17
    let pinput = ParseInput::new(&doc, "<input doc>");
135
17
    let case: Document<T> = parse_netdoc(&pinput).expect("parse failed");
136

            
137
17
    case.fields
138
17
}
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.
150
2537
pub fn parse_test_document<D>(text: &'static str) -> &'static D
151
2537
where
152
2537
    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
2537
    let mut memo = MEMO.lock().unwrap_or_else(|poison| poison.into_inner());
163
2537
    let key = (text, TypeId::of::<D>());
164

            
165
2537
    let map_entry = memo.get_or_insert_default().entry(key).or_insert_with(|| {
166
399
        let input = ParseInput::new(text, "<test document>");
167

            
168
        #[cfg(feature = "retain-unknown")]
169
399
        let input = input.retain_unknown_values();
170

            
171
399
        let doc = parse_netdoc::<D>(&input).expect(text);
172

            
173
399
        Box::leak(Box::new(doc))
174
399
    });
175

            
176
2537
    (*map_entry as &dyn Any)
177
2537
        .downcast_ref::<D>()
178
2537
        .expect("wrong type is impossible")
179
2537
}
180

            
181
/// Regex for the start of the item with keyword `kw` in a raw document
182
45
pub fn raw_item_start_regex(kw: &str) -> regex::Regex {
183
45
    regex::Regex::new(&format!(r#"(?m)^{kw}[ \n]"#)).expect(kw)
184
45
}
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.
191
2
pub fn raw_item_count<'d>(doc: &'d str, kw: &str) -> usize {
192
2
    raw_item_start_regex(kw).find_iter(doc).count()
193
2
}
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.
198
43
pub fn raw_find_item<'d>(doc: &'d str, kw: &str) -> (&'d str, &'d str) {
199
43
    let p = raw_item_start_regex(kw).find(doc).expect(kw).start();
200

            
201
43
    doc[p..].split_once('\n').expect(kw)
202
43
}
203

            
204
/// Finds the arguments to keyword `kw`, using raw strings, not the parser
205
37
pub fn raw_find_item_rhs<'d>(doc: &'d str, kw: &str) -> &'d str {
206
37
    let l = raw_find_item(doc, kw).0;
207
37
    let a = l.strip_prefix(kw).expect(l);
208

            
209
37
    let b = a.trim_start();
210
37
    assert!(a.is_empty() || a != b);
211
37
    b
212
37
}
213
/// Finds the object after keyword `kw`, using raw strings, not the parser
214
6
pub fn raw_find_object<'d>(doc: &'d str, kw: &str) -> &'d str {
215
6
    let l = raw_find_item(doc, kw).1;
216
6
    let r = l
217
6
        .split_once("\n-----END")
218
6
        .expect("END not found")
219
6
        .1
220
6
        .split_once("\n")
221
6
        .expect("no newline after END")
222
6
        .1;
223
6
    &l[0..(l.len() - r.len())]
224
6
}
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.)
232
1
pub fn find_vote_by_authority_id<'t>(
233
1
    input: &'t ParseInput<'t>,
234
1
    authority_id: tor_llcrypto::pk::rsa::RsaIdentity,
235
1
) -> (NetworkStatusVoteUnverified, &'t str) {
236
    let (doc, start, end) =
237
1
        parse_netdoc_multiple_with_offsets::<NetworkStatusVoteUnverified>(input)
238
1
            .expect("parse")
239
1
            .into_iter()
240
1
            .find(|(doc, _, _)| {
241
1
                *doc.inspect_unverified()
242
1
                    .0
243
1
                    .authority
244
1
                    .authority
245
1
                    .dir_source
246
1
                    .identity
247
1
                    == authority_id
248
1
            })
249
1
            .expect("missing");
250
1
    (doc, &input.input()[start..end])
251
1
}