punycode.rs 1.5 KB

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