punycode.rs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2013 Simon Sapin.
  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. use idna::punycode::{decode, encode_str};
  9. use rustc_serialize::json::{Json, Object};
  10. fn one_test(description: &str, decoded: &str, encoded: &str) {
  11. match decode(encoded) {
  12. None => panic!("Decoding {} failed.", encoded),
  13. Some(result) => {
  14. let result = result.into_iter().collect::<String>();
  15. assert!(result == decoded,
  16. format!("Incorrect decoding of {}:\n {}\n!= {}\n{}",
  17. encoded, result, decoded, description))
  18. }
  19. }
  20. match encode_str(decoded) {
  21. None => panic!("Encoding {} failed.", decoded),
  22. Some(result) => {
  23. assert!(result == encoded,
  24. format!("Incorrect encoding of {}:\n {}\n!= {}\n{}",
  25. decoded, result, encoded, description))
  26. }
  27. }
  28. }
  29. fn get_string<'a>(map: &'a Object, key: &str) -> &'a str {
  30. match map.get(&key.to_string()) {
  31. Some(&Json::String(ref s)) => s,
  32. None => "",
  33. _ => panic!(),
  34. }
  35. }
  36. #[test]
  37. fn test_punycode() {
  38. match Json::from_str(include_str!("punycode_tests.json")) {
  39. Ok(Json::Array(tests)) => for test in &tests {
  40. match test {
  41. &Json::Object(ref o) => one_test(
  42. get_string(o, "description"),
  43. get_string(o, "decoded"),
  44. get_string(o, "encoded")
  45. ),
  46. _ => panic!(),
  47. }
  48. },
  49. other => panic!("{:?}", other)
  50. }
  51. }