locale_test.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. from __future__ import absolute_import, division, print_function
  2. import datetime
  3. import os
  4. import shutil
  5. import tempfile
  6. import tornado.locale
  7. from tornado.escape import utf8, to_unicode
  8. from tornado.test.util import unittest, skipOnAppEngine
  9. from tornado.util import unicode_type
  10. class TranslationLoaderTest(unittest.TestCase):
  11. # TODO: less hacky way to get isolated tests
  12. SAVE_VARS = ['_translations', '_supported_locales', '_use_gettext']
  13. def clear_locale_cache(self):
  14. if hasattr(tornado.locale.Locale, '_cache'):
  15. del tornado.locale.Locale._cache
  16. def setUp(self):
  17. self.saved = {}
  18. for var in TranslationLoaderTest.SAVE_VARS:
  19. self.saved[var] = getattr(tornado.locale, var)
  20. self.clear_locale_cache()
  21. def tearDown(self):
  22. for k, v in self.saved.items():
  23. setattr(tornado.locale, k, v)
  24. self.clear_locale_cache()
  25. def test_csv(self):
  26. tornado.locale.load_translations(
  27. os.path.join(os.path.dirname(__file__), 'csv_translations'))
  28. locale = tornado.locale.get("fr_FR")
  29. self.assertTrue(isinstance(locale, tornado.locale.CSVLocale))
  30. self.assertEqual(locale.translate("school"), u"\u00e9cole")
  31. # tempfile.mkdtemp is not available on app engine.
  32. @skipOnAppEngine
  33. def test_csv_bom(self):
  34. with open(os.path.join(os.path.dirname(__file__), 'csv_translations',
  35. 'fr_FR.csv'), 'rb') as f:
  36. char_data = to_unicode(f.read())
  37. # Re-encode our input data (which is utf-8 without BOM) in
  38. # encodings that use the BOM and ensure that we can still load
  39. # it. Note that utf-16-le and utf-16-be do not write a BOM,
  40. # so we only test whichver variant is native to our platform.
  41. for encoding in ['utf-8-sig', 'utf-16']:
  42. tmpdir = tempfile.mkdtemp()
  43. try:
  44. with open(os.path.join(tmpdir, 'fr_FR.csv'), 'wb') as f:
  45. f.write(char_data.encode(encoding))
  46. tornado.locale.load_translations(tmpdir)
  47. locale = tornado.locale.get('fr_FR')
  48. self.assertIsInstance(locale, tornado.locale.CSVLocale)
  49. self.assertEqual(locale.translate("school"), u"\u00e9cole")
  50. finally:
  51. shutil.rmtree(tmpdir)
  52. def test_gettext(self):
  53. tornado.locale.load_gettext_translations(
  54. os.path.join(os.path.dirname(__file__), 'gettext_translations'),
  55. "tornado_test")
  56. locale = tornado.locale.get("fr_FR")
  57. self.assertTrue(isinstance(locale, tornado.locale.GettextLocale))
  58. self.assertEqual(locale.translate("school"), u"\u00e9cole")
  59. self.assertEqual(locale.pgettext("law", "right"), u"le droit")
  60. self.assertEqual(locale.pgettext("good", "right"), u"le bien")
  61. self.assertEqual(locale.pgettext("organization", "club", "clubs", 1), u"le club")
  62. self.assertEqual(locale.pgettext("organization", "club", "clubs", 2), u"les clubs")
  63. self.assertEqual(locale.pgettext("stick", "club", "clubs", 1), u"le b\xe2ton")
  64. self.assertEqual(locale.pgettext("stick", "club", "clubs", 2), u"les b\xe2tons")
  65. class LocaleDataTest(unittest.TestCase):
  66. def test_non_ascii_name(self):
  67. name = tornado.locale.LOCALE_NAMES['es_LA']['name']
  68. self.assertTrue(isinstance(name, unicode_type))
  69. self.assertEqual(name, u'Espa\u00f1ol')
  70. self.assertEqual(utf8(name), b'Espa\xc3\xb1ol')
  71. class EnglishTest(unittest.TestCase):
  72. def test_format_date(self):
  73. locale = tornado.locale.get('en_US')
  74. date = datetime.datetime(2013, 4, 28, 18, 35)
  75. self.assertEqual(locale.format_date(date, full_format=True),
  76. 'April 28, 2013 at 6:35 pm')
  77. now = datetime.datetime.utcnow()
  78. self.assertEqual(locale.format_date(now - datetime.timedelta(seconds=2), full_format=False),
  79. '2 seconds ago')
  80. self.assertEqual(locale.format_date(now - datetime.timedelta(minutes=2), full_format=False),
  81. '2 minutes ago')
  82. self.assertEqual(locale.format_date(now - datetime.timedelta(hours=2), full_format=False),
  83. '2 hours ago')
  84. self.assertEqual(locale.format_date(now - datetime.timedelta(days=1),
  85. full_format=False, shorter=True), 'yesterday')
  86. date = now - datetime.timedelta(days=2)
  87. self.assertEqual(locale.format_date(date, full_format=False, shorter=True),
  88. locale._weekdays[date.weekday()])
  89. date = now - datetime.timedelta(days=300)
  90. self.assertEqual(locale.format_date(date, full_format=False, shorter=True),
  91. '%s %d' % (locale._months[date.month - 1], date.day))
  92. date = now - datetime.timedelta(days=500)
  93. self.assertEqual(locale.format_date(date, full_format=False, shorter=True),
  94. '%s %d, %d' % (locale._months[date.month - 1], date.day, date.year))
  95. def test_friendly_number(self):
  96. locale = tornado.locale.get('en_US')
  97. self.assertEqual(locale.friendly_number(1000000), '1,000,000')
  98. def test_list(self):
  99. locale = tornado.locale.get('en_US')
  100. self.assertEqual(locale.list([]), '')
  101. self.assertEqual(locale.list(['A']), 'A')
  102. self.assertEqual(locale.list(['A', 'B']), 'A and B')
  103. self.assertEqual(locale.list(['A', 'B', 'C']), 'A, B and C')
  104. def test_format_day(self):
  105. locale = tornado.locale.get('en_US')
  106. date = datetime.datetime(2013, 4, 28, 18, 35)
  107. self.assertEqual(locale.format_day(date=date, dow=True), 'Sunday, April 28')
  108. self.assertEqual(locale.format_day(date=date, dow=False), 'April 28')