test_locale.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # -*- coding: utf-8 -*-
  2. import codecs
  3. import locale
  4. import os
  5. import pytest
  6. from pandas.compat import is_platform_windows
  7. import pandas.core.common as com
  8. import pandas.util.testing as tm
  9. _all_locales = tm.get_locales() or []
  10. _current_locale = locale.getlocale()
  11. # Don't run any of these tests if we are on Windows or have no locales.
  12. pytestmark = pytest.mark.skipif(is_platform_windows() or not _all_locales,
  13. reason="Need non-Windows and locales")
  14. _skip_if_only_one_locale = pytest.mark.skipif(
  15. len(_all_locales) <= 1, reason="Need multiple locales for meaningful test")
  16. def test_can_set_locale_valid_set():
  17. # Can set the default locale.
  18. assert tm.can_set_locale("")
  19. def test_can_set_locale_invalid_set():
  20. # Cannot set an invalid locale.
  21. assert not tm.can_set_locale("non-existent_locale")
  22. def test_can_set_locale_invalid_get(monkeypatch):
  23. # see gh-22129
  24. #
  25. # In some cases, an invalid locale can be set,
  26. # but a subsequent getlocale() raises a ValueError.
  27. def mock_get_locale():
  28. raise ValueError()
  29. with monkeypatch.context() as m:
  30. m.setattr(locale, "getlocale", mock_get_locale)
  31. assert not tm.can_set_locale("")
  32. def test_get_locales_at_least_one():
  33. # see gh-9744
  34. assert len(_all_locales) > 0
  35. @_skip_if_only_one_locale
  36. def test_get_locales_prefix():
  37. first_locale = _all_locales[0]
  38. assert len(tm.get_locales(prefix=first_locale[:2])) > 0
  39. @_skip_if_only_one_locale
  40. def test_set_locale():
  41. if com._all_none(_current_locale):
  42. # Not sure why, but on some Travis runs with pytest,
  43. # getlocale() returned (None, None).
  44. pytest.skip("Current locale is not set.")
  45. locale_override = os.environ.get("LOCALE_OVERRIDE", None)
  46. if locale_override is None:
  47. lang, enc = "it_CH", "UTF-8"
  48. elif locale_override == "C":
  49. lang, enc = "en_US", "ascii"
  50. else:
  51. lang, enc = locale_override.split(".")
  52. enc = codecs.lookup(enc).name
  53. new_locale = lang, enc
  54. if not tm.can_set_locale(new_locale):
  55. msg = "unsupported locale setting"
  56. with pytest.raises(locale.Error, match=msg):
  57. with tm.set_locale(new_locale):
  58. pass
  59. else:
  60. with tm.set_locale(new_locale) as normalized_locale:
  61. new_lang, new_enc = normalized_locale.split(".")
  62. new_enc = codecs.lookup(enc).name
  63. normalized_locale = new_lang, new_enc
  64. assert normalized_locale == new_locale
  65. # Once we exit the "with" statement, locale should be back to what it was.
  66. current_locale = locale.getlocale()
  67. assert current_locale == _current_locale