|
11 | 11 | extern crate pest; |
12 | 12 | extern crate pest_grammars; |
13 | 13 |
|
14 | | -use std::fs::File; |
15 | | -use std::io::Read; |
16 | | - |
17 | 14 | use pest::Parser; |
18 | | - |
19 | 15 | use pest_grammars::json::*; |
| 16 | +use pretty_assertions::assert_eq; |
20 | 17 |
|
21 | 18 | #[test] |
22 | 19 | fn null() { |
@@ -164,10 +161,50 @@ fn object() { |
164 | 161 |
|
165 | 162 | #[test] |
166 | 163 | fn examples() { |
167 | | - let mut file = File::open("tests/examples.json").unwrap(); |
168 | | - let mut data = String::new(); |
| 164 | + let raw = include_str!("examples.json"); |
| 165 | + let pairs = JsonParser::parse(Rule::json, raw).unwrap(); |
| 166 | + |
| 167 | + let expected = include_str!("examples.line-col.txt"); |
| 168 | + |
| 169 | + // Test for flatten iter, and use span.start_pos().line_col() |
| 170 | + let mut out = String::new(); |
| 171 | + for pair in pairs.clone().flatten() { |
| 172 | + let sub_pairs = pair.clone().into_inner(); |
| 173 | + if sub_pairs.count() == 0 { |
| 174 | + let span = pair.as_span(); |
| 175 | + out.push_str(&build_line_col(span.start_pos().line_col(), span.as_str())); |
| 176 | + } |
| 177 | + } |
| 178 | + assert_eq!(expected.trim(), out.trim()); |
| 179 | + |
| 180 | + // Test for nested iter, use pair.line_col() |
| 181 | + let mut out = String::new(); |
| 182 | + for pair in pairs { |
| 183 | + out.push_str(&build_result_for_pair(pair.clone())); |
| 184 | + } |
| 185 | + |
| 186 | + assert_eq!(expected.trim(), out.trim()); |
| 187 | +} |
169 | 188 |
|
170 | | - file.read_to_string(&mut data).unwrap(); |
| 189 | +fn build_line_col(line_col: (usize, usize), str: &str) -> String { |
| 190 | + format!( |
| 191 | + "({}:{}) {}\n", |
| 192 | + line_col.0, |
| 193 | + line_col.1, |
| 194 | + str.replace('\n', "\\n") |
| 195 | + ) |
| 196 | +} |
171 | 197 |
|
172 | | - JsonParser::parse(Rule::json, &data).unwrap(); |
| 198 | +fn build_result_for_pair(pair: pest::iterators::Pair<Rule>) -> String { |
| 199 | + let mut out = String::new(); |
| 200 | + |
| 201 | + let sub_pairs = pair.clone().into_inner(); |
| 202 | + if sub_pairs.clone().count() == 0 { |
| 203 | + out.push_str(&build_line_col(pair.line_col(), pair.as_str())); |
| 204 | + } else { |
| 205 | + for sub_pair in sub_pairs { |
| 206 | + out.push_str(&build_result_for_pair(sub_pair)); |
| 207 | + } |
| 208 | + } |
| 209 | + out |
173 | 210 | } |
0 commit comments