aboutsummaryrefslogtreecommitdiff
path: root/tests/test_spans.rs
blob: 0956f8e8e680f56ee1d9f4bcc1329619dd5a1ccc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
use std::ops::Range;

use codespan_reporting::{
    self,
    diagnostic::{Diagnostic, Label},
    files::SimpleFiles,
    term::{self, termcolor::Buffer},
};
use html5tokenizer::{offset::PosTrackingReader, NaiveParser, Token};
use insta::assert_snapshot;
use similar_asserts::assert_eq;

fn tokenizer(html: &'static str) -> impl Iterator<Item = Token<usize>> {
    NaiveParser::new(PosTrackingReader::new(html)).flatten()
}

fn annotate(html: &str, labels: Vec<(Range<usize>, impl AsRef<str>)>) -> String {
    let mut files = SimpleFiles::new();
    let file_id = files.add("test.html", html);

    let diagnostic = Diagnostic::note().with_labels(
        labels
            .into_iter()
            .map(|(span, text)| Label::primary(file_id, span).with_message(text.as_ref()))
            .collect(),
    );

    let mut writer = Buffer::no_color();
    let config = codespan_reporting::term::Config::default();
    term::emit(&mut writer, &config, &files, &diagnostic).unwrap();
    let msg = std::str::from_utf8(writer.as_slice()).unwrap();

    // strip the filename and the line numbers since we don't need them
    // (apparently they cannot be disabled in codespan_reporting)
    msg.lines()
        .skip(3)
        .flat_map(|l| l.split_once("│ ").map(|s| s.1.trim_end()))
        .collect::<Vec<_>>()
        .join("\n")
}

#[test]
fn start_tag_span() {
    let html = "<x> <xyz> <xyz  > <xyz/>";
    let mut labels = Vec::new();
    for token in tokenizer(html) {
        if let Token::StartTag(tag) = token {
            labels.push((tag.span, ""));
        }
    }
    assert_snapshot!(annotate(html, labels), @r###"
    <x> <xyz> <xyz  > <xyz/>
    ^^^ ^^^^^ ^^^^^^^ ^^^^^^
    "###);
}

#[test]
fn end_tag_span() {
    let html = "</x> </xyz> </xyz  > </xyz/>";
    let mut labels = Vec::new();
    for token in tokenizer(html) {
        if let Token::EndTag(tag) = token {
            labels.push((tag.span, ""));
        }
    }
    assert_snapshot!(annotate(html, labels), @r###"
    </x> </xyz> </xyz  > </xyz/>
    ^^^^ ^^^^^^ ^^^^^^^^ ^^^^^^^
    "###);
}

#[test]
fn start_tag_name_span() {
    let html = "<x> <xyz> <xyz  > <xyz/>";
    let mut labels = Vec::new();
    for token in tokenizer(html) {
        if let Token::StartTag(tag) = token {
            labels.push((tag.name_span(), ""));
        }
    }
    assert_snapshot!(annotate(html, labels), @r###"
    <x> <xyz> <xyz  > <xyz/>
     ^   ^^^   ^^^     ^^^
    "###);
}

#[test]
fn end_tag_name_span() {
    let html = "</x> </xyz> </xyz  > </xyz/>";
    let mut labels = Vec::new();
    for token in tokenizer(html) {
        if let Token::EndTag(tag) = token {
            labels.push((tag.name_span(), ""));
        }
    }
    assert_snapshot!(annotate(html, labels), @r###"
    </x> </xyz> </xyz  > </xyz/>
      ^    ^^^    ^^^      ^^^
    "###);
}

#[test]
fn attribute_name_span() {
    let html = "<test x xyz y=VAL xy=VAL z = VAL yzx = VAL>";
    let mut labels = Vec::new();
    let Token::StartTag(tag) = tokenizer(html).next().unwrap() else {
        panic!("expected start tag")
    };
    for attr in &tag.attributes {
        labels.push((attr.name_span(), ""));
    }
    assert_snapshot!(annotate(html, labels), @r###"
    <test x xyz y=VAL xy=VAL z = VAL yzx = VAL>
          ^ ^^^ ^     ^^     ^       ^^^
    "###);
}

#[test]
fn attribute_value_span() {
    let html = "<test x=unquoted y = unquoted z='single-quoted' zz=\"double-quoted\" empty=''>";
    let mut labels = Vec::new();
    let Token::StartTag(tag) = tokenizer(html).next().unwrap() else {
        panic!("expected start tag")
    };
    for attr in &tag.attributes {
        labels.push((attr.value_span().unwrap(), ""));
    }
    assert_snapshot!(annotate(html, labels), @r###"
    <test x=unquoted y = unquoted z='single-quoted' zz="double-quoted" empty=''>
            ^^^^^^^^     ^^^^^^^^    ^^^^^^^^^^^^^      ^^^^^^^^^^^^^         ^
    "###);
}

#[test]
fn attribute_value_with_char_ref() {
    let html = "<test x=&amp; y='&amp;' z=\"&amp;\">";
    let mut labels = Vec::new();
    let Token::StartTag(tag) = tokenizer(html).next().unwrap() else {
        panic!("expected start tag")
    };
    for attr in &tag.attributes {
        labels.push((attr.value_span().unwrap(), ""));
    }
    assert_snapshot!(annotate(html, labels), @r###"
    <test x=&amp; y='&amp;' z="&amp;">
            ^^^^^    ^^^^^     ^^^^^
    "###);
}

#[test]
fn comment_proper_data_span() {
    let html = "<!-- Why are you looking at the source code? -->";
    let Token::Comment(comment) = tokenizer(html).next().unwrap() else {
        panic!("expected comment");
    };
    assert_eq!(comment.data, html[comment.data_span()]);
    let labels = vec![(comment.data_span(), "")];
    assert_snapshot!(annotate(html, labels), @r###"
    <!-- Why are you looking at the source code? -->
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    "###);
}

#[test]
fn comment_bogus_data_span() {
    let html = "<! Why are you looking at the source code? -->";
    let Token::Comment(comment) = tokenizer(html)
        .filter(|t| !matches!(t, Token::Error { .. }))
        .next()
        .unwrap()
    else {
        panic!("expected comment");
    };
    assert_eq!(comment.data, html[comment.data_span()]);
    let labels = vec![(comment.data_span(), "")];
    assert_snapshot!(annotate(html, labels), @r###"
    <! Why are you looking at the source code? -->
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    "###);
}

#[test]
fn doctype_span() {
    let html = r#"<!DOCTYPE       HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"     >"#;
    let Token::Doctype(doctype) = tokenizer(html).next().unwrap() else {
        panic!("expected doctype");
    };
    let labels = vec![(doctype.span, "")];
    assert_snapshot!(annotate(html, labels), @r###"
    <!DOCTYPE       HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"     >
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    "###);
}

#[test]
fn doctype_id_spans() {
    let html = r#"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">"#;
    let Token::Doctype(doctype) = tokenizer(html).next().unwrap() else {
        panic!("expected doctype");
    };
    let labels = vec![
        (doctype.public_id_span().unwrap(), "public id"),
        (doctype.system_id_span().unwrap(), "system id"),
    ];
    assert_snapshot!(annotate(html, labels), @r###"
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
                           ^^^^^^^^^^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ system id
                           
                           public id
    "###);
}

fn annotate_errors(html: &'static str) -> String {
    let mut labels = Vec::new();
    for token in tokenizer(html) {
        let Token::Error { error, span } = token else {
            continue;
        };

        if span.start == span.end {
            if span.start != html.len() {
                panic!("empty error spans are only allowed at the very end of the source (for eof errors)");
            }
        } else {
            assert!(span.start < span.end);
            assert!(span.end <= html.len());
        }

        labels.push((span, error.code()));
    }
    annotate(html, labels)
}

#[test]
fn tests_for_errors_are_sorted() {
    let source_of_this_file = std::fs::read_to_string(file!()).unwrap();
    let mut error_tests: Vec<_> = source_of_this_file
        .lines()
        .filter(|l| l.starts_with("fn error_"))
        .collect();
    let error_tests_found_order = error_tests.join("\n");
    error_tests.sort();
    let error_tests_sorted = error_tests.join("\n");
    assert_eq!(error_tests_found_order, error_tests_sorted);
}

#[test]
fn error_char_ref_missing_semicolon() {
    let html = "&not";
    assert_snapshot!(annotate_errors(html), @r###"
    &not
        ^ missing-semicolon-after-character-reference
    "###);
}

#[test]
fn error_char_ref_unknown_named() {
    let html = "The pirate says &arrrrr;";
    assert_snapshot!(annotate_errors(html), @r###"
    The pirate says &arrrrr;
                           ^ unknown-named-character-reference
    "###);
}

#[test]
fn error_duplicate_attribute() {
    let html = "Does this open two pages? <a href=foo.html href=bar.html>";
    assert_snapshot!(annotate_errors(html), @r###"
    Does this open two pages? <a href=foo.html href=bar.html>
                                               ^^^^ duplicate-attribute
    "###);
}

#[test]
fn error_end_tag_with_attributes() {
    let html = "</end-tag first second=value>";
    assert_snapshot!(annotate_errors(html), @r###"
    </end-tag first second=value>
                    ^^^^^^ end-tag-with-attributes
    "###);
}

#[test]
fn error_end_tag_with_trailing_solidus() {
    let html = "Do you start or do you end? </yes/>";
    assert_snapshot!(annotate_errors(html), @r###"
    Do you start or do you end? </yes/>
                                     ^ end-tag-with-trailing-solidus
    "###);
}

#[test]
fn error_eof_before_tag_name() {
    let html = "<";
    assert_snapshot!(annotate_errors(html), @r###"
    <
     ^ eof-before-tag-name
    "###);
}

// TODO: add error_eof_in_cdata test
// blocked by lack of proper tree constructor (NaiveParser doesn't parse CDATA sections)

#[test]
fn error_eof_in_comment() {
    let html = "<!--";
    assert_snapshot!(annotate_errors(html), @r###"
    <!--
        ^ eof-in-comment
    "###);
}

#[test]
fn error_eof_in_doctype() {
    let html = "<!doctype html";
    assert_snapshot!(annotate_errors(html), @r###"
    <!doctype html
                  ^ eof-in-doctype
    "###);
}

#[test]
fn error_eof_in_script_html_comment_like_text() {
    let html = "<script><!--";
    assert_snapshot!(annotate_errors(html), @r###"
    <script><!--
                ^ eof-in-script-html-comment-like-text
    "###);
}

#[test]
fn error_eof_in_tag() {
    let html = "</sarcasm";
    assert_snapshot!(annotate_errors(html), @r###"
    </sarcasm
             ^ eof-in-tag
    "###);
}

#[test]
fn error_invalid_first_character_of_tag_name() {
    let html = "Please mind the gap: < test";
    assert_snapshot!(annotate_errors(html), @r###"
    Please mind the gap: < test
                          ^ invalid-first-character-of-tag-name
    "###);
}