From d50f981d768c3f9b870b8eb0be8f50783467e3be Mon Sep 17 00:00:00 2001 From: gfyoung Date: Sun, 7 May 2017 17:40:58 -0400 Subject: [PATCH] MAINT: Clean up pandas/util/testing.py (#16271) 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. --- pandas/tests/groupby/test_timegrouper.py | 7 +- pandas/tests/indexes/datetimes/test_astype.py | 22 ++---- .../indexes/datetimes/test_construction.py | 8 +-- .../indexes/datetimes/test_date_range.py | 13 ++-- .../tests/indexes/datetimes/test_datetime.py | 7 +- .../tests/indexes/datetimes/test_indexing.py | 6 +- pandas/tests/indexes/datetimes/test_ops.py | 10 +-- pandas/tests/indexes/datetimes/test_setops.py | 3 +- pandas/tests/indexes/datetimes/test_tools.py | 17 ++--- pandas/tests/io/formats/test_format.py | 14 ++-- pandas/tests/io/json/test_ujson.py | 10 ++- pandas/tests/io/test_pytables.py | 1 - pandas/tests/plotting/common.py | 2 +- pandas/tests/plotting/test_boxplot_method.py | 2 +- pandas/tests/plotting/test_datetimelike.py | 2 +- pandas/tests/plotting/test_deprecated.py | 2 +- pandas/tests/plotting/test_frame.py | 2 +- pandas/tests/plotting/test_groupby.py | 2 +- pandas/tests/plotting/test_hist_method.py | 2 +- pandas/tests/plotting/test_misc.py | 2 +- pandas/tests/plotting/test_series.py | 2 +- pandas/tests/reshape/test_concat.py | 4 +- pandas/tests/scalar/test_period.py | 3 +- pandas/tests/scalar/test_timestamp.py | 52 ++++---------- pandas/tests/series/test_combine_concat.py | 10 +-- pandas/tests/series/test_indexing.py | 3 - pandas/tests/series/test_operators.py | 5 +- pandas/tests/test_multilevel.py | 6 +- pandas/tests/test_resample.py | 12 ++-- pandas/tests/tseries/test_offsets.py | 8 +-- pandas/tests/tseries/test_timezones.py | 42 +++--------- pandas/util/testing.py | 68 ++++--------------- 32 files changed, 90 insertions(+), 259 deletions(-) diff --git a/pandas/tests/groupby/test_timegrouper.py b/pandas/tests/groupby/test_timegrouper.py index 2196318d1920e..70b6b1e439691 100644 --- a/pandas/tests/groupby/test_timegrouper.py +++ b/pandas/tests/groupby/test_timegrouper.py @@ -1,6 +1,7 @@ """ test with the TimeGrouper / grouping with datetimes """ import pytest +import pytz from datetime import datetime import numpy as np @@ -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 diff --git a/pandas/tests/indexes/datetimes/test_astype.py b/pandas/tests/indexes/datetimes/test_astype.py index 0f7acf1febae8..46be24b90faae 100644 --- a/pandas/tests/indexes/datetimes/test_astype.py +++ b/pandas/tests/indexes/datetimes/test_astype.py @@ -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, @@ -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) @@ -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) @@ -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) @@ -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() @@ -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')) @@ -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') diff --git a/pandas/tests/indexes/datetimes/test_construction.py b/pandas/tests/indexes/datetimes/test_construction.py index fcfc56ea823da..cf896b06130a2 100644 --- a/pandas/tests/indexes/datetimes/test_construction.py +++ b/pandas/tests/indexes/datetimes/test_construction.py @@ -1,5 +1,6 @@ import pytest +import pytz import numpy as np from datetime import timedelta @@ -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) @@ -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', diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 0586ea9c4db2b..62686b356dc30 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -6,6 +6,7 @@ import pytest import numpy as np +from pytz import timezone from datetime import datetime, timedelta, time import pandas as pd @@ -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)) @@ -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))), @@ -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) diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index 96c8da546ff9d..6cba7e17abf8e 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -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 @@ -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): diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index a9ea028c9d0f7..4ef5cc5499f4d 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -1,5 +1,6 @@ import pytest +import pytz import numpy as np import pandas as pd import pandas.util.testing as tm @@ -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): diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py index 80e93a1f76a66..f33cdf8800791 100644 --- a/pandas/tests/indexes/datetimes/test_ops.py +++ b/pandas/tests/indexes/datetimes/test_ops.py @@ -1,4 +1,6 @@ +import pytz import pytest +import dateutil import warnings import numpy as np from datetime import timedelta @@ -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): @@ -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): diff --git a/pandas/tests/indexes/datetimes/test_setops.py b/pandas/tests/indexes/datetimes/test_setops.py index f3af7dd30c27f..f43c010f59b9e 100644 --- a/pandas/tests/indexes/datetimes/test_setops.py +++ b/pandas/tests/indexes/datetimes/test_setops.py @@ -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') @@ -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') diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index 648df01be5289..61f7ac8abaf09 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -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 @@ -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)), @@ -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 @@ -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 @@ -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: @@ -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))} @@ -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) diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 3f08013e05ac8..4431108a55963 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -7,6 +7,8 @@ from __future__ import print_function import re +import pytz +import dateutil import itertools from operator import methodcaller import os @@ -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, @@ -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)) @@ -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) diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index 86b0e5a0c6a2d..662f06dbb725e 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -5,12 +5,14 @@ except ImportError: import simplejson as json import math +import pytz import pytest import time import datetime import calendar import re import decimal +import dateutil from functools import partial from pandas.compat import range, zip, StringIO, u import pandas._libs.json as ujson @@ -396,18 +398,14 @@ def test_encodeTimeConversion(self): assert expected == output def test_encodeTimeConversion_pytz(self): - # GH11473 to_json segfaults with timezone-aware datetimes - tm._skip_if_no_pytz() - import pytz + # see gh-11473: to_json segfaults with timezone-aware datetimes test = datetime.time(10, 12, 15, 343243, pytz.utc) output = ujson.encode(test) expected = '"%s"' % test.isoformat() assert expected == output def test_encodeTimeConversion_dateutil(self): - # GH11473 to_json segfaults with timezone-aware datetimes - tm._skip_if_no_dateutil() - import dateutil + # see gh-11473: to_json segfaults with timezone-aware datetimes test = datetime.time(10, 12, 15, 343243, dateutil.tz.tzutc()) output = ujson.encode(test) expected = '"%s"' % test.isoformat() diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index ee44fea55e51a..873bb20b3bba9 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -5243,7 +5243,6 @@ def _compare_with_tz(self, a, b): def test_append_with_timezones_dateutil(self): from datetime import timedelta - tm._skip_if_no_dateutil() # use maybe_get_tz instead of dateutil.tz.gettz to handle the windows # filename issues. diff --git a/pandas/tests/plotting/common.py b/pandas/tests/plotting/common.py index 1dbba676e4bc5..3ab443b223f20 100644 --- a/pandas/tests/plotting/common.py +++ b/pandas/tests/plotting/common.py @@ -23,7 +23,7 @@ This is a common base class used for various plotting tests """ -tm._skip_module_if_no_mpl() +tm._skip_if_no_mpl() def _skip_if_no_scipy_gaussian_kde(): diff --git a/pandas/tests/plotting/test_boxplot_method.py b/pandas/tests/plotting/test_boxplot_method.py index 1e06c13980657..a4c70f7945347 100644 --- a/pandas/tests/plotting/test_boxplot_method.py +++ b/pandas/tests/plotting/test_boxplot_method.py @@ -21,7 +21,7 @@ """ Test cases for .boxplot method """ -tm._skip_module_if_no_mpl() +tm._skip_if_no_mpl() def _skip_if_mpl_14_or_dev_boxplot(): diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index ed198de11bac1..3e7e789fa7de7 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -20,7 +20,7 @@ from pandas.tests.plotting.common import (TestPlotBase, _skip_if_no_scipy_gaussian_kde) -tm._skip_module_if_no_mpl() +tm._skip_if_no_mpl() class TestTSPlot(TestPlotBase): diff --git a/pandas/tests/plotting/test_deprecated.py b/pandas/tests/plotting/test_deprecated.py index 48030df48deca..ca03bcb060e25 100644 --- a/pandas/tests/plotting/test_deprecated.py +++ b/pandas/tests/plotting/test_deprecated.py @@ -18,7 +18,7 @@ pandas.tools.plotting """ -tm._skip_module_if_no_mpl() +tm._skip_if_no_mpl() class TestDeprecatedNameSpace(TestPlotBase): diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index 4a4a71d7ea639..9abbb348fbfa8 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -27,7 +27,7 @@ _skip_if_no_scipy_gaussian_kde, _ok_for_gaussian_kde) -tm._skip_module_if_no_mpl() +tm._skip_if_no_mpl() class TestDataFramePlots(TestPlotBase): diff --git a/pandas/tests/plotting/test_groupby.py b/pandas/tests/plotting/test_groupby.py index 8dcf73bce03c0..de48b58133e9a 100644 --- a/pandas/tests/plotting/test_groupby.py +++ b/pandas/tests/plotting/test_groupby.py @@ -10,7 +10,7 @@ from pandas.tests.plotting.common import TestPlotBase -tm._skip_module_if_no_mpl() +tm._skip_if_no_mpl() class TestDataFrameGroupByPlots(TestPlotBase): diff --git a/pandas/tests/plotting/test_hist_method.py b/pandas/tests/plotting/test_hist_method.py index c3e32f52e0474..17a75e5cb287c 100644 --- a/pandas/tests/plotting/test_hist_method.py +++ b/pandas/tests/plotting/test_hist_method.py @@ -15,7 +15,7 @@ from pandas.tests.plotting.common import (TestPlotBase, _check_plot_works) -tm._skip_module_if_no_mpl() +tm._skip_if_no_mpl() class TestSeriesPlots(TestPlotBase): diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py index 9eace32aa19a3..d93ad90a36a9c 100644 --- a/pandas/tests/plotting/test_misc.py +++ b/pandas/tests/plotting/test_misc.py @@ -17,7 +17,7 @@ from pandas.tests.plotting.common import (TestPlotBase, _check_plot_works, _ok_for_gaussian_kde) -tm._skip_module_if_no_mpl() +tm._skip_if_no_mpl() class TestSeriesPlots(TestPlotBase): diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index 448661c7af0e9..340a98484480f 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -22,7 +22,7 @@ _skip_if_no_scipy_gaussian_kde, _ok_for_gaussian_kde) -tm._skip_module_if_no_mpl() +tm._skip_if_no_mpl() class TestSeriesPlots(TestPlotBase): diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index 4dfa2904313ce..7486c32f57fdb 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -1,5 +1,6 @@ from warnings import catch_warnings +import dateutil import numpy as np from numpy.random import randn @@ -1780,9 +1781,6 @@ def test_concat_tz_series_with_datetimelike(self): def test_concat_tz_series_tzlocal(self): # see gh-13583 - tm._skip_if_no_dateutil() - import dateutil - x = [pd.Timestamp('2011-01-01', tz=dateutil.tz.tzlocal()), pd.Timestamp('2011-02-01', tz=dateutil.tz.tzlocal())] y = [pd.Timestamp('2012-01-01', tz=dateutil.tz.tzlocal()), diff --git a/pandas/tests/scalar/test_period.py b/pandas/tests/scalar/test_period.py index 54366dc9b1c3f..931d6b2b8f1f0 100644 --- a/pandas/tests/scalar/test_period.py +++ b/pandas/tests/scalar/test_period.py @@ -1,5 +1,6 @@ import pytest +import pytz import numpy as np from datetime import datetime, date, timedelta @@ -210,8 +211,6 @@ def test_period_cons_combined(self): Period('2011-01', freq='1D1W') def test_timestamp_tz_arg(self): - tm._skip_if_no_pytz() - import pytz for case in ['Europe/Brussels', 'Asia/Tokyo', 'US/Pacific']: p = Period('1/1/2005', freq='M').to_timestamp(tz=case) exp = Timestamp('1/1/2005', tz='UTC').tz_convert(case) diff --git a/pandas/tests/scalar/test_timestamp.py b/pandas/tests/scalar/test_timestamp.py index 5caa0252b69b8..7cd1a7db0f9fe 100644 --- a/pandas/tests/scalar/test_timestamp.py +++ b/pandas/tests/scalar/test_timestamp.py @@ -1,12 +1,18 @@ """ test the scalar Timestamp """ import sys +import pytz import pytest +import dateutil import operator import calendar import numpy as np + +from dateutil.tz import tzutc +from pytz import timezone, utc from datetime import datetime, timedelta from distutils.version import LooseVersion +from pytz.exceptions import AmbiguousTimeError, NonExistentTimeError import pandas.util.testing as tm from pandas.tseries import offsets, frequencies @@ -44,10 +50,6 @@ def test_constructor(self): Timestamp('2014-07-01 09:00:00.000000005'), base_expected + 5)] - tm._skip_if_no_pytz() - tm._skip_if_no_dateutil() - import pytz - import dateutil timezones = [(None, 0), ('UTC', 0), (pytz.utc, 0), ('Asia/Tokyo', 9), ('US/Eastern', -4), ('dateutil/US/Pacific', -7), (pytz.FixedOffset(-180), -3), @@ -100,10 +102,6 @@ def test_constructor_with_stringoffset(self): ('2014-07-01 11:00:00.000008000+02:00', base_expected + 8000), ('2014-07-01 11:00:00.000000005+02:00', base_expected + 5)] - tm._skip_if_no_pytz() - tm._skip_if_no_dateutil() - import pytz - import dateutil timezones = [(None, 0), ('UTC', 0), (pytz.utc, 0), ('Asia/Tokyo', 9), ('US/Eastern', -4), ('dateutil/US/Pacific', -7), (pytz.FixedOffset(-180), -3), @@ -274,14 +272,10 @@ def test_conversion(self): assert result.dtype == expected.dtype def test_repr(self): - tm._skip_if_no_pytz() - tm._skip_if_no_dateutil() - dates = ['2014-03-07', '2014-01-01 09:00', '2014-01-01 00:00:00.000000001'] # dateutil zone change (only matters for repr) - import dateutil if (dateutil.__version__ >= LooseVersion('2.3') and (dateutil.__version__ <= LooseVersion('2.4.0') or dateutil.__version__ >= LooseVersion('2.6.0'))): @@ -330,8 +324,6 @@ def test_repr(self): # This can cause the tz field to be populated, but it's redundant to # include this information in the date-string. - tm._skip_if_no_pytz() - import pytz # noqa date_with_utc_offset = Timestamp('2014-03-13 00:00:00-0400', tz=None) assert '2014-03-13 00:00:00-0400' in repr(date_with_utc_offset) assert 'tzoffset' not in repr(date_with_utc_offset) @@ -399,8 +391,7 @@ def test_tz_localize_ambiguous(self): Timestamp('2011-01-01').tz_convert('Asia/Tokyo') def test_tz_localize_nonexistent(self): - # See issue 13057 - from pytz.exceptions import NonExistentTimeError + # see gh-13057 times = ['2015-03-08 02:00', '2015-03-08 02:30', '2015-03-29 02:00', '2015-03-29 02:30'] timezones = ['US/Eastern', 'US/Pacific', @@ -414,8 +405,7 @@ def test_tz_localize_nonexistent(self): assert ts.tz_localize(tz, errors='coerce') is NaT def test_tz_localize_errors_ambiguous(self): - # See issue 13057 - from pytz.exceptions import AmbiguousTimeError + # see gh-13057 ts = Timestamp('2015-11-1 01:00') pytest.raises(AmbiguousTimeError, ts.tz_localize, 'US/Pacific', errors='coerce') @@ -709,9 +699,6 @@ def _check_round(freq, expected): stamp.round('foo') def test_class_ops_pytz(self): - tm._skip_if_no_pytz() - from pytz import timezone - def compare(x, y): assert (int(Timestamp(x).value / 1e9) == int(Timestamp(y).value / 1e9)) @@ -732,9 +719,6 @@ def compare(x, y): datetime.combine(date_component, time_component)) def test_class_ops_dateutil(self): - tm._skip_if_no_dateutil() - from dateutil.tz import tzutc - def compare(x, y): assert (int(np.round(Timestamp(x).value / 1e9)) == int(np.round(Timestamp(y).value / 1e9))) @@ -910,8 +894,7 @@ def test_compare_invalid(self): tm.assert_series_equal(a / b, 1 / (b / a)) def test_cant_compare_tz_naive_w_aware(self): - tm._skip_if_no_pytz() - # #1404 + # see gh-1404 a = Timestamp('3/12/2012') b = Timestamp('3/12/2012', tz='utc') @@ -932,9 +915,7 @@ def test_cant_compare_tz_naive_w_aware(self): assert not a.to_pydatetime() == b def test_cant_compare_tz_naive_w_aware_explicit_pytz(self): - tm._skip_if_no_pytz() - from pytz import utc - # #1404 + # see gh-1404 a = Timestamp('3/12/2012') b = Timestamp('3/12/2012', tz=utc) @@ -955,12 +936,9 @@ def test_cant_compare_tz_naive_w_aware_explicit_pytz(self): assert not a.to_pydatetime() == b def test_cant_compare_tz_naive_w_aware_dateutil(self): - tm._skip_if_no_dateutil() - from dateutil.tz import tzutc - utc = tzutc() - # #1404 + # see gh-1404 a = Timestamp('3/12/2012') - b = Timestamp('3/12/2012', tz=utc) + b = Timestamp('3/12/2012', tz=tzutc()) pytest.raises(Exception, a.__eq__, b) pytest.raises(Exception, a.__ne__, b) @@ -1282,7 +1260,6 @@ def test_compare_hour13(self): class TestTimeSeries(object): def test_timestamp_to_datetime(self): - tm._skip_if_no_pytz() rng = date_range('20090415', '20090519', tz='US/Eastern') stamp = rng[0] @@ -1291,7 +1268,6 @@ def test_timestamp_to_datetime(self): assert stamp.tzinfo == dtval.tzinfo def test_timestamp_to_datetime_dateutil(self): - tm._skip_if_no_pytz() rng = date_range('20090415', '20090519', tz='dateutil/US/Eastern') stamp = rng[0] @@ -1300,8 +1276,6 @@ def test_timestamp_to_datetime_dateutil(self): assert stamp.tzinfo == dtval.tzinfo def test_timestamp_to_datetime_explicit_pytz(self): - tm._skip_if_no_pytz() - import pytz rng = date_range('20090415', '20090519', tz=pytz.timezone('US/Eastern')) @@ -1312,7 +1286,7 @@ def test_timestamp_to_datetime_explicit_pytz(self): def test_timestamp_to_datetime_explicit_dateutil(self): tm._skip_if_windows_python_3() - tm._skip_if_no_dateutil() + from pandas._libs.tslib import _dateutil_gettz as gettz rng = date_range('20090415', '20090519', tz=gettz('US/Eastern')) diff --git a/pandas/tests/series/test_combine_concat.py b/pandas/tests/series/test_combine_concat.py index bb998b7fa55dd..71ac00975af03 100644 --- a/pandas/tests/series/test_combine_concat.py +++ b/pandas/tests/series/test_combine_concat.py @@ -246,9 +246,7 @@ def test_append_concat(self): assert rng1.append(rng2).name is None def test_append_concat_tz(self): - # GH 2938 - tm._skip_if_no_pytz() - + # see gh-2938 rng = date_range('5/8/2012 1:45', periods=10, freq='5T', tz='US/Eastern') rng2 = date_range('5/8/2012 2:35', periods=10, freq='5T', @@ -269,8 +267,7 @@ def test_append_concat_tz(self): tm.assert_index_equal(appended, rng3) def test_append_concat_tz_explicit_pytz(self): - # GH 2938 - tm._skip_if_no_pytz() + # see gh-2938 from pytz import timezone as timezone rng = date_range('5/8/2012 1:45', periods=10, freq='5T', @@ -293,8 +290,7 @@ def test_append_concat_tz_explicit_pytz(self): tm.assert_index_equal(appended, rng3) def test_append_concat_tz_dateutil(self): - # GH 2938 - tm._skip_if_no_dateutil() + # see gh-2938 rng = date_range('5/8/2012 1:45', periods=10, freq='5T', tz='dateutil/US/Eastern') rng2 = date_range('5/8/2012 2:35', periods=10, freq='5T', diff --git a/pandas/tests/series/test_indexing.py b/pandas/tests/series/test_indexing.py index 7f876357ad3ab..6ded4d593a571 100644 --- a/pandas/tests/series/test_indexing.py +++ b/pandas/tests/series/test_indexing.py @@ -338,9 +338,7 @@ def test_getitem_setitem_slice_integers(self): assert not (s[4:] == 0).any() def test_getitem_setitem_datetime_tz_pytz(self): - tm._skip_if_no_pytz() from pytz import timezone as tz - from pandas import date_range N = 50 @@ -374,7 +372,6 @@ def test_getitem_setitem_datetime_tz_pytz(self): assert_series_equal(result, ts) def test_getitem_setitem_datetime_tz_dateutil(self): - tm._skip_if_no_dateutil() from dateutil.tz import tzutc from pandas._libs.tslib import _dateutil_gettz as gettz diff --git a/pandas/tests/series/test_operators.py b/pandas/tests/series/test_operators.py index db0d06aa35a2a..2e400812e0331 100644 --- a/pandas/tests/series/test_operators.py +++ b/pandas/tests/series/test_operators.py @@ -2,6 +2,7 @@ # pylint: disable-msg=E1101,W0612 import pytest +import pytz from collections import Iterable from datetime import datetime, timedelta @@ -725,9 +726,7 @@ def run_ops(ops, get_ser, test_ser): pytest.raises(TypeError, lambda: td2 - dt2) def test_sub_datetime_compat(self): - # GH 14088 - tm._skip_if_no_pytz() - import pytz + # see gh-14088 s = Series([datetime(2016, 8, 23, 12, tzinfo=pytz.utc), pd.NaT]) dt = datetime(2016, 8, 22, 12, tzinfo=pytz.utc) exp = Series([Timedelta('1 days'), pd.NaT]) diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index ab28b8b43f359..9d80190ae2813 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -4,6 +4,7 @@ import datetime import itertools import pytest +import pytz from numpy.random import randn import numpy as np @@ -68,8 +69,6 @@ def test_append(self): tm.assert_series_equal(result, self.frame['A']) def test_append_index(self): - tm._skip_if_no_pytz() - idx1 = Index([1.1, 1.2, 1.3]) idx2 = pd.date_range('2011-01-01', freq='D', periods=3, tz='Asia/Tokyo') @@ -80,8 +79,7 @@ def test_append_index(self): result = idx1.append(midx_lv2) - # GH 7112 - import pytz + # see gh-7112 tz = pytz.timezone('Asia/Tokyo') expected_tuples = [(1.1, tz.localize(datetime.datetime(2011, 1, 1))), (1.2, tz.localize(datetime.datetime(2011, 1, 2))), diff --git a/pandas/tests/test_resample.py b/pandas/tests/test_resample.py index 9734431c8b012..37e2fd0e9b188 100644 --- a/pandas/tests/test_resample.py +++ b/pandas/tests/test_resample.py @@ -4,7 +4,9 @@ from datetime import datetime, timedelta from functools import partial +import pytz import pytest +import dateutil import numpy as np import pandas as pd @@ -2424,10 +2426,7 @@ def test_resample_incompat_freq(self): start='2000', periods=3, freq='M')).resample('W').mean() def test_with_local_timezone_pytz(self): - # GH5430 - tm._skip_if_no_pytz() - import pytz - + # see gh-5430 local_timezone = pytz.timezone('America/Los_Angeles') start = datetime(year=2013, month=11, day=1, hour=0, minute=0, @@ -2450,10 +2449,7 @@ def test_with_local_timezone_pytz(self): assert_series_equal(result, expected) def test_with_local_timezone_dateutil(self): - # GH5430 - tm._skip_if_no_dateutil() - import dateutil - + # see gh-5430 local_timezone = 'dateutil/America/Los_Angeles' start = datetime(year=2013, month=11, day=1, hour=0, minute=0, diff --git a/pandas/tests/tseries/test_offsets.py b/pandas/tests/tseries/test_offsets.py index 09de064c15183..47b15a2b66fc4 100644 --- a/pandas/tests/tseries/test_offsets.py +++ b/pandas/tests/tseries/test_offsets.py @@ -148,8 +148,6 @@ def test_apply_out_of_range(self): assert isinstance(result, datetime) assert result.tzinfo is None - tm._skip_if_no_pytz() - tm._skip_if_no_dateutil() # Check tz is preserved for tz in self.timezones: t = Timestamp('20080101', tz=tz) @@ -157,7 +155,7 @@ def test_apply_out_of_range(self): assert isinstance(result, datetime) assert t.tzinfo == result.tzinfo - except (tslib.OutOfBoundsDatetime): + except tslib.OutOfBoundsDatetime: raise except (ValueError, KeyError) as e: pytest.skip( @@ -285,9 +283,6 @@ def _check_offsetfunc_works(self, offset, funcname, dt, expected, # test tz when input is datetime or Timestamp return - tm._skip_if_no_pytz() - tm._skip_if_no_dateutil() - for tz in self.timezones: expected_localize = expected.tz_localize(tz) tz_obj = tslib.maybe_get_tz(tz) @@ -468,7 +463,6 @@ def test_add(self): assert isinstance(result, Timestamp) assert result == expected - tm._skip_if_no_pytz() for tz in self.timezones: expected_localize = expected.tz_localize(tz) result = Timestamp(dt, tz=tz) + offset_s diff --git a/pandas/tests/tseries/test_timezones.py b/pandas/tests/tseries/test_timezones.py index 97c54922d36e9..de6978d52968b 100644 --- a/pandas/tests/tseries/test_timezones.py +++ b/pandas/tests/tseries/test_timezones.py @@ -1,10 +1,15 @@ # pylint: disable-msg=E1101,W0612 import pytest + import pytz +import dateutil import numpy as np + +from dateutil.parser import parse +from pytz import NonExistentTimeError from distutils.version import LooseVersion +from dateutil.tz import tzlocal, tzoffset from datetime import datetime, timedelta, tzinfo, date -from pytz import NonExistentTimeError import pandas.util.testing as tm import pandas.core.tools.datetimes as tools @@ -18,16 +23,6 @@ from pandas.util.testing import (assert_frame_equal, assert_series_equal, set_timezone) -try: - import pytz # noqa -except ImportError: - pass - -try: - import dateutil -except ImportError: - pass - class FixedOffset(tzinfo): """Fixed offset in minutes east from UTC.""" @@ -52,9 +47,6 @@ def dst(self, dt): class TestTimeZoneSupportPytz(object): - def setup_method(self, method): - tm._skip_if_no_pytz() - def tz(self, tz): # Construct a timezone object from a string. Overridden in subclass to # parameterize tests. @@ -207,8 +199,6 @@ def test_timestamp_constructor_near_dst_boundary(self): assert result == expected def test_timestamp_to_datetime_tzoffset(self): - # tzoffset - from dateutil.tz import tzoffset tzinfo = tzoffset(None, 7200) expected = Timestamp('3/11/2012 04:00', tz=tzinfo) result = Timestamp(expected.to_pydatetime()) @@ -294,7 +284,7 @@ def test_create_with_tz(self): assert utc_stamp.tzinfo is pytz.utc assert utc_stamp.hour == 5 - stamp = Timestamp('3/11/2012 05:00').tz_localize('utc') + utc_stamp = Timestamp('3/11/2012 05:00').tz_localize('utc') assert utc_stamp.hour == 5 def test_create_with_fixed_tz(self): @@ -670,7 +660,6 @@ def test_tz_string(self): tm.assert_index_equal(result, expected) def test_take_dont_lose_meta(self): - tm._skip_if_no_pytz() rng = date_range('1/1/2000', periods=20, tz=self.tzstr('US/Eastern')) result = rng.take(lrange(5)) @@ -765,15 +754,12 @@ def test_convert_tz_aware_datetime_datetime(self): assert converted.tz is pytz.utc def test_to_datetime_utc(self): - from dateutil.parser import parse arr = np.array([parse('2012-06-13T01:39:00Z')], dtype=object) result = to_datetime(arr, utc=True) assert result.tz is pytz.utc def test_to_datetime_tzlocal(self): - from dateutil.parser import parse - from dateutil.tz import tzlocal dt = parse('2012-06-13T01:39:00Z') dt = dt.replace(tzinfo=tzlocal()) @@ -889,7 +875,6 @@ def test_frame_reset_index(self): assert xp == rs def test_dateutil_tzoffset_support(self): - from dateutil.tz import tzoffset values = [188.5, 328.25] tzinfo = tzoffset(None, 7200) index = [datetime(2012, 5, 11, 11, tzinfo=tzinfo), @@ -944,9 +929,6 @@ def test_datetimeindex_tz_nat(self): class TestTimeZoneSupportDateutil(TestTimeZoneSupportPytz): - def setup_method(self, method): - tm._skip_if_no_dateutil() - def tz(self, tz): """ Construct a dateutil timezone. @@ -1197,9 +1179,6 @@ def test_cache_keys_are_distinct_for_pytz_vs_dateutil(self): class TestTimeZones(object): timezones = ['UTC', 'Asia/Tokyo', 'US/Eastern', 'dateutil/US/Pacific'] - def setup_method(self, method): - tm._skip_if_no_pytz() - def test_replace(self): # GH 14621 # GH 7825 @@ -1244,8 +1223,6 @@ def f(): def test_ambiguous_compat(self): # validate that pytz and dateutil are compat for dst # when the transition happens - tm._skip_if_no_dateutil() - tm._skip_if_no_pytz() pytz_zone = 'Europe/London' dateutil_zone = 'dateutil/Europe/London' @@ -1637,7 +1614,6 @@ def test_normalize_tz(self): assert result.is_normalized assert not rng.is_normalized - from dateutil.tz import tzlocal rng = date_range('1/1/2000 9:30', periods=10, freq='D', tz=tzlocal()) result = rng.normalize() expected = date_range('1/1/2000', periods=10, freq='D', tz=tzlocal()) @@ -1647,9 +1623,7 @@ def test_normalize_tz(self): assert not rng.is_normalized def test_normalize_tz_local(self): - # GH 13459 - from dateutil.tz import tzlocal - + # see gh-13459 timezones = ['US/Pacific', 'US/Eastern', 'UTC', 'Asia/Kolkata', 'Asia/Shanghai', 'Australia/Canberra'] diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 4b610c505c574..5f01f42eb0c69 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -270,27 +270,18 @@ def close(fignum=None): def _skip_if_32bit(): - import pytest if is_platform_32bit(): + import pytest pytest.skip("skipping for 32 bit") -def _skip_module_if_no_mpl(): +def _skip_if_no_mpl(): import pytest mpl = pytest.importorskip("matplotlib") mpl.use("Agg", warn=False) -def _skip_if_no_mpl(): - try: - import matplotlib as mpl - mpl.use("Agg", warn=False) - except ImportError: - import pytest - pytest.skip("matplotlib not installed") - - def _skip_if_mpl_1_5(): import matplotlib as mpl @@ -303,21 +294,11 @@ def _skip_if_mpl_1_5(): def _skip_if_no_scipy(): - try: - import scipy.stats # noqa - except ImportError: - import pytest - pytest.skip("no scipy.stats module") - try: - import scipy.interpolate # noqa - except ImportError: - import pytest - pytest.skip('scipy.interpolate missing') - try: - import scipy.sparse # noqa - except ImportError: - import pytest - pytest.skip('scipy.sparse missing') + import pytest + + pytest.importorskip("scipy.stats") + pytest.importorskip("scipy.sparse") + pytest.importorskip("scipy.interpolate") def _check_if_lzma(): @@ -333,34 +314,16 @@ def _skip_if_no_lzma(): def _skip_if_no_xarray(): - try: - import xarray - except ImportError: - import pytest - pytest.skip("xarray not installed") + import pytest + xarray = pytest.importorskip("xarray") v = xarray.__version__ + if v < LooseVersion('0.7.0'): import pytest pytest.skip("xarray not version is too low: {0}".format(v)) -def _skip_if_no_pytz(): - try: - import pytz # noqa - except ImportError: - import pytest - pytest.skip("pytz not installed") - - -def _skip_if_no_dateutil(): - try: - import dateutil # noqa - except ImportError: - import pytest - pytest.skip("dateutil not installed") - - def _skip_if_windows_python_3(): if PY3 and is_platform_windows(): import pytest @@ -441,16 +404,13 @@ def _skip_if_no_mock(): try: from unittest import mock # noqa except ImportError: - import nose - raise nose.SkipTest("mock is not installed") + import pytest + raise pytest.skip("mock is not installed") def _skip_if_no_ipython(): - try: - import IPython # noqa - except ImportError: - import nose - raise nose.SkipTest("IPython not installed") + import pytest + pytest.importorskip("IPython") # ----------------------------------------------------------------------------- # locale utilities