Skip to content

Commit d177852

Browse files
author
Sylvain MARIE
committed
Added test representative of pandas-dev#46319. Should fail on CI
1 parent 48d5159 commit d177852

File tree

1 file changed

+47
-1
lines changed

1 file changed

+47
-1
lines changed

pandas/tests/io/formats/test_format.py

+47-1
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,13 @@
22
Test output formatting for Series/DataFrame, including to_string & reprs
33
"""
44

5-
from datetime import datetime
5+
from datetime import (
6+
datetime,
7+
time,
8+
)
69
from io import StringIO
710
import itertools
11+
import locale
812
from operator import methodcaller
913
import os
1014
from pathlib import Path
@@ -47,6 +51,13 @@
4751
use_32bit_repr = is_platform_windows() or not IS64
4852

4953

54+
def get_local_am_pm():
55+
"""Return the AM and PM strings returned by strftime in current locale."""
56+
am_local = time(1).strftime("%p")
57+
pm_local = time(13).strftime("%p")
58+
return am_local, pm_local
59+
60+
5061
@pytest.fixture(params=["string", "pathlike", "buffer"])
5162
def filepath_or_buffer_id(request):
5263
"""
@@ -3167,6 +3178,41 @@ def test_str(self):
31673178
assert str(NaT) == "NaT"
31683179

31693180

3181+
class TestPeriodIndexFormat:
3182+
def test_period_custom_locale(self, overridden_locale):
3183+
# GH#46319 locale-specific formatting directive leads to non-utf8 str result
3184+
3185+
# Get locale-specific reference
3186+
am_local, pm_local = get_local_am_pm()
3187+
3188+
# Scalar
3189+
per = pd.Period("2018-03-11 13:00", freq="H")
3190+
assert per.strftime("%p") == pm_local
3191+
3192+
# Index
3193+
per = pd.period_range("2003-01-01 01:00:00", periods=2, freq="12h")
3194+
formatted = per.format(date_format="%y %I:%M:%S%p")
3195+
assert formatted[0] == f"03 01:00:00{am_local}"
3196+
assert formatted[1] == f"03 01:00:00{pm_local}"
3197+
3198+
3199+
@pytest.fixture(params=[None, "fr_FR", "zh_CN"])
3200+
def overridden_locale(request):
3201+
"""A fixture used to temporarily change the locale"""
3202+
old = locale.setlocale(locale.LC_ALL)
3203+
target = request.param
3204+
if target is None:
3205+
yield old
3206+
else:
3207+
try:
3208+
locale.setlocale(locale.LC_ALL, target)
3209+
except locale.Error as e:
3210+
pytest.skip(f"Skipping as locale cannot be set. {type(e).__name__}: {e}")
3211+
else:
3212+
yield target
3213+
locale.setlocale(locale.LC_ALL, old)
3214+
3215+
31703216
class TestDatetimeIndexFormat:
31713217
def test_datetime(self):
31723218
formatted = pd.to_datetime([datetime(2003, 1, 1, 12), NaT]).format()

0 commit comments

Comments
 (0)