Skip to content

Commit 25401fc

Browse files
jbrockmendelnickleus27
authored andcommitted
TST: collect/share Index tests (pandas-dev#44413)
1 parent 7483ee9 commit 25401fc

20 files changed

+301
-331
lines changed

pandas/tests/frame/indexing/test_setitem.py

+13
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,19 @@
4444

4545

4646
class TestDataFrameSetItem:
47+
def test_setitem_str_subclass(self):
48+
# GH#37366
49+
class mystring(str):
50+
pass
51+
52+
data = ["2020-10-22 01:21:00+00:00"]
53+
index = DatetimeIndex(data)
54+
df = DataFrame({"a": [1]}, index=index)
55+
df["b"] = 2
56+
df[mystring("c")] = 3
57+
expected = DataFrame({"a": [1], "b": [2], mystring("c"): [3]}, index=index)
58+
tm.assert_equal(df, expected)
59+
4760
@pytest.mark.parametrize("dtype", ["int32", "int64", "float32", "float64"])
4861
def test_setitem_dtype(self, dtype, float_frame):
4962
arr = np.random.randn(len(float_frame))

pandas/tests/indexes/base_class/test_formats.py

+14
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,14 @@ def test_repr_summary(self):
122122
assert len(result) < 200
123123
assert "..." in result
124124

125+
def test_summary_bug(self):
126+
# GH#3869
127+
ind = Index(["{other}%s", "~:{range}:0"], name="A")
128+
result = ind._summary()
129+
# shouldn't be formatted accidentally.
130+
assert "~:{range}:0" in result
131+
assert "{other}%s" in result
132+
125133
def test_index_repr_bool_nan(self):
126134
# GH32146
127135
arr = Index([True, False, np.nan], dtype=object)
@@ -132,3 +140,9 @@ def test_index_repr_bool_nan(self):
132140
exp2 = repr(arr)
133141
out2 = "Index([True, False, nan], dtype='object')"
134142
assert out2 == exp2
143+
144+
def test_format_different_scalar_lengths(self):
145+
# GH#35439
146+
idx = Index(["aaaaaaaaa", "b"])
147+
expected = ["aaaaaaaaa", "b"]
148+
assert idx.format() == expected

pandas/tests/indexes/common.py

-60
Original file line numberDiff line numberDiff line change
@@ -69,26 +69,6 @@ def test_pickle_compat_construction(self):
6969
with pytest.raises(TypeError, match=msg):
7070
self._index_cls()
7171

72-
@pytest.mark.parametrize("name", [None, "new_name"])
73-
def test_to_frame(self, name, simple_index):
74-
# see GH-15230, GH-22580
75-
idx = simple_index
76-
77-
if name:
78-
idx_name = name
79-
else:
80-
idx_name = idx.name or 0
81-
82-
df = idx.to_frame(name=idx_name)
83-
84-
assert df.index is idx
85-
assert len(df.columns) == 1
86-
assert df.columns[0] == idx_name
87-
assert df[idx_name].values is not idx.values
88-
89-
df = idx.to_frame(index=False, name=idx_name)
90-
assert df.index is not idx
91-
9272
def test_shift(self, simple_index):
9373

9474
# GH8083 test the base class for shift
@@ -226,46 +206,6 @@ def test_repr_max_seq_item_setting(self, simple_index):
226206
repr(idx)
227207
assert "..." not in str(idx)
228208

229-
def test_copy_name(self, index):
230-
# gh-12309: Check that the "name" argument
231-
# passed at initialization is honored.
232-
if isinstance(index, MultiIndex):
233-
return
234-
235-
first = type(index)(index, copy=True, name="mario")
236-
second = type(first)(first, copy=False)
237-
238-
# Even though "copy=False", we want a new object.
239-
assert first is not second
240-
241-
# Not using tm.assert_index_equal() since names differ.
242-
assert index.equals(first)
243-
244-
assert first.name == "mario"
245-
assert second.name == "mario"
246-
247-
s1 = Series(2, index=first)
248-
s2 = Series(3, index=second[:-1])
249-
250-
if not isinstance(index, CategoricalIndex):
251-
# See gh-13365
252-
s3 = s1 * s2
253-
assert s3.index.name == "mario"
254-
255-
def test_copy_name2(self, index):
256-
# gh-35592
257-
if isinstance(index, MultiIndex):
258-
return
259-
260-
assert index.copy(name="mario").name == "mario"
261-
262-
with pytest.raises(ValueError, match="Length of new names must be 1, got 2"):
263-
index.copy(name=["mario", "luigi"])
264-
265-
msg = f"{type(index).__name__}.name must be a hashable type"
266-
with pytest.raises(TypeError, match=msg):
267-
index.copy(name=[["mario"]])
268-
269209
def test_ensure_copied_data(self, index):
270210
# Check the "copy" argument of each Index.__new__ is honoured
271211
# GH12309

pandas/tests/indexes/datetimes/test_formats.py

+17
Original file line numberDiff line numberDiff line change
@@ -254,3 +254,20 @@ def test_dti_custom_business_summary_dateutil(self):
254254
pd.bdate_range(
255255
"1/1/2005", "1/1/2009", freq="C", tz=dateutil.tz.tzutc()
256256
)._summary()
257+
258+
259+
class TestFormat:
260+
def test_format_with_name_time_info(self):
261+
# bug I fixed 12/20/2011
262+
dates = pd.date_range("2011-01-01 04:00:00", periods=10, name="something")
263+
264+
formatted = dates.format(name=True)
265+
assert formatted[0] == "something"
266+
267+
def test_format_datetime_with_time(self):
268+
dti = DatetimeIndex([datetime(2012, 2, 7), datetime(2012, 2, 7, 23)])
269+
270+
result = dti.format()
271+
expected = ["2012-02-07 00:00:00", "2012-02-07 23:00:00"]
272+
assert len(result) == 2
273+
assert result == expected

pandas/tests/indexes/datetimes/test_indexing.py

+15-48
Original file line numberDiff line numberDiff line change
@@ -21,25 +21,12 @@
2121
)
2222
import pandas._testing as tm
2323

24-
from pandas.tseries.offsets import (
25-
BDay,
26-
CDay,
27-
)
24+
from pandas.tseries.frequencies import to_offset
2825

2926
START, END = datetime(2009, 1, 1), datetime(2010, 1, 1)
3027

3128

3229
class TestGetItem:
33-
def test_ellipsis(self):
34-
# GH#21282
35-
idx = date_range(
36-
"2011-01-01", "2011-01-31", freq="D", tz="Asia/Tokyo", name="idx"
37-
)
38-
39-
result = idx[...]
40-
assert result.equals(idx)
41-
assert result is not idx
42-
4330
def test_getitem_slice_keeps_name(self):
4431
# GH4226
4532
st = Timestamp("2013-07-01 00:00:00", tz="America/Los_Angeles")
@@ -88,44 +75,17 @@ def test_getitem(self):
8875
tm.assert_index_equal(result, expected)
8976
assert result.freq == expected.freq
9077

91-
def test_dti_business_getitem(self):
92-
rng = bdate_range(START, END)
93-
smaller = rng[:5]
94-
exp = DatetimeIndex(rng.view(np.ndarray)[:5], freq="B")
95-
tm.assert_index_equal(smaller, exp)
96-
assert smaller.freq == exp.freq
97-
98-
assert smaller.freq == rng.freq
99-
100-
sliced = rng[::5]
101-
assert sliced.freq == BDay() * 5
102-
103-
fancy_indexed = rng[[4, 3, 2, 1, 0]]
104-
assert len(fancy_indexed) == 5
105-
assert isinstance(fancy_indexed, DatetimeIndex)
106-
assert fancy_indexed.freq is None
107-
108-
# 32-bit vs. 64-bit platforms
109-
assert rng[4] == rng[np.int_(4)]
110-
111-
def test_dti_business_getitem_matplotlib_hackaround(self):
112-
rng = bdate_range(START, END)
113-
with tm.assert_produces_warning(FutureWarning):
114-
# GH#30588 multi-dimensional indexing deprecated
115-
values = rng[:, None]
116-
expected = rng.values[:, None]
117-
tm.assert_numpy_array_equal(values, expected)
118-
119-
def test_dti_custom_getitem(self):
120-
rng = bdate_range(START, END, freq="C")
78+
@pytest.mark.parametrize("freq", ["B", "C"])
79+
def test_dti_business_getitem(self, freq):
80+
rng = bdate_range(START, END, freq=freq)
12181
smaller = rng[:5]
122-
exp = DatetimeIndex(rng.view(np.ndarray)[:5], freq="C")
82+
exp = DatetimeIndex(rng.view(np.ndarray)[:5], freq=freq)
12383
tm.assert_index_equal(smaller, exp)
12484
assert smaller.freq == exp.freq
12585
assert smaller.freq == rng.freq
12686

12787
sliced = rng[::5]
128-
assert sliced.freq == CDay() * 5
88+
assert sliced.freq == to_offset(freq) * 5
12989

13090
fancy_indexed = rng[[4, 3, 2, 1, 0]]
13191
assert len(fancy_indexed) == 5
@@ -135,8 +95,9 @@ def test_dti_custom_getitem(self):
13595
# 32-bit vs. 64-bit platforms
13696
assert rng[4] == rng[np.int_(4)]
13797

138-
def test_dti_custom_getitem_matplotlib_hackaround(self):
139-
rng = bdate_range(START, END, freq="C")
98+
@pytest.mark.parametrize("freq", ["B", "C"])
99+
def test_dti_business_getitem_matplotlib_hackaround(self, freq):
100+
rng = bdate_range(START, END, freq=freq)
140101
with tm.assert_produces_warning(FutureWarning):
141102
# GH#30588 multi-dimensional indexing deprecated
142103
values = rng[:, None]
@@ -255,6 +216,12 @@ def test_where_tz(self):
255216

256217

257218
class TestTake:
219+
def test_take_nan_first_datetime(self):
220+
index = DatetimeIndex([pd.NaT, Timestamp("20130101"), Timestamp("20130102")])
221+
result = index.take([-1, 0, 1])
222+
expected = DatetimeIndex([index[-1], index[0], index[1]])
223+
tm.assert_index_equal(result, expected)
224+
258225
def test_take(self):
259226
# GH#10295
260227
idx1 = date_range("2011-01-01", "2011-01-31", freq="D", name="idx")

pandas/tests/indexes/interval/test_indexing.py

+35
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
Interval,
1212
IntervalIndex,
1313
NaT,
14+
Series,
1415
Timedelta,
1516
date_range,
1617
timedelta_range,
@@ -523,3 +524,37 @@ def test_putmask_td64(self):
523524
result = idx.putmask(mask, idx[-1])
524525
expected = IntervalIndex([idx[-1]] * 3 + list(idx[3:]))
525526
tm.assert_index_equal(result, expected)
527+
528+
529+
class TestGetValue:
530+
@pytest.mark.parametrize("key", [[5], (2, 3)])
531+
def test_get_value_non_scalar_errors(self, key):
532+
# GH#31117
533+
idx = IntervalIndex.from_tuples([(1, 3), (2, 4), (3, 5), (7, 10), (3, 10)])
534+
ser = Series(range(len(idx)), index=idx)
535+
536+
msg = str(key)
537+
with pytest.raises(InvalidIndexError, match=msg):
538+
with tm.assert_produces_warning(FutureWarning):
539+
idx.get_value(ser, key)
540+
541+
542+
class TestContains:
543+
# .__contains__, not .contains
544+
545+
def test_contains_dunder(self):
546+
547+
index = IntervalIndex.from_arrays([0, 1], [1, 2], closed="right")
548+
549+
# __contains__ requires perfect matches to intervals.
550+
assert 0 not in index
551+
assert 1 not in index
552+
assert 2 not in index
553+
554+
assert Interval(0, 1, closed="right") in index
555+
assert Interval(0, 2, closed="right") not in index
556+
assert Interval(0, 0.5, closed="right") not in index
557+
assert Interval(3, 5, closed="right") not in index
558+
assert Interval(-1, 0, closed="left") not in index
559+
assert Interval(0, 1, closed="left") not in index
560+
assert Interval(0, 1, closed="both") not in index

pandas/tests/indexes/interval/test_interval.py

-37
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@
44
import numpy as np
55
import pytest
66

7-
from pandas.errors import InvalidIndexError
8-
97
import pandas as pd
108
from pandas import (
119
Index,
@@ -500,23 +498,6 @@ def test_contains_method(self):
500498
):
501499
i.contains(Interval(0, 1))
502500

503-
def test_contains_dunder(self):
504-
505-
index = IntervalIndex.from_arrays([0, 1], [1, 2], closed="right")
506-
507-
# __contains__ requires perfect matches to intervals.
508-
assert 0 not in index
509-
assert 1 not in index
510-
assert 2 not in index
511-
512-
assert Interval(0, 1, closed="right") in index
513-
assert Interval(0, 2, closed="right") not in index
514-
assert Interval(0, 0.5, closed="right") not in index
515-
assert Interval(3, 5, closed="right") not in index
516-
assert Interval(-1, 0, closed="left") not in index
517-
assert Interval(0, 1, closed="left") not in index
518-
assert Interval(0, 1, closed="both") not in index
519-
520501
def test_dropna(self, closed):
521502

522503
expected = IntervalIndex.from_tuples([(0.0, 1.0), (1.0, 2.0)], closed=closed)
@@ -908,24 +889,6 @@ def test_is_all_dates(self):
908889
year_2017_index = IntervalIndex([year_2017])
909890
assert not year_2017_index._is_all_dates
910891

911-
@pytest.mark.parametrize("key", [[5], (2, 3)])
912-
def test_get_value_non_scalar_errors(self, key):
913-
# GH 31117
914-
idx = IntervalIndex.from_tuples([(1, 3), (2, 4), (3, 5), (7, 10), (3, 10)])
915-
s = pd.Series(range(len(idx)), index=idx)
916-
917-
msg = str(key)
918-
with pytest.raises(InvalidIndexError, match=msg):
919-
with tm.assert_produces_warning(FutureWarning):
920-
idx.get_value(s, key)
921-
922-
@pytest.mark.parametrize("closed", ["left", "right", "both"])
923-
def test_pickle_round_trip_closed(self, closed):
924-
# https://github.com/pandas-dev/pandas/issues/35658
925-
idx = IntervalIndex.from_tuples([(1, 2), (2, 3)], closed=closed)
926-
result = tm.round_trip_pickle(idx)
927-
tm.assert_index_equal(result, idx)
928-
929892

930893
def test_dir():
931894
# GH#27571 dir(interval_index) should not raise
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import pytest
2+
3+
from pandas import IntervalIndex
4+
import pandas._testing as tm
5+
6+
7+
class TestPickle:
8+
@pytest.mark.parametrize("closed", ["left", "right", "both"])
9+
def test_pickle_round_trip_closed(self, closed):
10+
# https://github.com/pandas-dev/pandas/issues/35658
11+
idx = IntervalIndex.from_tuples([(1, 2), (2, 3)], closed=closed)
12+
result = tm.round_trip_pickle(idx)
13+
tm.assert_index_equal(result, idx)

pandas/tests/indexes/multi/test_compat.py

-7
Original file line numberDiff line numberDiff line change
@@ -96,10 +96,3 @@ def test_inplace_mutation_resets_values():
9696
assert "_values" not in mi2._cache
9797
tm.assert_almost_equal(mi2.values, new_values)
9898
assert "_values" in mi2._cache
99-
100-
101-
def test_pickle_compat_construction():
102-
# this is testing for pickle compat
103-
# need an object to create with
104-
with pytest.raises(TypeError, match="Must pass both levels and codes"):
105-
MultiIndex()
+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import pytest
2+
3+
from pandas import MultiIndex
4+
5+
6+
def test_pickle_compat_construction():
7+
# this is testing for pickle compat
8+
# need an object to create with
9+
with pytest.raises(TypeError, match="Must pass both levels and codes"):
10+
MultiIndex()

pandas/tests/indexes/period/test_indexing.py

-8
Original file line numberDiff line numberDiff line change
@@ -52,14 +52,6 @@ def non_comparable_idx(request):
5252

5353

5454
class TestGetItem:
55-
def test_ellipsis(self):
56-
# GH#21282
57-
idx = period_range("2011-01-01", "2011-01-31", freq="D", name="idx")
58-
59-
result = idx[...]
60-
assert result.equals(idx)
61-
assert result is not idx
62-
6355
def test_getitem_slice_keeps_name(self):
6456
idx = period_range("20010101", periods=10, freq="D", name="bob")
6557
assert idx.name == idx[1:].name

0 commit comments

Comments
 (0)