Skip to content

Commit ab274c2

Browse files
ginggsTomAugspurger
authored andcommitted
Fix Python2 test failures in certain locales (#22213)
* Fix Python2 test failures in certain locales Check that we can also get the locale, after setting it, without raising an Exception. Closes: #22129
1 parent d09db1f commit ab274c2

File tree

2 files changed

+28
-11
lines changed

2 files changed

+28
-11
lines changed

pandas/tests/util/test_util.py

+20
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,26 @@ def teardown_class(cls):
433433
del cls.locales
434434
del cls.current_locale
435435

436+
def test_can_set_locale_valid_set(self):
437+
# Setting the default locale should return True
438+
assert tm.can_set_locale('') is True
439+
440+
def test_can_set_locale_invalid_set(self):
441+
# Setting an invalid locale should return False
442+
assert tm.can_set_locale('non-existent_locale') is False
443+
444+
def test_can_set_locale_invalid_get(self, monkeypatch):
445+
# In some cases, an invalid locale can be set,
446+
# but a subsequent getlocale() raises a ValueError
447+
# See GH 22129
448+
449+
def mockgetlocale():
450+
raise ValueError()
451+
452+
with monkeypatch.context() as m:
453+
m.setattr(locale, 'getlocale', mockgetlocale)
454+
assert tm.can_set_locale('') is False
455+
436456
def test_get_locales(self):
437457
# all systems should have at least a single locale
438458
assert len(tm.get_locales()) > 0

pandas/util/testing.py

+8-11
Original file line numberDiff line numberDiff line change
@@ -504,23 +504,19 @@ def set_locale(new_locale, lc_var=locale.LC_ALL):
504504

505505
try:
506506
locale.setlocale(lc_var, new_locale)
507-
508-
try:
509-
normalized_locale = locale.getlocale()
510-
except ValueError:
511-
yield new_locale
507+
normalized_locale = locale.getlocale()
508+
if com._all_not_none(*normalized_locale):
509+
yield '.'.join(normalized_locale)
512510
else:
513-
if com._all_not_none(*normalized_locale):
514-
yield '.'.join(normalized_locale)
515-
else:
516-
yield new_locale
511+
yield new_locale
517512
finally:
518513
locale.setlocale(lc_var, current_locale)
519514

520515

521516
def can_set_locale(lc, lc_var=locale.LC_ALL):
522517
"""
523-
Check to see if we can set a locale without raising an Exception.
518+
Check to see if we can set a locale, and subsequently get the locale,
519+
without raising an Exception.
524520
525521
Parameters
526522
----------
@@ -538,7 +534,8 @@ def can_set_locale(lc, lc_var=locale.LC_ALL):
538534
try:
539535
with set_locale(lc, lc_var=lc_var):
540536
pass
541-
except locale.Error: # horrible name for a Exception subclass
537+
except (ValueError,
538+
locale.Error): # horrible name for a Exception subclass
542539
return False
543540
else:
544541
return True

0 commit comments

Comments
 (0)