Skip to content

TST: collect/share Index tests #44413

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions pandas/tests/frame/indexing/test_setitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,19 @@


class TestDataFrameSetItem:
def test_setitem_str_subclass(self):
# GH#37366
class mystring(str):
pass

data = ["2020-10-22 01:21:00+00:00"]
index = DatetimeIndex(data)
df = DataFrame({"a": [1]}, index=index)
df["b"] = 2
df[mystring("c")] = 3
expected = DataFrame({"a": [1], "b": [2], mystring("c"): [3]}, index=index)
tm.assert_equal(df, expected)

@pytest.mark.parametrize("dtype", ["int32", "int64", "float32", "float64"])
def test_setitem_dtype(self, dtype, float_frame):
arr = np.random.randn(len(float_frame))
Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/indexes/base_class/test_formats.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,14 @@ def test_repr_summary(self):
assert len(result) < 200
assert "..." in result

def test_summary_bug(self):
# GH#3869
ind = Index(["{other}%s", "~:{range}:0"], name="A")
result = ind._summary()
# shouldn't be formatted accidentally.
assert "~:{range}:0" in result
assert "{other}%s" in result

def test_index_repr_bool_nan(self):
# GH32146
arr = Index([True, False, np.nan], dtype=object)
Expand All @@ -132,3 +140,9 @@ def test_index_repr_bool_nan(self):
exp2 = repr(arr)
out2 = "Index([True, False, nan], dtype='object')"
assert out2 == exp2

def test_format_different_scalar_lengths(self):
# GH#35439
idx = Index(["aaaaaaaaa", "b"])
expected = ["aaaaaaaaa", "b"]
assert idx.format() == expected
60 changes: 0 additions & 60 deletions pandas/tests/indexes/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,26 +69,6 @@ def test_pickle_compat_construction(self):
with pytest.raises(TypeError, match=msg):
self._index_cls()

@pytest.mark.parametrize("name", [None, "new_name"])
def test_to_frame(self, name, simple_index):
# see GH-15230, GH-22580
idx = simple_index

if name:
idx_name = name
else:
idx_name = idx.name or 0

df = idx.to_frame(name=idx_name)

assert df.index is idx
assert len(df.columns) == 1
assert df.columns[0] == idx_name
assert df[idx_name].values is not idx.values

df = idx.to_frame(index=False, name=idx_name)
assert df.index is not idx

def test_shift(self, simple_index):

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

def test_copy_name(self, index):
# gh-12309: Check that the "name" argument
# passed at initialization is honored.
if isinstance(index, MultiIndex):
return

first = type(index)(index, copy=True, name="mario")
second = type(first)(first, copy=False)

# Even though "copy=False", we want a new object.
assert first is not second

# Not using tm.assert_index_equal() since names differ.
assert index.equals(first)

assert first.name == "mario"
assert second.name == "mario"

s1 = Series(2, index=first)
s2 = Series(3, index=second[:-1])

if not isinstance(index, CategoricalIndex):
# See gh-13365
s3 = s1 * s2
assert s3.index.name == "mario"

def test_copy_name2(self, index):
# gh-35592
if isinstance(index, MultiIndex):
return

assert index.copy(name="mario").name == "mario"

with pytest.raises(ValueError, match="Length of new names must be 1, got 2"):
index.copy(name=["mario", "luigi"])

msg = f"{type(index).__name__}.name must be a hashable type"
with pytest.raises(TypeError, match=msg):
index.copy(name=[["mario"]])

def test_ensure_copied_data(self, index):
# Check the "copy" argument of each Index.__new__ is honoured
# GH12309
Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/indexes/datetimes/test_formats.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,3 +254,20 @@ def test_dti_custom_business_summary_dateutil(self):
pd.bdate_range(
"1/1/2005", "1/1/2009", freq="C", tz=dateutil.tz.tzutc()
)._summary()


class TestFormat:
def test_format_with_name_time_info(self):
# bug I fixed 12/20/2011
dates = pd.date_range("2011-01-01 04:00:00", periods=10, name="something")

formatted = dates.format(name=True)
assert formatted[0] == "something"

def test_format_datetime_with_time(self):
dti = DatetimeIndex([datetime(2012, 2, 7), datetime(2012, 2, 7, 23)])

result = dti.format()
expected = ["2012-02-07 00:00:00", "2012-02-07 23:00:00"]
assert len(result) == 2
assert result == expected
63 changes: 15 additions & 48 deletions pandas/tests/indexes/datetimes/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,25 +21,12 @@
)
import pandas._testing as tm

from pandas.tseries.offsets import (
BDay,
CDay,
)
from pandas.tseries.frequencies import to_offset

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


class TestGetItem:
def test_ellipsis(self):
# GH#21282
idx = date_range(
"2011-01-01", "2011-01-31", freq="D", tz="Asia/Tokyo", name="idx"
)

result = idx[...]
assert result.equals(idx)
assert result is not idx

def test_getitem_slice_keeps_name(self):
# GH4226
st = Timestamp("2013-07-01 00:00:00", tz="America/Los_Angeles")
Expand Down Expand Up @@ -88,44 +75,17 @@ def test_getitem(self):
tm.assert_index_equal(result, expected)
assert result.freq == expected.freq

def test_dti_business_getitem(self):
rng = bdate_range(START, END)
smaller = rng[:5]
exp = DatetimeIndex(rng.view(np.ndarray)[:5], freq="B")
tm.assert_index_equal(smaller, exp)
assert smaller.freq == exp.freq

assert smaller.freq == rng.freq

sliced = rng[::5]
assert sliced.freq == BDay() * 5

fancy_indexed = rng[[4, 3, 2, 1, 0]]
assert len(fancy_indexed) == 5
assert isinstance(fancy_indexed, DatetimeIndex)
assert fancy_indexed.freq is None

# 32-bit vs. 64-bit platforms
assert rng[4] == rng[np.int_(4)]

def test_dti_business_getitem_matplotlib_hackaround(self):
rng = bdate_range(START, END)
with tm.assert_produces_warning(FutureWarning):
# GH#30588 multi-dimensional indexing deprecated
values = rng[:, None]
expected = rng.values[:, None]
tm.assert_numpy_array_equal(values, expected)

def test_dti_custom_getitem(self):
rng = bdate_range(START, END, freq="C")
@pytest.mark.parametrize("freq", ["B", "C"])
def test_dti_business_getitem(self, freq):
rng = bdate_range(START, END, freq=freq)
smaller = rng[:5]
exp = DatetimeIndex(rng.view(np.ndarray)[:5], freq="C")
exp = DatetimeIndex(rng.view(np.ndarray)[:5], freq=freq)
tm.assert_index_equal(smaller, exp)
assert smaller.freq == exp.freq
assert smaller.freq == rng.freq

sliced = rng[::5]
assert sliced.freq == CDay() * 5
assert sliced.freq == to_offset(freq) * 5

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

def test_dti_custom_getitem_matplotlib_hackaround(self):
rng = bdate_range(START, END, freq="C")
@pytest.mark.parametrize("freq", ["B", "C"])
def test_dti_business_getitem_matplotlib_hackaround(self, freq):
rng = bdate_range(START, END, freq=freq)
with tm.assert_produces_warning(FutureWarning):
# GH#30588 multi-dimensional indexing deprecated
values = rng[:, None]
Expand Down Expand Up @@ -255,6 +216,12 @@ def test_where_tz(self):


class TestTake:
def test_take_nan_first_datetime(self):
index = DatetimeIndex([pd.NaT, Timestamp("20130101"), Timestamp("20130102")])
result = index.take([-1, 0, 1])
expected = DatetimeIndex([index[-1], index[0], index[1]])
tm.assert_index_equal(result, expected)

def test_take(self):
# GH#10295
idx1 = date_range("2011-01-01", "2011-01-31", freq="D", name="idx")
Expand Down
35 changes: 35 additions & 0 deletions pandas/tests/indexes/interval/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
Interval,
IntervalIndex,
NaT,
Series,
Timedelta,
date_range,
timedelta_range,
Expand Down Expand Up @@ -523,3 +524,37 @@ def test_putmask_td64(self):
result = idx.putmask(mask, idx[-1])
expected = IntervalIndex([idx[-1]] * 3 + list(idx[3:]))
tm.assert_index_equal(result, expected)


class TestGetValue:
@pytest.mark.parametrize("key", [[5], (2, 3)])
def test_get_value_non_scalar_errors(self, key):
# GH#31117
idx = IntervalIndex.from_tuples([(1, 3), (2, 4), (3, 5), (7, 10), (3, 10)])
ser = Series(range(len(idx)), index=idx)

msg = str(key)
with pytest.raises(InvalidIndexError, match=msg):
with tm.assert_produces_warning(FutureWarning):
idx.get_value(ser, key)


class TestContains:
# .__contains__, not .contains

def test_contains_dunder(self):

index = IntervalIndex.from_arrays([0, 1], [1, 2], closed="right")

# __contains__ requires perfect matches to intervals.
assert 0 not in index
assert 1 not in index
assert 2 not in index

assert Interval(0, 1, closed="right") in index
assert Interval(0, 2, closed="right") not in index
assert Interval(0, 0.5, closed="right") not in index
assert Interval(3, 5, closed="right") not in index
assert Interval(-1, 0, closed="left") not in index
assert Interval(0, 1, closed="left") not in index
assert Interval(0, 1, closed="both") not in index
37 changes: 0 additions & 37 deletions pandas/tests/indexes/interval/test_interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
import numpy as np
import pytest

from pandas.errors import InvalidIndexError

import pandas as pd
from pandas import (
Index,
Expand Down Expand Up @@ -500,23 +498,6 @@ def test_contains_method(self):
):
i.contains(Interval(0, 1))

def test_contains_dunder(self):

index = IntervalIndex.from_arrays([0, 1], [1, 2], closed="right")

# __contains__ requires perfect matches to intervals.
assert 0 not in index
assert 1 not in index
assert 2 not in index

assert Interval(0, 1, closed="right") in index
assert Interval(0, 2, closed="right") not in index
assert Interval(0, 0.5, closed="right") not in index
assert Interval(3, 5, closed="right") not in index
assert Interval(-1, 0, closed="left") not in index
assert Interval(0, 1, closed="left") not in index
assert Interval(0, 1, closed="both") not in index

def test_dropna(self, closed):

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

@pytest.mark.parametrize("key", [[5], (2, 3)])
def test_get_value_non_scalar_errors(self, key):
# GH 31117
idx = IntervalIndex.from_tuples([(1, 3), (2, 4), (3, 5), (7, 10), (3, 10)])
s = pd.Series(range(len(idx)), index=idx)

msg = str(key)
with pytest.raises(InvalidIndexError, match=msg):
with tm.assert_produces_warning(FutureWarning):
idx.get_value(s, key)

@pytest.mark.parametrize("closed", ["left", "right", "both"])
def test_pickle_round_trip_closed(self, closed):
# https://github.com/pandas-dev/pandas/issues/35658
idx = IntervalIndex.from_tuples([(1, 2), (2, 3)], closed=closed)
result = tm.round_trip_pickle(idx)
tm.assert_index_equal(result, idx)


def test_dir():
# GH#27571 dir(interval_index) should not raise
Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/indexes/interval/test_pickle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import pytest

from pandas import IntervalIndex
import pandas._testing as tm


class TestPickle:
@pytest.mark.parametrize("closed", ["left", "right", "both"])
def test_pickle_round_trip_closed(self, closed):
# https://github.com/pandas-dev/pandas/issues/35658
idx = IntervalIndex.from_tuples([(1, 2), (2, 3)], closed=closed)
result = tm.round_trip_pickle(idx)
tm.assert_index_equal(result, idx)
7 changes: 0 additions & 7 deletions pandas/tests/indexes/multi/test_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,3 @@ def test_inplace_mutation_resets_values():
assert "_values" not in mi2._cache
tm.assert_almost_equal(mi2.values, new_values)
assert "_values" in mi2._cache


def test_pickle_compat_construction():
# this is testing for pickle compat
# need an object to create with
with pytest.raises(TypeError, match="Must pass both levels and codes"):
MultiIndex()
10 changes: 10 additions & 0 deletions pandas/tests/indexes/multi/test_pickle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import pytest

from pandas import MultiIndex


def test_pickle_compat_construction():
# this is testing for pickle compat
# need an object to create with
with pytest.raises(TypeError, match="Must pass both levels and codes"):
MultiIndex()
8 changes: 0 additions & 8 deletions pandas/tests/indexes/period/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,6 @@ def non_comparable_idx(request):


class TestGetItem:
def test_ellipsis(self):
# GH#21282
idx = period_range("2011-01-01", "2011-01-31", freq="D", name="idx")

result = idx[...]
assert result.equals(idx)
assert result is not idx

def test_getitem_slice_keeps_name(self):
idx = period_range("20010101", periods=10, freq="D", name="bob")
assert idx.name == idx[1:].name
Expand Down
Loading