Skip to content

Commit bd5e1df

Browse files
authored
TST: split/parametrize (#44805)
1 parent fac3b21 commit bd5e1df

File tree

4 files changed

+91
-88
lines changed

4 files changed

+91
-88
lines changed

pandas/_testing/asserters.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1385,7 +1385,8 @@ def assert_equal(left, right, **kwargs):
13851385
assert kwargs == {}
13861386
assert left == right
13871387
else:
1388-
raise NotImplementedError(type(left))
1388+
assert kwargs == {}
1389+
assert_almost_equal(left, right)
13891390

13901391

13911392
def assert_sp_array_equal(left, right):

pandas/tests/frame/methods/test_convert.py

+2
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ def test_convert_objects(self, float_string_frame):
4545
with pytest.raises(ValueError, match="invalid literal"):
4646
converted["H"].astype("int32")
4747

48+
def test_convert_mixed_single_column(self):
49+
# GH#4119, not converting a mixed type (e.g.floats and object)
4850
# mixed in a single column
4951
df = DataFrame({"s": Series([1, "na", 3, 4])})
5052
result = df._convert(datetime=True, numeric=True)

pandas/tests/series/accessors/test_cat_accessor.py

+61-68
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,6 @@
1414
timedelta_range,
1515
)
1616
import pandas._testing as tm
17-
from pandas.core.arrays import (
18-
DatetimeArray,
19-
PeriodArray,
20-
TimedeltaArray,
21-
)
2217
from pandas.core.arrays.categorical import CategoricalAccessor
2318
from pandas.core.indexes.accessors import Properties
2419

@@ -163,86 +158,84 @@ def test_categorical_delegations(self):
163158
)
164159
tm.assert_series_equal(result, expected)
165160

166-
def test_dt_accessor_api_for_categorical(self):
161+
@pytest.mark.parametrize(
162+
"idx",
163+
[
164+
date_range("1/1/2015", periods=5),
165+
date_range("1/1/2015", periods=5, tz="MET"),
166+
period_range("1/1/2015", freq="D", periods=5),
167+
timedelta_range("1 days", "10 days"),
168+
],
169+
)
170+
def test_dt_accessor_api_for_categorical(self, idx):
167171
# https://github.com/pandas-dev/pandas/issues/10661
168172

169-
s_dr = Series(date_range("1/1/2015", periods=5, tz="MET"))
170-
c_dr = s_dr.astype("category")
171-
172-
s_pr = Series(period_range("1/1/2015", freq="D", periods=5))
173-
c_pr = s_pr.astype("category")
174-
175-
s_tdr = Series(timedelta_range("1 days", "10 days"))
176-
c_tdr = s_tdr.astype("category")
173+
ser = Series(idx)
174+
cat = ser.astype("category")
177175

178176
# only testing field (like .day)
179177
# and bool (is_month_start)
180-
get_ops = lambda x: x._datetimelike_ops
181-
182-
test_data = [
183-
("Datetime", get_ops(DatetimeArray), s_dr, c_dr),
184-
("Period", get_ops(PeriodArray), s_pr, c_pr),
185-
("Timedelta", get_ops(TimedeltaArray), s_tdr, c_tdr),
186-
]
178+
attr_names = type(ser._values)._datetimelike_ops
187179

188-
assert isinstance(c_dr.dt, Properties)
180+
assert isinstance(cat.dt, Properties)
189181

190182
special_func_defs = [
191183
("strftime", ("%Y-%m-%d",), {}),
192-
("tz_convert", ("EST",), {}),
193184
("round", ("D",), {}),
194185
("floor", ("D",), {}),
195186
("ceil", ("D",), {}),
196187
("asfreq", ("D",), {}),
197-
# FIXME: don't leave commented-out
198-
# ('tz_localize', ("UTC",), {}),
199188
]
189+
if idx.dtype == "M8[ns]":
190+
# exclude dt64tz since that is already localized and would raise
191+
tup = ("tz_localize", ("UTC",), {})
192+
special_func_defs.append(tup)
193+
elif idx.dtype.kind == "M":
194+
# exclude dt64 since that is not localized so would raise
195+
tup = ("tz_convert", ("EST",), {})
196+
special_func_defs.append(tup)
197+
200198
_special_func_names = [f[0] for f in special_func_defs]
201199

202-
# the series is already localized
203-
_ignore_names = ["tz_localize", "components"]
204-
205-
for name, attr_names, s, c in test_data:
206-
func_names = [
207-
f
208-
for f in dir(s.dt)
209-
if not (
210-
f.startswith("_")
211-
or f in attr_names
212-
or f in _special_func_names
213-
or f in _ignore_names
214-
)
215-
]
216-
217-
func_defs = [(f, (), {}) for f in func_names]
218-
for f_def in special_func_defs:
219-
if f_def[0] in dir(s.dt):
220-
func_defs.append(f_def)
221-
222-
for func, args, kwargs in func_defs:
223-
with warnings.catch_warnings():
224-
if func == "to_period":
225-
# dropping TZ
226-
warnings.simplefilter("ignore", UserWarning)
227-
res = getattr(c.dt, func)(*args, **kwargs)
228-
exp = getattr(s.dt, func)(*args, **kwargs)
229-
230-
tm.assert_equal(res, exp)
231-
232-
for attr in attr_names:
233-
if attr in ["week", "weekofyear"]:
234-
# GH#33595 Deprecate week and weekofyear
235-
continue
236-
res = getattr(c.dt, attr)
237-
exp = getattr(s.dt, attr)
238-
239-
if isinstance(res, DataFrame):
240-
tm.assert_frame_equal(res, exp)
241-
elif isinstance(res, Series):
242-
tm.assert_series_equal(res, exp)
243-
else:
244-
tm.assert_almost_equal(res, exp)
200+
_ignore_names = ["components", "tz_localize", "tz_convert"]
201+
202+
func_names = [
203+
fname
204+
for fname in dir(ser.dt)
205+
if not (
206+
fname.startswith("_")
207+
or fname in attr_names
208+
or fname in _special_func_names
209+
or fname in _ignore_names
210+
)
211+
]
212+
213+
func_defs = [(fname, (), {}) for fname in func_names]
214+
215+
for f_def in special_func_defs:
216+
if f_def[0] in dir(ser.dt):
217+
func_defs.append(f_def)
218+
219+
for func, args, kwargs in func_defs:
220+
with warnings.catch_warnings():
221+
if func == "to_period":
222+
# dropping TZ
223+
warnings.simplefilter("ignore", UserWarning)
224+
res = getattr(cat.dt, func)(*args, **kwargs)
225+
exp = getattr(ser.dt, func)(*args, **kwargs)
226+
227+
tm.assert_equal(res, exp)
228+
229+
for attr in attr_names:
230+
if attr in ["week", "weekofyear"]:
231+
# GH#33595 Deprecate week and weekofyear
232+
continue
233+
res = getattr(cat.dt, attr)
234+
exp = getattr(ser.dt, attr)
235+
236+
tm.assert_equal(res, exp)
245237

238+
def test_dt_accessor_api_for_categorical_invalid(self):
246239
invalid = Series([1, 2, 3]).astype("category")
247240
msg = "Can only use .dt accessor with datetimelike"
248241

pandas/tests/series/methods/test_convert.py

+26-19
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ def test_convert(self):
3232
results = ser._convert(timedelta=True)
3333
tm.assert_series_equal(results, ser)
3434

35+
def test_convert_numeric_strings_with_other_true_args(self):
3536
# test pass-through and non-conversion when other types selected
3637
ser = Series(["1.0", "2.0", "3.0"])
3738
results = ser._convert(datetime=True, numeric=True, timedelta=True)
@@ -40,6 +41,7 @@ def test_convert(self):
4041
results = ser._convert(True, False, True)
4142
tm.assert_series_equal(results, ser)
4243

44+
def test_convert_datetime_objects(self):
4345
ser = Series(
4446
[datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 1, 0, 0)], dtype="O"
4547
)
@@ -49,6 +51,27 @@ def test_convert(self):
4951
results = ser._convert(datetime=False, numeric=True, timedelta=True)
5052
tm.assert_series_equal(results, ser)
5153

54+
def test_convert_datetime64(self):
55+
# no-op if already dt64 dtype
56+
ser = Series(
57+
[
58+
datetime(2001, 1, 1, 0, 0),
59+
datetime(2001, 1, 2, 0, 0),
60+
datetime(2001, 1, 3, 0, 0),
61+
]
62+
)
63+
64+
result = ser._convert(datetime=True)
65+
expected = Series(
66+
[Timestamp("20010101"), Timestamp("20010102"), Timestamp("20010103")],
67+
dtype="M8[ns]",
68+
)
69+
tm.assert_series_equal(result, expected)
70+
71+
result = ser._convert(datetime=True)
72+
tm.assert_series_equal(result, expected)
73+
74+
def test_convert_timedeltas(self):
5275
td = datetime(2001, 1, 1, 0, 0) - datetime(2000, 1, 1, 0, 0)
5376
ser = Series([td, td], dtype="O")
5477
results = ser._convert(datetime=True, numeric=True, timedelta=True)
@@ -57,6 +80,7 @@ def test_convert(self):
5780
results = ser._convert(True, True, False)
5881
tm.assert_series_equal(results, ser)
5982

83+
def test_convert_numeric_strings(self):
6084
ser = Series([1.0, 2, 3], index=["a", "b", "c"])
6185
result = ser._convert(numeric=True)
6286
tm.assert_series_equal(result, ser)
@@ -79,6 +103,7 @@ def test_convert(self):
79103
expected["a"] = np.nan
80104
tm.assert_series_equal(result, expected)
81105

106+
def test_convert_mixed_type_noop(self):
82107
# GH 4119, not converting a mixed type (e.g.floats and object)
83108
ser = Series([1, "na", 3, 4])
84109
result = ser._convert(datetime=True, numeric=True)
@@ -89,25 +114,7 @@ def test_convert(self):
89114
result = ser._convert(datetime=True, numeric=True)
90115
tm.assert_series_equal(result, expected)
91116

92-
# dates
93-
ser = Series(
94-
[
95-
datetime(2001, 1, 1, 0, 0),
96-
datetime(2001, 1, 2, 0, 0),
97-
datetime(2001, 1, 3, 0, 0),
98-
]
99-
)
100-
101-
result = ser._convert(datetime=True)
102-
expected = Series(
103-
[Timestamp("20010101"), Timestamp("20010102"), Timestamp("20010103")],
104-
dtype="M8[ns]",
105-
)
106-
tm.assert_series_equal(result, expected)
107-
108-
result = ser._convert(datetime=True)
109-
tm.assert_series_equal(result, expected)
110-
117+
def test_convert_preserve_non_object(self):
111118
# preserve if non-object
112119
ser = Series([1], dtype="float32")
113120
result = ser._convert(datetime=True)

0 commit comments

Comments
 (0)