1 // Copyright 2013 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 use crate::test::TestFn;
10 use idna::punycode::{decode, encode_str};
11 use serde_json::map::Map;
12 use serde_json::Value;
13 use std::str::FromStr;
14
one_test(decoded: &str, encoded: &str)15 fn one_test(decoded: &str, encoded: &str) {
16 match decode(encoded) {
17 None => panic!("Decoding {} failed.", encoded),
18 Some(result) => {
19 let result = result.into_iter().collect::<String>();
20 assert!(
21 result == decoded,
22 "Incorrect decoding of \"{}\":\n \"{}\"\n!= \"{}\"\n",
23 encoded,
24 result,
25 decoded
26 )
27 }
28 }
29
30 match encode_str(decoded) {
31 None => panic!("Encoding {} failed.", decoded),
32 Some(result) => assert!(
33 result == encoded,
34 "Incorrect encoding of \"{}\":\n \"{}\"\n!= \"{}\"\n",
35 decoded,
36 result,
37 encoded
38 ),
39 }
40 }
41
get_string<'a>(map: &'a Map<String, Value>, key: &str) -> &'a str42 fn get_string<'a>(map: &'a Map<String, Value>, key: &str) -> &'a str {
43 match map.get(&key.to_string()) {
44 Some(&Value::String(ref s)) => s,
45 None => "",
46 _ => panic!(),
47 }
48 }
49
collect_tests<F: FnMut(String, TestFn)>(add_test: &mut F)50 pub fn collect_tests<F: FnMut(String, TestFn)>(add_test: &mut F) {
51 match Value::from_str(include_str!("punycode_tests.json")) {
52 Ok(Value::Array(tests)) => {
53 for (i, test) in tests.into_iter().enumerate() {
54 match test {
55 Value::Object(o) => {
56 let test_name = {
57 let desc = get_string(&o, "description");
58 if desc.is_empty() {
59 format!("Punycode {}", i + 1)
60 } else {
61 format!("Punycode {}: {}", i + 1, desc)
62 }
63 };
64 add_test(
65 test_name,
66 TestFn::dyn_test_fn(move || {
67 one_test(get_string(&o, "decoded"), get_string(&o, "encoded"))
68 }),
69 )
70 }
71 _ => panic!(),
72 }
73 }
74 }
75 other => panic!("{:?}", other),
76 }
77 }
78