Skip to content

REF/TST: collect index tests #44377

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 11, 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
46 changes: 46 additions & 0 deletions pandas/tests/indexes/datetimelike_/test_is_monotonic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from pandas import (
Index,
NaT,
date_range,
)


def test_is_monotonic_with_nat():
# GH#31437
# PeriodIndex.is_monotonic should behave analogously to DatetimeIndex,
# in particular never be monotonic when we have NaT
dti = date_range("2016-01-01", periods=3)
pi = dti.to_period("D")
tdi = Index(dti.view("timedelta64[ns]"))

for obj in [pi, pi._engine, dti, dti._engine, tdi, tdi._engine]:
if isinstance(obj, Index):
# i.e. not Engines
assert obj.is_monotonic
assert obj.is_monotonic_increasing
assert not obj.is_monotonic_decreasing
assert obj.is_unique

dti1 = dti.insert(0, NaT)
pi1 = dti1.to_period("D")
tdi1 = Index(dti1.view("timedelta64[ns]"))

for obj in [pi1, pi1._engine, dti1, dti1._engine, tdi1, tdi1._engine]:
if isinstance(obj, Index):
# i.e. not Engines
assert not obj.is_monotonic
assert not obj.is_monotonic_increasing
assert not obj.is_monotonic_decreasing
assert obj.is_unique

dti2 = dti.insert(3, NaT)
pi2 = dti2.to_period("H")
tdi2 = Index(dti2.view("timedelta64[ns]"))

for obj in [pi2, pi2._engine, dti2, dti2._engine, tdi2, tdi2._engine]:
if isinstance(obj, Index):
# i.e. not Engines
assert not obj.is_monotonic
assert not obj.is_monotonic_increasing
assert not obj.is_monotonic_decreasing
assert obj.is_unique
20 changes: 20 additions & 0 deletions pandas/tests/indexes/datetimes/methods/test_isocalendar.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from pandas import (
DataFrame,
DatetimeIndex,
)
import pandas._testing as tm


def test_isocalendar_returns_correct_values_close_to_new_year_with_tz():
# GH#6538: Check that DatetimeIndex and its TimeStamp elements
# return the same weekofyear accessor close to new year w/ tz
dates = ["2013/12/29", "2013/12/30", "2013/12/31"]
dates = DatetimeIndex(dates, tz="Europe/Brussels")
result = dates.isocalendar()
expected_data_frame = DataFrame(
[[2013, 52, 7], [2014, 1, 1], [2014, 1, 2]],
columns=["year", "week", "day"],
index=dates,
dtype="UInt32",
)
tm.assert_frame_equal(result, expected_data_frame)
17 changes: 17 additions & 0 deletions pandas/tests/indexes/datetimes/test_asof.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
from datetime import timedelta

from pandas import (
Index,
Timestamp,
date_range,
isna,
)
import pandas._testing as tm


class TestAsOf:
Expand All @@ -12,3 +16,16 @@ def test_asof_partial(self):
result = index.asof("2010-02")
assert result == expected
assert not isinstance(result, Index)

def test_asof(self):
index = tm.makeDateIndex(100)

dt = index[0]
assert index.asof(dt) == dt
assert isna(index.asof(dt - timedelta(1)))

dt = index[-1]
assert index.asof(dt + timedelta(1)) == dt

dt = index[0].to_pydatetime()
assert isinstance(index.asof(dt), Timestamp)
61 changes: 61 additions & 0 deletions pandas/tests/indexes/datetimes/test_freq_attr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import pytest

from pandas import (
DatetimeIndex,
date_range,
)

from pandas.tseries.offsets import (
BDay,
DateOffset,
Day,
Hour,
)


class TestFreq:
def test_freq_setter_errors(self):
# GH#20678
idx = DatetimeIndex(["20180101", "20180103", "20180105"])

# setting with an incompatible freq
msg = (
"Inferred frequency 2D from passed values does not conform to "
"passed frequency 5D"
)
with pytest.raises(ValueError, match=msg):
idx._data.freq = "5D"

# setting with non-freq string
with pytest.raises(ValueError, match="Invalid frequency"):
idx._data.freq = "foo"

@pytest.mark.parametrize("values", [["20180101", "20180103", "20180105"], []])
@pytest.mark.parametrize("freq", ["2D", Day(2), "2B", BDay(2), "48H", Hour(48)])
@pytest.mark.parametrize("tz", [None, "US/Eastern"])
def test_freq_setter(self, values, freq, tz):
# GH#20678
idx = DatetimeIndex(values, tz=tz)

# can set to an offset, converting from string if necessary
idx._data.freq = freq
assert idx.freq == freq
assert isinstance(idx.freq, DateOffset)

# can reset to None
idx._data.freq = None
assert idx.freq is None

def test_freq_view_safe(self):
# Setting the freq for one DatetimeIndex shouldn't alter the freq
# for another that views the same data

dti = date_range("2016-01-01", periods=5)
dta = dti._data

dti2 = DatetimeIndex(dta)._with_freq(None)
assert dti2.freq is None

# Original was not altered
assert dti.freq == "D"
assert dta.freq == "D"
15 changes: 0 additions & 15 deletions pandas/tests/indexes/datetimes/test_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,21 +297,6 @@ def test_week_and_weekofyear_are_deprecated():
idx.weekofyear


def test_isocalendar_returns_correct_values_close_to_new_year_with_tz():
# GH 6538: Check that DatetimeIndex and its TimeStamp elements
# return the same weekofyear accessor close to new year w/ tz
dates = ["2013/12/29", "2013/12/30", "2013/12/31"]
dates = DatetimeIndex(dates, tz="Europe/Brussels")
result = dates.isocalendar()
expected_data_frame = pd.DataFrame(
[[2013, 52, 7], [2014, 1, 1], [2014, 1, 2]],
columns=["year", "week", "day"],
index=dates,
dtype="UInt32",
)
tm.assert_frame_equal(result, expected_data_frame)


def test_add_timedelta_preserves_freq():
# GH#37295 should hold for any DTI with freq=None or Tick freq
tz = "Canada/Eastern"
Expand Down
113 changes: 13 additions & 100 deletions pandas/tests/indexes/datetimes/test_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,43 +6,17 @@
from pandas.compat import IS64

from pandas import (
DateOffset,
DatetimeIndex,
Index,
Series,
bdate_range,
date_range,
)
import pandas._testing as tm

from pandas.tseries.offsets import (
BDay,
Day,
Hour,
)

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


class TestDatetimeIndexOps:
def test_ops_properties_basic(self, datetime_series):

# sanity check that the behavior didn't change
# GH#7206
for op in ["year", "day", "second", "weekday"]:
msg = f"'Series' object has no attribute '{op}'"
with pytest.raises(AttributeError, match=msg):
getattr(datetime_series, op)

# attribute access should still work!
s = Series({"year": 2000, "month": 1, "day": 10})
assert s.year == 2000
assert s.month == 1
assert s.day == 10
msg = "'Series' object has no attribute 'weekday'"
with pytest.raises(AttributeError, match=msg):
s.weekday

@pytest.mark.parametrize(
"freq,expected",
[
Expand Down Expand Up @@ -74,72 +48,28 @@ def test_infer_freq(self, freq_sample):
tm.assert_index_equal(idx, result)
assert result.freq == freq_sample

@pytest.mark.parametrize("values", [["20180101", "20180103", "20180105"], []])
@pytest.mark.parametrize("freq", ["2D", Day(2), "2B", BDay(2), "48H", Hour(48)])
@pytest.mark.parametrize("tz", [None, "US/Eastern"])
def test_freq_setter(self, values, freq, tz):
# GH 20678
idx = DatetimeIndex(values, tz=tz)

# can set to an offset, converting from string if necessary
idx._data.freq = freq
assert idx.freq == freq
assert isinstance(idx.freq, DateOffset)

# can reset to None
idx._data.freq = None
assert idx.freq is None

def test_freq_setter_errors(self):
# GH 20678
idx = DatetimeIndex(["20180101", "20180103", "20180105"])

# setting with an incompatible freq
msg = (
"Inferred frequency 2D from passed values does not conform to "
"passed frequency 5D"
)
with pytest.raises(ValueError, match=msg):
idx._data.freq = "5D"

# setting with non-freq string
with pytest.raises(ValueError, match="Invalid frequency"):
idx._data.freq = "foo"

def test_freq_view_safe(self):
# Setting the freq for one DatetimeIndex shouldn't alter the freq
# for another that views the same data

dti = date_range("2016-01-01", periods=5)
dta = dti._data

dti2 = DatetimeIndex(dta)._with_freq(None)
assert dti2.freq is None

# Original was not altered
assert dti.freq == "D"
assert dta.freq == "D"


@pytest.mark.parametrize("freq", ["B", "C"])
class TestBusinessDatetimeIndex:
def setup_method(self, method):
self.rng = bdate_range(START, END)
@pytest.fixture
def rng(self, freq):
return bdate_range(START, END, freq=freq)

def test_comparison(self):
d = self.rng[10]
def test_comparison(self, rng):
d = rng[10]

comp = self.rng > d
comp = rng > d
assert comp[11]
assert not comp[9]

def test_copy(self):
cp = self.rng.copy()
def test_copy(self, rng):
cp = rng.copy()
repr(cp)
tm.assert_index_equal(cp, self.rng)
tm.assert_index_equal(cp, rng)

def test_identical(self):
t1 = self.rng.copy()
t2 = self.rng.copy()
def test_identical(self, rng):
t1 = rng.copy()
t2 = rng.copy()
assert t1.identical(t2)

# name
Expand All @@ -153,20 +83,3 @@ def test_identical(self):
t2v = Index(t2.values)
assert t1.equals(t2v)
assert not t1.identical(t2v)


class TestCustomDatetimeIndex:
def setup_method(self, method):
self.rng = bdate_range(START, END, freq="C")

def test_comparison(self):
d = self.rng[10]

comp = self.rng > d
assert comp[11]
assert not comp[9]

def test_copy(self):
cp = self.rng.copy()
repr(cp)
tm.assert_index_equal(cp, self.rng)
21 changes: 21 additions & 0 deletions pandas/tests/indexes/period/test_freq_attr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import pytest

from pandas import (
offsets,
period_range,
)
import pandas._testing as tm


class TestFreq:
def test_freq_setter_deprecated(self):
# GH#20678
idx = period_range("2018Q1", periods=4, freq="Q")

# no warning for getter
with tm.assert_produces_warning(None):
idx.freq

# warning for setter
with pytest.raises(AttributeError, match="can't set attribute"):
idx.freq = offsets.Day()
Loading