Debian Codegraph @

debian/missing-sources/idna/tests/uts46.rs

raw
1 // Copyright 2013-2014 The rust-url developers.
2 //
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
8
9 #![allow(clippy::assigning_clones)]
10
11 use crate::test::TestFn;
12 use std::char;
13 use std::fmt::Write;
14
15 use idna::uts46::verify_dns_length;
16 use idna::uts46::ProcessingError;
17 use idna::uts46::ProcessingSuccess;
18 use idna::uts46::{AsciiDenyList, DnsLength, ErrorPolicy, Hyphens};
19 use idna::Errors;
20
21 pub fn collect_tests<F: FnMut(String, TestFn)>(add_test: &mut F) {
22 // https://www.unicode.org/Public/idna/13.0.0/IdnaTestV2.txt
23 for (i, line) in include_str!("IdnaTestV2.txt").lines().enumerate() {
24 if line.is_empty() || line.starts_with('#') {
25 continue;
26 }
27
28 // Remove comments
29 let line = match line.find('#') {
30 Some(index) => &line[0..index],
31 None => line,
32 };
33
34 let mut pieces = line.split(';').map(|x| x.trim()).collect::<Vec<&str>>();
35 let source = unescape(pieces.remove(0));
36
37 // ToUnicode
38 let mut to_unicode = unescape(pieces.remove(0));
39 if to_unicode.is_empty() {
40 to_unicode = source.clone();
41 }
42 let to_unicode_status = status(pieces.remove(0));
43
44 // ToAsciiN
45 let to_ascii_n = pieces.remove(0);
46 let to_ascii_n = if to_ascii_n.is_empty() {
47 to_unicode.clone()
48 } else {
49 to_ascii_n.to_owned()
50 };
51 let to_ascii_n_status = pieces.remove(0);
52 let to_ascii_n_status = if to_ascii_n_status.is_empty() {
53 to_unicode_status.clone()
54 } else {
55 status(to_ascii_n_status)
56 };
57
58 let test_name = format!("UTS #46 line {}", i + 1);
59 add_test(
60 test_name,
61 TestFn::DynTestFn(Box::new(move || {
62 let config = idna::uts46::Uts46::new();
63
64 // http://unicode.org/reports/tr46/#Deviations
65 // applications that perform IDNA2008 lookup are not required to check
66 // for these contexts, so we skip all tests annotated with C*
67
68 // Everybody ignores V2
69 // https://github.com/servo/rust-url/pull/240
70 // https://github.com/whatwg/url/issues/53#issuecomment-181528158
71 // http://www.unicode.org/review/pri317/
72
73 // "The special error codes X3 and X4_2 are now returned where a toASCII error code
74 // was formerly being generated in toUnicode due to an empty label."
75 // This is not implemented yet, so we skip toUnicode X4_2 tests for now, too.
76
77 let (to_unicode_value, to_unicode_result) =
78 config.to_unicode(source.as_bytes(), AsciiDenyList::STD3, Hyphens::Check);
79 let to_unicode_result = to_unicode_result.map(|()| to_unicode_value.into_owned());
80 check(
81 &source,
82 (&to_unicode, &to_unicode_status),
83 to_unicode_result,
84 |e| e == "X4_2",
85 );
86
87 let to_ascii_n_result = config.to_ascii(
88 source.as_bytes(),
89 AsciiDenyList::STD3,
90 Hyphens::Check,
91 DnsLength::Verify,
92 );
93 check(
94 &source,
95 (&to_ascii_n, &to_ascii_n_status),
96 to_ascii_n_result.map(|cow| cow.into_owned()),
97 |_| false,
98 );
99
100 let mut to_unicode_simultaneous = String::new();
101 let mut to_ascii_simultaneous = String::new();
102 let (to_unicode_simultaneous_result, to_ascii_simultaneous_result) = match config
103 .process(
104 source.as_bytes(),
105 AsciiDenyList::STD3,
106 Hyphens::Check,
107 ErrorPolicy::MarkErrors,
108 |_, _, _| true,
109 &mut to_unicode_simultaneous,
110 Some(&mut to_ascii_simultaneous),
111 ) {
112 Ok(ProcessingSuccess::Passthrough) => (
113 Ok(source.to_string()),
114 if verify_dns_length(&source, false) {
115 Ok(source.to_string())
116 } else {
117 Err(Errors::default())
118 },
119 ),
120 Ok(ProcessingSuccess::WroteToSink) => {
121 if to_ascii_simultaneous.is_empty() {
122 (
123 Ok(to_unicode_simultaneous.clone()),
124 if verify_dns_length(&to_unicode_simultaneous, false) {
125 Ok(to_unicode_simultaneous)
126 } else {
127 Err(Errors::default())
128 },
129 )
130 } else {
131 (
132 Ok(to_unicode_simultaneous),
133 if verify_dns_length(&to_ascii_simultaneous, false) {
134 Ok(to_ascii_simultaneous)
135 } else {
136 Err(Errors::default())
137 },
138 )
139 }
140 }
141 Err(ProcessingError::ValidityError) => {
142 (Err(Errors::default()), Err(Errors::default()))
143 }
144 Err(ProcessingError::SinkError) => unreachable!(),
145 };
146 check(
147 &source,
148 (&to_unicode, &to_unicode_status),
149 to_unicode_simultaneous_result,
150 |e| e == "X4_2",
151 );
152 check(
153 &source,
154 (&to_ascii_n, &to_ascii_n_status),
155 to_ascii_simultaneous_result,
156 |_| false,
157 );
158 })),
159 )
160 }
161 }
162
163 #[allow(clippy::redundant_clone)]
164 fn check<F>(source: &str, expected: (&str, &[&str]), actual: Result<String, Errors>, ignore: F)
165 where
166 F: Fn(&str) -> bool,
167 {
168 if !expected.1.is_empty() {
169 if !expected.1.iter().copied().any(ignore) {
170 let res = actual.ok();
171 assert_eq!(
172 res.clone(),
173 None,
174 "Expected error {:?}. result: {} | source: {}",
175 expected.1,
176 res.unwrap(),
177 source,
178 );
179 }
180 } else {
181 assert!(
182 actual.is_ok(),
183 "Couldn't parse {} | error: {:?}",
184 source,
185 actual.err().unwrap(),
186 );
187 assert_eq!(actual.unwrap(), expected.0, "source: {}", source);
188 }
189 }
190
191 fn unescape(input: &str) -> String {
192 let mut output = String::new();
193 let mut chars = input.chars();
194 loop {
195 match chars.next() {
196 None => return output,
197 Some(c) => {
198 if c == '\\' {
199 match chars.next().unwrap() {
200 '\\' => output.push('\\'),
201 'u' => {
202 let c1 = chars.next().unwrap().to_digit(16).unwrap();
203 let c2 = chars.next().unwrap().to_digit(16).unwrap();
204 let c3 = chars.next().unwrap().to_digit(16).unwrap();
205 let c4 = chars.next().unwrap().to_digit(16).unwrap();
206 match char::from_u32(((c1 * 16 + c2) * 16 + c3) * 16 + c4) {
207 Some(c) => output.push(c),
208 None => {
209 write!(&mut output, "\\u{:X}{:X}{:X}{:X}", c1, c2, c3, c4)
210 .expect("Could not write to output");
211 }
212 };
213 }
214 _ => panic!("Invalid test data input"),
215 }
216 } else {
217 output.push(c);
218 }
219 }
220 }
221 }
222 }
223
224 fn status(status: &str) -> Vec<&str> {
225 if status.is_empty() || status == "[]" {
226 return Vec::new();
227 }
228
229 let mut result = status.split(", ").collect::<Vec<_>>();
230 assert!(result[0].starts_with('['));
231 result[0] = &result[0][1..];
232
233 let idx = result.len() - 1;
234 let last = &mut result[idx];
235 assert!(last.ends_with(']'));
236 *last = &last[..last.len() - 1];
237
238 result
239 }