test_idna_codec.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/env python
  2. import codecs
  3. import sys
  4. import unittest
  5. import idna.codec
  6. class IDNACodecTests(unittest.TestCase):
  7. def testCodec(self):
  8. pass
  9. def testIncrementalDecoder(self):
  10. # Tests derived from Python standard library test/test_codecs.py
  11. incremental_tests = (
  12. (u"python.org", b"python.org"),
  13. (u"python.org.", b"python.org."),
  14. (u"pyth\xf6n.org", b"xn--pythn-mua.org"),
  15. (u"pyth\xf6n.org.", b"xn--pythn-mua.org."),
  16. )
  17. for decoded, encoded in incremental_tests:
  18. if sys.version_info[0] == 2:
  19. self.assertEqual("".join(codecs.iterdecode(encoded, "idna")),
  20. decoded)
  21. else:
  22. self.assertEqual("".join(codecs.iterdecode((bytes([c]) for c in encoded), "idna")),
  23. decoded)
  24. decoder = codecs.getincrementaldecoder("idna")()
  25. self.assertEqual(decoder.decode(b"xn--xam", ), u"")
  26. self.assertEqual(decoder.decode(b"ple-9ta.o", ), u"\xe4xample.")
  27. self.assertEqual(decoder.decode(b"rg"), u"")
  28. self.assertEqual(decoder.decode(b"", True), u"org")
  29. decoder.reset()
  30. self.assertEqual(decoder.decode(b"xn--xam", ), u"")
  31. self.assertEqual(decoder.decode(b"ple-9ta.o", ), u"\xe4xample.")
  32. self.assertEqual(decoder.decode(b"rg."), u"org.")
  33. self.assertEqual(decoder.decode(b"", True), u"")
  34. def testIncrementalEncoder(self):
  35. # Tests derived from Python standard library test/test_codecs.py
  36. incremental_tests = (
  37. (u"python.org", b"python.org"),
  38. (u"python.org.", b"python.org."),
  39. (u"pyth\xf6n.org", b"xn--pythn-mua.org"),
  40. (u"pyth\xf6n.org.", b"xn--pythn-mua.org."),
  41. )
  42. for decoded, encoded in incremental_tests:
  43. self.assertEqual(b"".join(codecs.iterencode(decoded, "idna")),
  44. encoded)
  45. encoder = codecs.getincrementalencoder("idna")()
  46. self.assertEqual(encoder.encode(u"\xe4x"), b"")
  47. self.assertEqual(encoder.encode(u"ample.org"), b"xn--xample-9ta.")
  48. self.assertEqual(encoder.encode(u"", True), b"org")
  49. encoder.reset()
  50. self.assertEqual(encoder.encode(u"\xe4x"), b"")
  51. self.assertEqual(encoder.encode(u"ample.org."), b"xn--xample-9ta.org.")
  52. self.assertEqual(encoder.encode(u"", True), b"")
  53. if __name__ == '__main__':
  54. unittest.main()