tor_netdoc/
test_support.rs1#![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)] use 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#[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
48pub 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 "===== 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
79pub 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
92pub fn parse_testcase_from_netdoc<T: NetdocParseableFields>(input_doc: &str) -> T {
103 #[derive(Deftly)]
104 #[derive_deftly(NetdocParseable)]
105 struct Document<T: NetdocParseableFields> {
106 #[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 .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
140pub fn parse_test_document<D>(text: &'static str) -> &'static D
151where
152 D: NetdocParseable + Sync,
153{
154 type MemoKey = (&'static str, TypeId);
156
157 static MEMO: Mutex<Option<HashMap<MemoKey, &'static (dyn Any + Sync)>>> = Mutex::new(None);
159
160 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
181pub fn raw_item_start_regex(kw: &str) -> regex::Regex {
183 regex::Regex::new(&format!(r#"(?m)^{kw}[ \n]"#)).expect(kw)
184}
185
186pub fn raw_item_count<'d>(doc: &'d str, kw: &str) -> usize {
192 raw_item_start_regex(kw).find_iter(doc).count()
193}
194
195pub 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
204pub 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}
213pub 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
226pub 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}