Skip to content

Commit

Permalink
MAINT: Clean up pandas/util/testing.py (#16271)
Browse files Browse the repository at this point in the history
Transform testing methods to use more
pytest idiom.

Also, assume that dateutil and pytz
are installed for testing because
there are core dependencies for pandas.
  • Loading branch information
gfyoung authored and jreback committed May 7, 2017
1 parent ea56550 commit d50f981
Show file tree
Hide file tree
Showing 32 changed files with 90 additions and 259 deletions.
7 changes: 3 additions & 4 deletions pandas/tests/groupby/test_timegrouper.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
""" test with the TimeGrouper / grouping with datetimes """

import pytest
import pytz

from datetime import datetime
import numpy as np
Expand Down Expand Up @@ -569,10 +570,8 @@ def test_groupby_with_timezone_selection(self):
tm.assert_series_equal(df1, df2)

def test_timezone_info(self):
# GH 11682
# Timezone info lost when broadcasting scalar datetime to DataFrame
tm._skip_if_no_pytz()
import pytz
# see gh-11682: Timezone info lost when broadcasting
# scalar datetime to DataFrame

df = pd.DataFrame({'a': [1], 'b': [datetime.now(pytz.utc)]})
assert df['b'][0].tzinfo == pytz.utc
Expand Down
22 changes: 4 additions & 18 deletions pandas/tests/indexes/datetimes/test_astype.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import pytest

import pytz
import dateutil
import numpy as np

from datetime import datetime
from dateutil.tz import tzlocal

import pandas as pd
import pandas.util.testing as tm
from pandas import (DatetimeIndex, date_range, Series, NaT, Index, Timestamp,
Expand Down Expand Up @@ -124,8 +128,6 @@ def test_astype_raises(self):
pytest.raises(ValueError, idx.astype, 'datetime64[D]')

def test_index_convert_to_datetime_array(self):
tm._skip_if_no_pytz()

def _check_rng(rng):
converted = rng.to_pydatetime()
assert isinstance(converted, np.ndarray)
Expand All @@ -143,9 +145,6 @@ def _check_rng(rng):
_check_rng(rng_utc)

def test_index_convert_to_datetime_array_explicit_pytz(self):
tm._skip_if_no_pytz()
import pytz

def _check_rng(rng):
converted = rng.to_pydatetime()
assert isinstance(converted, np.ndarray)
Expand All @@ -164,9 +163,6 @@ def _check_rng(rng):
_check_rng(rng_utc)

def test_index_convert_to_datetime_array_dateutil(self):
tm._skip_if_no_dateutil()
import dateutil

def _check_rng(rng):
converted = rng.to_pydatetime()
assert isinstance(converted, np.ndarray)
Expand Down Expand Up @@ -209,8 +205,6 @@ def test_to_period_microsecond(self):
assert period[1] == Period('2007-01-01 10:11:13.789123Z', 'U')

def test_to_period_tz_pytz(self):
tm._skip_if_no_pytz()
from dateutil.tz import tzlocal
from pytz import utc as UTC

xp = date_range('1/1/2000', '4/1/2000').to_period()
Expand Down Expand Up @@ -240,10 +234,6 @@ def test_to_period_tz_pytz(self):
tm.assert_index_equal(ts.to_period(), xp)

def test_to_period_tz_explicit_pytz(self):
tm._skip_if_no_pytz()
import pytz
from dateutil.tz import tzlocal

xp = date_range('1/1/2000', '4/1/2000').to_period()

ts = date_range('1/1/2000', '4/1/2000', tz=pytz.timezone('US/Eastern'))
Expand Down Expand Up @@ -271,10 +261,6 @@ def test_to_period_tz_explicit_pytz(self):
tm.assert_index_equal(ts.to_period(), xp)

def test_to_period_tz_dateutil(self):
tm._skip_if_no_dateutil()
import dateutil
from dateutil.tz import tzlocal

xp = date_range('1/1/2000', '4/1/2000').to_period()

ts = date_range('1/1/2000', '4/1/2000', tz='dateutil/US/Eastern')
Expand Down
8 changes: 2 additions & 6 deletions pandas/tests/indexes/datetimes/test_construction.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import pytest

import pytz
import numpy as np
from datetime import timedelta

Expand Down Expand Up @@ -350,10 +351,7 @@ def test_constructor_coverage(self):
pytest.raises(ValueError, DatetimeIndex, periods=10, freq='D')

def test_constructor_datetime64_tzformat(self):
# GH 6572
tm._skip_if_no_pytz()
import pytz
# ISO 8601 format results in pytz.FixedOffset
# see gh-6572: ISO 8601 format results in pytz.FixedOffset
for freq in ['AS', 'W-SUN']:
idx = date_range('2013-01-01T00:00:00-05:00',
'2016-01-01T23:59:59-05:00', freq=freq)
Expand All @@ -376,8 +374,6 @@ def test_constructor_datetime64_tzformat(self):
tz='Asia/Tokyo')
tm.assert_numpy_array_equal(idx.asi8, expected_i8.asi8)

tm._skip_if_no_dateutil()

# Non ISO 8601 format results in dateutil.tz.tzoffset
for freq in ['AS', 'W-SUN']:
idx = date_range('2013/1/1 0:00:00-5:00', '2016/1/1 23:59:59-5:00',
Expand Down
13 changes: 4 additions & 9 deletions pandas/tests/indexes/datetimes/test_date_range.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import pytest

import numpy as np
from pytz import timezone
from datetime import datetime, timedelta, time

import pandas as pd
Expand Down Expand Up @@ -299,10 +300,7 @@ def test_range_bug(self):
tm.assert_index_equal(result, DatetimeIndex(exp_values))

def test_range_tz_pytz(self):
# GH 2906
tm._skip_if_no_pytz()
from pytz import timezone

# see gh-2906
tz = timezone('US/Eastern')
start = tz.localize(datetime(2011, 1, 1))
end = tz.localize(datetime(2011, 1, 3))
Expand All @@ -323,9 +321,6 @@ def test_range_tz_pytz(self):
assert dr[2] == end

def test_range_tz_dst_straddle_pytz(self):

tm._skip_if_no_pytz()
from pytz import timezone
tz = timezone('US/Eastern')
dates = [(tz.localize(datetime(2014, 3, 6)),
tz.localize(datetime(2014, 3, 12))),
Expand All @@ -349,8 +344,8 @@ def test_range_tz_dst_straddle_pytz(self):
assert np.all(dr.hour == 0)

def test_range_tz_dateutil(self):
# GH 2906
tm._skip_if_no_dateutil()
# see gh-2906

# Use maybe_get_tz to fix filename in tz under dateutil.
from pandas._libs.tslib import maybe_get_tz
tz = lambda x: maybe_get_tz('dateutil/' + x)
Expand Down
7 changes: 2 additions & 5 deletions pandas/tests/indexes/datetimes/test_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import numpy as np
from datetime import date, timedelta, time

import dateutil
import pandas as pd
import pandas.util.testing as tm
from pandas.compat import lrange
Expand Down Expand Up @@ -363,11 +364,7 @@ def test_map(self):
tm.assert_index_equal(result, exp)

def test_iteration_preserves_tz(self):

tm._skip_if_no_dateutil()

# GH 8890
import dateutil
# see gh-8890
index = date_range("2012-01-01", periods=3, freq='H', tz='US/Eastern')

for i, ts in enumerate(index):
Expand Down
6 changes: 2 additions & 4 deletions pandas/tests/indexes/datetimes/test_indexing.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import pytest

import pytz
import numpy as np
import pandas as pd
import pandas.util.testing as tm
Expand Down Expand Up @@ -97,10 +98,7 @@ def test_insert(self):
assert result.name == expected.name
assert result.freq is None

# GH 7299
tm._skip_if_no_pytz()
import pytz

# see gh-7299
idx = date_range('1/1/2000', periods=3, freq='D', tz='Asia/Tokyo',
name='idx')
with pytest.raises(ValueError):
Expand Down
10 changes: 2 additions & 8 deletions pandas/tests/indexes/datetimes/test_ops.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import pytz
import pytest
import dateutil
import warnings
import numpy as np
from datetime import timedelta
Expand Down Expand Up @@ -1177,13 +1179,9 @@ def test_summary(self):
self.rng[2:2].summary()

def test_summary_pytz(self):
tm._skip_if_no_pytz()
import pytz
bdate_range('1/1/2005', '1/1/2009', tz=pytz.utc).summary()

def test_summary_dateutil(self):
tm._skip_if_no_dateutil()
import dateutil
bdate_range('1/1/2005', '1/1/2009', tz=dateutil.tz.tzutc()).summary()

def test_equals(self):
Expand Down Expand Up @@ -1279,13 +1277,9 @@ def test_summary(self):
self.rng[2:2].summary()

def test_summary_pytz(self):
tm._skip_if_no_pytz()
import pytz
cdate_range('1/1/2005', '1/1/2009', tz=pytz.utc).summary()

def test_summary_dateutil(self):
tm._skip_if_no_dateutil()
import dateutil
cdate_range('1/1/2005', '1/1/2009', tz=dateutil.tz.tzutc()).summary()

def test_equals(self):
Expand Down
3 changes: 1 addition & 2 deletions pandas/tests/indexes/datetimes/test_setops.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,6 @@ def test_intersection_bug(self):
tm.assert_index_equal(result, b)

def test_month_range_union_tz_pytz(self):
tm._skip_if_no_pytz()
from pytz import timezone
tz = timezone('US/Eastern')

Expand All @@ -325,7 +324,7 @@ def test_month_range_union_tz_pytz(self):

def test_month_range_union_tz_dateutil(self):
tm._skip_if_windows_python_3()
tm._skip_if_no_dateutil()

from pandas._libs.tslib import _dateutil_gettz as timezone
tz = timezone('US/Eastern')

Expand Down
17 changes: 4 additions & 13 deletions pandas/tests/indexes/datetimes/test_tools.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
""" test to_datetime """

import sys
import pytz
import pytest
import locale
import calendar
import dateutil
import numpy as np
from dateutil.parser import parse
from datetime import datetime, date, time
from distutils.version import LooseVersion

Expand Down Expand Up @@ -244,11 +247,7 @@ def test_to_datetime_tz(self):
pytest.raises(ValueError, lambda: pd.to_datetime(arr))

def test_to_datetime_tz_pytz(self):

# xref 8260
tm._skip_if_no_pytz()
import pytz

# see gh-8260
us_eastern = pytz.timezone('US/Eastern')
arr = np.array([us_eastern.localize(datetime(year=2000, month=1, day=1,
hour=3, minute=0)),
Expand Down Expand Up @@ -1124,8 +1123,6 @@ def test_parsers_quarter_invalid(self):
pytest.raises(ValueError, tools.parse_time_string, case)

def test_parsers_dayfirst_yearfirst(self):
tm._skip_if_no_dateutil()

# OK
# 2.5.1 10-11-12 [dayfirst=0, yearfirst=0] -> 2012-10-11 00:00:00
# 2.5.2 10-11-12 [dayfirst=0, yearfirst=1] -> 2012-10-11 00:00:00
Expand Down Expand Up @@ -1166,7 +1163,6 @@ def test_parsers_dayfirst_yearfirst(self):
# 2.5.2 20/12/21 [dayfirst=1, yearfirst=0] -> 2021-12-20 00:00:00
# 2.5.3 20/12/21 [dayfirst=1, yearfirst=0] -> 2021-12-20 00:00:00

import dateutil
is_lt_253 = dateutil.__version__ < LooseVersion('2.5.3')

# str : dayfirst, yearfirst, expected
Expand All @@ -1187,7 +1183,6 @@ def test_parsers_dayfirst_yearfirst(self):
(True, True,
datetime(2020, 12, 21))]}

from dateutil.parser import parse
for date_str, values in compat.iteritems(cases):
for dayfirst, yearfirst, expected in values:

Expand Down Expand Up @@ -1221,9 +1216,6 @@ def test_parsers_dayfirst_yearfirst(self):
assert result4 == expected

def test_parsers_timestring(self):
tm._skip_if_no_dateutil()
from dateutil.parser import parse

# must be the same as dateutil result
cases = {'10:15': (parse('10:15'), datetime(1, 1, 1, 10, 15)),
'9:05': (parse('9:05'), datetime(1, 1, 1, 9, 5))}
Expand Down Expand Up @@ -1365,7 +1357,6 @@ def test_parsers_iso8601(self):
class TestArrayToDatetime(object):

def test_try_parse_dates(self):
from dateutil.parser import parse
arr = np.array(['5/1/2000', '6/1/2000', '7/1/2000'], dtype=object)

result = lib.try_parse_dates(arr, dayfirst=True)
Expand Down
14 changes: 4 additions & 10 deletions pandas/tests/io/formats/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from __future__ import print_function
import re

import pytz
import dateutil
import itertools
from operator import methodcaller
import os
Expand Down Expand Up @@ -1548,17 +1550,15 @@ def get_ipython():

def test_pprint_pathological_object(self):
"""
if the test fails, the stack will overflow and nose crash,
but it won't hang.
If the test fails, it at least won't hang.
"""

class A:

def __getitem__(self, key):
return 3 # obviously simplified

df = DataFrame([A()])
repr(df) # just don't dine
repr(df) # just don't die

def test_float_trim_zeros(self):
vals = [2.08430917305e+10, 3.52205017305e+10, 2.30674817305e+10,
Expand Down Expand Up @@ -2508,10 +2508,6 @@ def test_no_tz(self):
assert str(ts_nanos_micros) == "1970-01-01 00:00:00.000001200"

def test_tz_pytz(self):
tm._skip_if_no_pytz()

import pytz

dt_date = datetime(2013, 1, 2, tzinfo=pytz.utc)
assert str(dt_date) == str(Timestamp(dt_date))

Expand All @@ -2522,8 +2518,6 @@ def test_tz_pytz(self):
assert str(dt_datetime_us) == str(Timestamp(dt_datetime_us))

def test_tz_dateutil(self):
tm._skip_if_no_dateutil()
import dateutil
utc = dateutil.tz.tzutc()

dt_date = datetime(2013, 1, 2, tzinfo=utc)
Expand Down
Loading

0 comments on commit d50f981

Please sign in to comment.