aboutsummaryrefslogtreecommitdiff
path: root/tests/test_spans.rs
blob: 970099add5294cc93d5cb0122f0555f5b7bac9da (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
use std::ops::Range;

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

fn tokenizer(html: &'static str) -> impl Iterator<Item = Token<usize>> {
    Tokenizer::new(
        PosTrackingReader::new(html),
        DefaultEmitter::<usize>::default(),
    )
    .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_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 (_name, 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 (_name, attr) in tag.attributes {
        labels.push((attr.value_span, ""));
    }
    assert_snapshot!(annotate(html, labels), @r###"
    <test x=unquoted y = unquoted z='single-quoted' zz="double-quoted" empty=''>
            ^^^^^^^^     ^^^^^^^^    ^^^^^^^^^^^^^      ^^^^^^^^^^^^^         ^
    "###);
}

#[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");
    };
    // FIXME: this span is wrong (starts one byte too soon)
    assert_eq!(comment.data, html[1..][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? -->
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    "###);
}

fn annotate_errors(html: &'static str) -> String {
    let mut labels = Vec::new();
    for token in tokenizer(html) {
        if let Token::Error { error, span } = token {
            labels.push((span, error.to_string()));
        }
    }
    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_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_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
    "###);
}

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