_locales.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. """Provide class for testing in French locale
  2. """
  3. import sys
  4. import locale
  5. import pytest
  6. __ALL__ = ['CommaDecimalPointLocale']
  7. def find_comma_decimal_point_locale():
  8. """See if platform has a decimal point as comma locale.
  9. Find a locale that uses a comma instead of a period as the
  10. decimal point.
  11. Returns
  12. -------
  13. old_locale: str
  14. Locale when the function was called.
  15. new_locale: {str, None)
  16. First French locale found, None if none found.
  17. """
  18. if sys.platform == 'win32':
  19. locales = ['FRENCH']
  20. else:
  21. locales = ['fr_FR', 'fr_FR.UTF-8', 'fi_FI', 'fi_FI.UTF-8']
  22. old_locale = locale.getlocale(locale.LC_NUMERIC)
  23. new_locale = None
  24. try:
  25. for loc in locales:
  26. try:
  27. locale.setlocale(locale.LC_NUMERIC, loc)
  28. new_locale = loc
  29. break
  30. except locale.Error:
  31. pass
  32. finally:
  33. locale.setlocale(locale.LC_NUMERIC, locale=old_locale)
  34. return old_locale, new_locale
  35. class CommaDecimalPointLocale:
  36. """Sets LC_NUMERIC to a locale with comma as decimal point.
  37. Classes derived from this class have setup and teardown methods that run
  38. tests with locale.LC_NUMERIC set to a locale where commas (',') are used as
  39. the decimal point instead of periods ('.'). On exit the locale is restored
  40. to the initial locale. It also serves as context manager with the same
  41. effect. If no such locale is available, the test is skipped.
  42. .. versionadded:: 1.15.0
  43. """
  44. (cur_locale, tst_locale) = find_comma_decimal_point_locale()
  45. def setup_method(self):
  46. if self.tst_locale is None:
  47. pytest.skip("No French locale available")
  48. locale.setlocale(locale.LC_NUMERIC, locale=self.tst_locale)
  49. def teardown_method(self):
  50. locale.setlocale(locale.LC_NUMERIC, locale=self.cur_locale)
  51. def __enter__(self):
  52. if self.tst_locale is None:
  53. pytest.skip("No French locale available")
  54. locale.setlocale(locale.LC_NUMERIC, locale=self.tst_locale)
  55. def __exit__(self, type, value, traceback):
  56. locale.setlocale(locale.LC_NUMERIC, locale=self.cur_locale)