From ccf75ae43dd08412f197270a14cef9ddbef76850 Mon Sep 17 00:00:00 2001 From: gfyoung Date: Thu, 20 Apr 2017 19:48:49 -0400 Subject: [PATCH] MAINT: Remove assertIsInstance from testing --- pandas/tests/dtypes/test_generic.py | 37 +++++---- pandas/tests/dtypes/test_missing.py | 2 +- pandas/tests/frame/test_alter_axes.py | 6 +- pandas/tests/frame/test_analytics.py | 12 +-- pandas/tests/frame/test_api.py | 6 +- pandas/tests/frame/test_apply.py | 10 +-- pandas/tests/frame/test_constructors.py | 8 +- pandas/tests/frame/test_convert_to.py | 2 +- pandas/tests/frame/test_indexing.py | 4 +- pandas/tests/frame/test_period.py | 2 +- pandas/tests/frame/test_subclass.py | 30 +++---- pandas/tests/frame/test_timeseries.py | 4 +- pandas/tests/frame/test_to_csv.py | 2 +- pandas/tests/groupby/test_aggregate.py | 4 +- pandas/tests/groupby/test_groupby.py | 24 +++--- pandas/tests/groupby/test_timegrouper.py | 2 +- pandas/tests/indexes/common.py | 2 +- pandas/tests/indexes/datetimes/test_astype.py | 12 +-- .../indexes/datetimes/test_date_range.py | 4 +- .../tests/indexes/datetimes/test_datetime.py | 16 ++-- pandas/tests/indexes/datetimes/test_misc.py | 10 +-- pandas/tests/indexes/datetimes/test_ops.py | 14 ++-- .../indexes/datetimes/test_partial_slcing.py | 4 +- pandas/tests/indexes/datetimes/test_setops.py | 38 ++++----- pandas/tests/indexes/datetimes/test_tools.py | 10 +-- .../tests/indexes/period/test_construction.py | 4 +- pandas/tests/indexes/period/test_indexing.py | 2 +- pandas/tests/indexes/period/test_period.py | 12 +-- pandas/tests/indexes/period/test_setops.py | 2 +- pandas/tests/indexes/period/test_tools.py | 3 +- pandas/tests/indexes/test_base.py | 26 +++--- pandas/tests/indexes/test_interval.py | 4 +- pandas/tests/indexes/test_multi.py | 8 +- pandas/tests/indexes/test_numeric.py | 60 +++++++------- pandas/tests/indexes/test_range.py | 26 +++--- pandas/tests/indexes/timedeltas/test_ops.py | 2 +- .../indexes/timedeltas/test_timedelta.py | 18 ++--- .../indexing/test_chaining_and_caching.py | 2 +- pandas/tests/io/formats/test_format.py | 4 +- pandas/tests/io/formats/test_to_html.py | 2 +- pandas/tests/io/parser/common.py | 14 ++-- pandas/tests/io/parser/converters.py | 2 +- pandas/tests/io/parser/parse_dates.py | 10 +-- pandas/tests/io/test_excel.py | 6 +- pandas/tests/io/test_html.py | 32 ++++---- pandas/tests/io/test_packers.py | 2 +- pandas/tests/io/test_pickle.py | 2 +- pandas/tests/io/test_pytables.py | 8 +- pandas/tests/io/test_stata.py | 4 +- pandas/tests/plotting/common.py | 10 +-- pandas/tests/plotting/test_boxplot_method.py | 2 +- pandas/tests/plotting/test_datetimelike.py | 8 +- pandas/tests/plotting/test_frame.py | 2 +- pandas/tests/reshape/test_concat.py | 16 ++-- pandas/tests/reshape/test_merge.py | 2 +- pandas/tests/reshape/test_merge_ordered.py | 2 +- pandas/tests/reshape/test_pivot.py | 2 +- pandas/tests/scalar/test_period.py | 20 ++--- pandas/tests/scalar/test_timedelta.py | 19 ++--- pandas/tests/scalar/test_timestamp.py | 8 +- pandas/tests/series/test_alter_axes.py | 6 +- pandas/tests/series/test_analytics.py | 6 +- pandas/tests/series/test_api.py | 8 +- pandas/tests/series/test_apply.py | 4 +- pandas/tests/series/test_constructors.py | 4 +- pandas/tests/series/test_datetime_values.py | 12 +-- pandas/tests/series/test_indexing.py | 6 +- pandas/tests/series/test_io.py | 10 +-- pandas/tests/series/test_operators.py | 6 +- pandas/tests/series/test_subclass.py | 8 +- pandas/tests/series/test_timeseries.py | 6 +- pandas/tests/sparse/test_arithmetics.py | 4 +- pandas/tests/sparse/test_array.py | 8 +- pandas/tests/sparse/test_combine_concat.py | 22 ++--- pandas/tests/sparse/test_frame.py | 44 +++++----- pandas/tests/sparse/test_libsparse.py | 30 +++---- pandas/tests/sparse/test_series.py | 18 ++--- pandas/tests/test_algos.py | 6 +- pandas/tests/test_base.py | 4 +- pandas/tests/test_categorical.py | 20 ++--- pandas/tests/test_join.py | 6 +- pandas/tests/test_multilevel.py | 16 ++-- pandas/tests/test_resample.py | 20 ++--- pandas/tests/test_strings.py | 64 +++++++-------- pandas/tests/test_testing.py | 9 --- pandas/tests/test_window.py | 6 +- pandas/tests/tseries/test_offsets.py | 8 +- pandas/tests/tseries/test_timezones.py | 6 +- pandas/util/testing.py | 81 ++++++++++--------- 89 files changed, 527 insertions(+), 532 deletions(-) diff --git a/pandas/tests/dtypes/test_generic.py b/pandas/tests/dtypes/test_generic.py index d550b5535cea3..e9af53aaa1e1a 100644 --- a/pandas/tests/dtypes/test_generic.py +++ b/pandas/tests/dtypes/test_generic.py @@ -20,23 +20,22 @@ class TestABCClasses(tm.TestCase): sparse_array = pd.SparseArray(np.random.randn(10)) def test_abc_types(self): - self.assertIsInstance(pd.Index(['a', 'b', 'c']), gt.ABCIndex) - self.assertIsInstance(pd.Int64Index([1, 2, 3]), gt.ABCInt64Index) - self.assertIsInstance(pd.UInt64Index([1, 2, 3]), gt.ABCUInt64Index) - self.assertIsInstance(pd.Float64Index([1, 2, 3]), gt.ABCFloat64Index) - self.assertIsInstance(self.multi_index, gt.ABCMultiIndex) - self.assertIsInstance(self.datetime_index, gt.ABCDatetimeIndex) - self.assertIsInstance(self.timedelta_index, gt.ABCTimedeltaIndex) - self.assertIsInstance(self.period_index, gt.ABCPeriodIndex) - self.assertIsInstance(self.categorical_df.index, - gt.ABCCategoricalIndex) - self.assertIsInstance(pd.Index(['a', 'b', 'c']), gt.ABCIndexClass) - self.assertIsInstance(pd.Int64Index([1, 2, 3]), gt.ABCIndexClass) - self.assertIsInstance(pd.Series([1, 2, 3]), gt.ABCSeries) - self.assertIsInstance(self.df, gt.ABCDataFrame) + assert isinstance(pd.Index(['a', 'b', 'c']), gt.ABCIndex) + assert isinstance(pd.Int64Index([1, 2, 3]), gt.ABCInt64Index) + assert isinstance(pd.UInt64Index([1, 2, 3]), gt.ABCUInt64Index) + assert isinstance(pd.Float64Index([1, 2, 3]), gt.ABCFloat64Index) + assert isinstance(self.multi_index, gt.ABCMultiIndex) + assert isinstance(self.datetime_index, gt.ABCDatetimeIndex) + assert isinstance(self.timedelta_index, gt.ABCTimedeltaIndex) + assert isinstance(self.period_index, gt.ABCPeriodIndex) + assert isinstance(self.categorical_df.index, gt.ABCCategoricalIndex) + assert isinstance(pd.Index(['a', 'b', 'c']), gt.ABCIndexClass) + assert isinstance(pd.Int64Index([1, 2, 3]), gt.ABCIndexClass) + assert isinstance(pd.Series([1, 2, 3]), gt.ABCSeries) + assert isinstance(self.df, gt.ABCDataFrame) with catch_warnings(record=True): - self.assertIsInstance(self.df.to_panel(), gt.ABCPanel) - self.assertIsInstance(self.sparse_series, gt.ABCSparseSeries) - self.assertIsInstance(self.sparse_array, gt.ABCSparseArray) - self.assertIsInstance(self.categorical, gt.ABCCategorical) - self.assertIsInstance(pd.Period('2012', freq='A-DEC'), gt.ABCPeriod) + assert isinstance(self.df.to_panel(), gt.ABCPanel) + assert isinstance(self.sparse_series, gt.ABCSparseSeries) + assert isinstance(self.sparse_array, gt.ABCSparseArray) + assert isinstance(self.categorical, gt.ABCCategorical) + assert isinstance(pd.Period('2012', freq='A-DEC'), gt.ABCPeriod) diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py index 0ee2cef127a8b..c03ba2b7daf50 100644 --- a/pandas/tests/dtypes/test_missing.py +++ b/pandas/tests/dtypes/test_missing.py @@ -76,7 +76,7 @@ def test_isnull(self): for s in [tm.makeFloatSeries(), tm.makeStringSeries(), tm.makeObjectSeries(), tm.makeTimeSeries(), tm.makePeriodSeries()]: - self.assertIsInstance(isnull(s), Series) + assert isinstance(isnull(s), Series) # frame for df in [tm.makeTimeDataFrame(), tm.makePeriodFrame(), diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index 904dd2e3cd4ed..5f1eb8ff46259 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -198,7 +198,7 @@ def test_set_index_cast_datetimeindex(self): 'B': np.random.randn(1000)}) idf = df.set_index('A') - tm.assertIsInstance(idf.index, pd.DatetimeIndex) + assert isinstance(idf.index, pd.DatetimeIndex) # don't cast a DatetimeIndex WITH a tz, leave as object # GH 6032 @@ -740,7 +740,7 @@ def test_reset_index_range(self): df = pd.DataFrame([[0, 0], [1, 1]], columns=['A', 'B'], index=RangeIndex(stop=2)) result = df.reset_index() - tm.assertIsInstance(result.index, RangeIndex) + assert isinstance(result.index, RangeIndex) expected = pd.DataFrame([[0, 0, 0], [1, 1, 1]], columns=['index', 'A', 'B'], index=RangeIndex(stop=2)) @@ -809,7 +809,7 @@ def test_setitem(self): df = DataFrame({'A': range(10)}) s = pd.cut(df.A, 5) - self.assertIsInstance(s.cat.categories, IntervalIndex) + assert isinstance(s.cat.categories, IntervalIndex) # B & D end up as Categoricals # the remainer are converted to in-line objects diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index f4bc4eaeb1fdc..75a12ebaebf9d 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -399,10 +399,10 @@ def test_count(self): # corner case frame = DataFrame() ct1 = frame.count(1) - tm.assertIsInstance(ct1, Series) + assert isinstance(ct1, Series) ct2 = frame.count(0) - tm.assertIsInstance(ct2, Series) + assert isinstance(ct2, Series) # GH #423 df = DataFrame(index=lrange(10)) @@ -711,11 +711,11 @@ def _check_stat_op(self, name, alternative, frame=None, has_skipna=True, df = DataFrame({'b': date_range('1/1/2001', periods=2)}) _f = getattr(df, name) result = _f() - self.assertIsInstance(result, Series) + assert isinstance(result, Series) df['a'] = lrange(len(df)) result = getattr(df, name)() - self.assertIsInstance(result, Series) + assert isinstance(result, Series) self.assertTrue(len(result)) if has_skipna: @@ -913,8 +913,8 @@ def test_operators_timedelta64(self): def test_sum_corner(self): axis0 = self.empty.sum(0) axis1 = self.empty.sum(1) - tm.assertIsInstance(axis0, Series) - tm.assertIsInstance(axis1, Series) + assert isinstance(axis0, Series) + assert isinstance(axis1, Series) self.assertEqual(len(axis0), 0) self.assertEqual(len(axis1), 0) diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index a534d8eefba3c..c8d36e01d5205 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -118,7 +118,7 @@ def test_new_empty_index(self): def test_array_interface(self): with np.errstate(all='ignore'): result = np.sqrt(self.frame) - tm.assertIsInstance(result, type(self.frame)) + assert isinstance(result, type(self.frame)) self.assertIs(result.index, self.frame.index) self.assertIs(result.columns, self.frame.columns) @@ -174,7 +174,7 @@ def test_itertuples(self): 'ints': lrange(5)}, columns=['floats', 'ints']) for tup in df.itertuples(index=False): - tm.assertIsInstance(tup[1], np.integer) + assert isinstance(tup[1], np.integer) df = DataFrame(data={"a": [1, 2, 3], "b": [4, 5, 6]}) dfaa = df[['a', 'a']] @@ -204,7 +204,7 @@ def test_itertuples(self): # will raise SyntaxError if trying to create namedtuple tup3 = next(df3.itertuples()) self.assertFalse(hasattr(tup3, '_fields')) - self.assertIsInstance(tup3, tuple) + assert isinstance(tup3, tuple) def test_len(self): self.assertEqual(len(self.frame), len(self.frame.index)) diff --git a/pandas/tests/frame/test_apply.py b/pandas/tests/frame/test_apply.py index 1afb048ad825a..89bb0e1fdf5b2 100644 --- a/pandas/tests/frame/test_apply.py +++ b/pandas/tests/frame/test_apply.py @@ -187,10 +187,10 @@ def _checkit(axis=0, raw=False): res = df.apply(f, axis=axis, raw=raw) if is_reduction: agg_axis = df._get_agg_axis(axis) - tm.assertIsInstance(res, Series) + assert isinstance(res, Series) self.assertIs(res.index, agg_axis) else: - tm.assertIsInstance(res, DataFrame) + assert isinstance(res, DataFrame) _checkit() _checkit(axis=1) @@ -204,7 +204,7 @@ def _checkit(axis=0, raw=False): _check(no_index, lambda x: x.mean()) result = no_cols.apply(lambda x: x.mean(), broadcast=True) - tm.assertIsInstance(result, DataFrame) + assert isinstance(result, DataFrame) def test_apply_with_args_kwds(self): def add_some(x, howmuch=0): @@ -357,7 +357,7 @@ def test_apply_multi_index(self): s.index = MultiIndex.from_arrays([['a', 'a', 'b'], ['c', 'd', 'd']]) s.columns = ['col1', 'col2'] res = s.apply(lambda x: Series({'min': min(x), 'max': max(x)}), 1) - tm.assertIsInstance(res.index, MultiIndex) + assert isinstance(res.index, MultiIndex) def test_apply_dict(self): @@ -385,7 +385,7 @@ def test_applymap(self): # GH #465, function returning tuples result = self.frame.applymap(lambda x: (x, x)) - tm.assertIsInstance(result['A'][0], tuple) + assert isinstance(result['A'][0], tuple) # GH 2909, object conversion to float in constructor? df = DataFrame(data=[1, 'a']) diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index c01be17172b82..29d742b2b79e2 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -101,7 +101,7 @@ def test_constructor_list_frames(self): self.assertEqual(result.shape, (1, 0)) result = DataFrame([DataFrame(dict(A=lrange(5)))]) - tm.assertIsInstance(result.iloc[0, 0], DataFrame) + assert isinstance(result.iloc[0, 0], DataFrame) def test_constructor_mixed_dtypes(self): @@ -397,10 +397,10 @@ def test_constructor_dict_cast(self): def test_constructor_dict_dont_upcast(self): d = {'Col1': {'Row1': 'A String', 'Row2': np.nan}} df = DataFrame(d) - tm.assertIsInstance(df['Col1']['Row2'], float) + assert isinstance(df['Col1']['Row2'], float) dm = DataFrame([[1, 2], ['a', 'b']], index=[1, 2], columns=[1, 2]) - tm.assertIsInstance(dm[1][1], int) + assert isinstance(dm[1][1], int) def test_constructor_dict_of_tuples(self): # GH #1491 @@ -1169,7 +1169,7 @@ def test_constructor_from_items(self): columns=self.mixed_frame.columns, orient='index') tm.assert_frame_equal(recons, self.mixed_frame) - tm.assertIsInstance(recons['foo'][0], tuple) + assert isinstance(recons['foo'][0], tuple) rs = DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])], orient='index', diff --git a/pandas/tests/frame/test_convert_to.py b/pandas/tests/frame/test_convert_to.py index 8323d5ed9069f..24a0e9c866eaf 100644 --- a/pandas/tests/frame/test_convert_to.py +++ b/pandas/tests/frame/test_convert_to.py @@ -45,7 +45,7 @@ def test_to_dict(self): expected_records = [{'A': 1.0, 'B': '1'}, {'A': 2.0, 'B': '2'}, {'A': np.nan, 'B': '3'}] - tm.assertIsInstance(recons_data, list) + assert isinstance(recons_data, list) self.assertEqual(len(recons_data), 3) for l, r in zip(recons_data, expected_records): tm.assert_dict_equal(l, r) diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index a04565ab9f54f..d25a62c5e5932 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -1830,14 +1830,14 @@ def test_iloc_duplicates(self): result = df.iloc[0] with catch_warnings(record=True): result2 = df.ix[0] - tm.assertIsInstance(result, Series) + assert isinstance(result, Series) assert_almost_equal(result.values, df.values[0]) assert_series_equal(result, result2) with catch_warnings(record=True): result = df.T.iloc[:, 0] result2 = df.T.ix[:, 0] - tm.assertIsInstance(result, Series) + assert isinstance(result, Series) assert_almost_equal(result.values, df.values[0]) assert_series_equal(result, result2) diff --git a/pandas/tests/frame/test_period.py b/pandas/tests/frame/test_period.py index 7f808723ac636..c1b5a92725868 100644 --- a/pandas/tests/frame/test_period.py +++ b/pandas/tests/frame/test_period.py @@ -41,7 +41,7 @@ def test_frame_setitem(self): self.assertEqual(rng.name, 'index') rs = df.reset_index().set_index('index') - tm.assertIsInstance(rs.index, PeriodIndex) + assert isinstance(rs.index, PeriodIndex) tm.assert_index_equal(rs.index, rng) def test_frame_to_time_stamp(self): diff --git a/pandas/tests/frame/test_subclass.py b/pandas/tests/frame/test_subclass.py index 1899df74c60ab..995abfb1ca01a 100644 --- a/pandas/tests/frame/test_subclass.py +++ b/pandas/tests/frame/test_subclass.py @@ -99,32 +99,32 @@ def test_indexing_sliced(self): res = df.loc[:, 'X'] exp = tm.SubclassedSeries([1, 2, 3], index=list('abc'), name='X') tm.assert_series_equal(res, exp) - tm.assertIsInstance(res, tm.SubclassedSeries) + assert isinstance(res, tm.SubclassedSeries) res = df.iloc[:, 1] exp = tm.SubclassedSeries([4, 5, 6], index=list('abc'), name='Y') tm.assert_series_equal(res, exp) - tm.assertIsInstance(res, tm.SubclassedSeries) + assert isinstance(res, tm.SubclassedSeries) res = df.loc[:, 'Z'] exp = tm.SubclassedSeries([7, 8, 9], index=list('abc'), name='Z') tm.assert_series_equal(res, exp) - tm.assertIsInstance(res, tm.SubclassedSeries) + assert isinstance(res, tm.SubclassedSeries) res = df.loc['a', :] exp = tm.SubclassedSeries([1, 4, 7], index=list('XYZ'), name='a') tm.assert_series_equal(res, exp) - tm.assertIsInstance(res, tm.SubclassedSeries) + assert isinstance(res, tm.SubclassedSeries) res = df.iloc[1, :] exp = tm.SubclassedSeries([2, 5, 8], index=list('XYZ'), name='b') tm.assert_series_equal(res, exp) - tm.assertIsInstance(res, tm.SubclassedSeries) + assert isinstance(res, tm.SubclassedSeries) res = df.loc['c', :] exp = tm.SubclassedSeries([3, 6, 9], index=list('XYZ'), name='c') tm.assert_series_equal(res, exp) - tm.assertIsInstance(res, tm.SubclassedSeries) + assert isinstance(res, tm.SubclassedSeries) def test_to_panel_expanddim(self): # GH 9762 @@ -173,15 +173,15 @@ def test_subclass_align(self): exp2 = tm.SubclassedDataFrame({'c': [1, 2, np.nan, 4, np.nan], 'd': [1, 2, np.nan, 4, np.nan]}, index=list('ABCDE')) - tm.assertIsInstance(res1, tm.SubclassedDataFrame) + assert isinstance(res1, tm.SubclassedDataFrame) tm.assert_frame_equal(res1, exp1) - tm.assertIsInstance(res2, tm.SubclassedDataFrame) + assert isinstance(res2, tm.SubclassedDataFrame) tm.assert_frame_equal(res2, exp2) res1, res2 = df1.a.align(df2.c) - tm.assertIsInstance(res1, tm.SubclassedSeries) + assert isinstance(res1, tm.SubclassedSeries) tm.assert_series_equal(res1, exp1.a) - tm.assertIsInstance(res2, tm.SubclassedSeries) + assert isinstance(res2, tm.SubclassedSeries) tm.assert_series_equal(res2, exp2.c) def test_subclass_align_combinations(self): @@ -199,23 +199,23 @@ def test_subclass_align_combinations(self): exp2 = pd.Series([1, 2, np.nan, 4, np.nan], index=list('ABCDE'), name='x') - tm.assertIsInstance(res1, tm.SubclassedDataFrame) + assert isinstance(res1, tm.SubclassedDataFrame) tm.assert_frame_equal(res1, exp1) - tm.assertIsInstance(res2, tm.SubclassedSeries) + assert isinstance(res2, tm.SubclassedSeries) tm.assert_series_equal(res2, exp2) # series + frame res1, res2 = s.align(df) - tm.assertIsInstance(res1, tm.SubclassedSeries) + assert isinstance(res1, tm.SubclassedSeries) tm.assert_series_equal(res1, exp2) - tm.assertIsInstance(res2, tm.SubclassedDataFrame) + assert isinstance(res2, tm.SubclassedDataFrame) tm.assert_frame_equal(res2, exp1) def test_subclass_iterrows(self): # GH 13977 df = tm.SubclassedDataFrame({'a': [1]}) for i, row in df.iterrows(): - tm.assertIsInstance(row, tm.SubclassedSeries) + assert isinstance(row, tm.SubclassedSeries) tm.assert_series_equal(row, df.loc[i]) def test_subclass_sparse_slice(self): diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py index accad0eaabbbb..c521ba9ec215a 100644 --- a/pandas/tests/frame/test_timeseries.py +++ b/pandas/tests/frame/test_timeseries.py @@ -372,10 +372,10 @@ def test_asfreq_datetimeindex(self): index=[datetime(2011, 11, 1), datetime(2011, 11, 2), datetime(2011, 11, 3)]) df = df.asfreq('B') - tm.assertIsInstance(df.index, DatetimeIndex) + assert isinstance(df.index, DatetimeIndex) ts = df['A'].asfreq('B') - tm.assertIsInstance(ts.index, DatetimeIndex) + assert isinstance(ts.index, DatetimeIndex) def test_asfreq_fillvalue(self): # test for fill value during upsampling, related to issue 3715 diff --git a/pandas/tests/frame/test_to_csv.py b/pandas/tests/frame/test_to_csv.py index a691e398c5fc4..f7da45e14cbde 100644 --- a/pandas/tests/frame/test_to_csv.py +++ b/pandas/tests/frame/test_to_csv.py @@ -883,7 +883,7 @@ def test_to_csv_path_is_none(self): # Make sure we return string for consistency with # Series.to_csv() csv_str = self.frame.to_csv(path_or_buf=None) - self.assertIsInstance(csv_str, str) + assert isinstance(csv_str, str) recons = pd.read_csv(StringIO(csv_str), index_col=0) assert_frame_equal(self.frame, recons) diff --git a/pandas/tests/groupby/test_aggregate.py b/pandas/tests/groupby/test_aggregate.py index df5f7abd64d8e..d91340312d7c2 100644 --- a/pandas/tests/groupby/test_aggregate.py +++ b/pandas/tests/groupby/test_aggregate.py @@ -117,7 +117,7 @@ def test_agg_period_index(self): prng = period_range('2012-1-1', freq='M', periods=3) df = DataFrame(np.random.randn(3, 2), index=prng) rs = df.groupby(level=0).sum() - tm.assertIsInstance(rs.index, PeriodIndex) + assert isinstance(rs.index, PeriodIndex) # GH 3579 index = period_range(start='1999-01', periods=5, freq='M') @@ -464,7 +464,7 @@ def aggfun(ser): return ser.size result = DataFrame().groupby(self.df.A).agg(aggfun) - tm.assertIsInstance(result, DataFrame) + assert isinstance(result, DataFrame) self.assertEqual(len(result), 0) def test_agg_item_by_item_raise_typeerror(self): diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 6a942edfffe7c..ea76fa24cc37c 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -740,7 +740,7 @@ def func(dataf): return dataf["val2"] - dataf["val2"].mean() result = df1.groupby("val1", squeeze=True).apply(func) - tm.assertIsInstance(result, Series) + assert isinstance(result, Series) df2 = DataFrame( [{"val1": 1, "val2": 20}, @@ -753,12 +753,12 @@ def func(dataf): return dataf["val2"] - dataf["val2"].mean() result = df2.groupby("val1", squeeze=True).apply(func) - tm.assertIsInstance(result, Series) + assert isinstance(result, Series) # GH3596, return a consistent type (regression in 0.11 from 0.10.1) df = DataFrame([[1, 1], [1, 1]], columns=['X', 'Y']) result = df.groupby('X', squeeze=False).count() - tm.assertIsInstance(result, DataFrame) + assert isinstance(result, DataFrame) # GH5592 # inconcistent return type @@ -1566,22 +1566,22 @@ def test_as_index_series_return_frame(self): result = grouped['C'].agg(np.sum) expected = grouped.agg(np.sum).loc[:, ['A', 'C']] - tm.assertIsInstance(result, DataFrame) + assert isinstance(result, DataFrame) assert_frame_equal(result, expected) result2 = grouped2['C'].agg(np.sum) expected2 = grouped2.agg(np.sum).loc[:, ['A', 'B', 'C']] - tm.assertIsInstance(result2, DataFrame) + assert isinstance(result2, DataFrame) assert_frame_equal(result2, expected2) result = grouped['C'].sum() expected = grouped.sum().loc[:, ['A', 'C']] - tm.assertIsInstance(result, DataFrame) + assert isinstance(result, DataFrame) assert_frame_equal(result, expected) result2 = grouped2['C'].sum() expected2 = grouped2.sum().loc[:, ['A', 'B', 'C']] - tm.assertIsInstance(result2, DataFrame) + assert isinstance(result2, DataFrame) assert_frame_equal(result2, expected2) # corner case @@ -2000,7 +2000,7 @@ def test_wrap_aggregated_output_multindex(self): keys = [np.array([0, 0, 1]), np.array([0, 0, 1])] agged = df.groupby(keys).agg(np.mean) - tm.assertIsInstance(agged.columns, MultiIndex) + assert isinstance(agged.columns, MultiIndex) def aggfun(ser): if ser.name == ('foo', 'one'): @@ -2182,7 +2182,7 @@ def f(piece): grouped = ts.groupby(lambda x: x.month) result = grouped.apply(f) - tm.assertIsInstance(result, DataFrame) + assert isinstance(result, DataFrame) tm.assert_index_equal(result.index, ts.index) def test_apply_series_yield_constant(self): @@ -2818,11 +2818,11 @@ def convert_force_pure(x): result = grouped.agg(convert_fast) self.assertEqual(result.dtype, np.object_) - tm.assertIsInstance(result[0], Decimal) + assert isinstance(result[0], Decimal) result = grouped.agg(convert_force_pure) self.assertEqual(result.dtype, np.object_) - tm.assertIsInstance(result[0], Decimal) + assert isinstance(result[0], Decimal) def test_fast_apply(self): # make sure that fast apply is correctly called @@ -3197,7 +3197,7 @@ def g(group): result = self.df.groupby('A')['C'].apply(f) expected = self.df.groupby('A')['C'].apply(g) - tm.assertIsInstance(result, Series) + assert isinstance(result, Series) assert_series_equal(result, expected) def test_getitem_list_of_columns(self): diff --git a/pandas/tests/groupby/test_timegrouper.py b/pandas/tests/groupby/test_timegrouper.py index f97f59cd92262..dfc23d3db21bc 100644 --- a/pandas/tests/groupby/test_timegrouper.py +++ b/pandas/tests/groupby/test_timegrouper.py @@ -370,7 +370,7 @@ def test_groupby_groups_datetimeindex(self): # it works! groups = grouped.groups - tm.assertIsInstance(list(groups.keys())[0], datetime) + assert isinstance(list(groups.keys())[0], datetime) # GH 11442 index = pd.date_range('2015/01/01', periods=5, name='date') diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index ecf85407d6c72..91c08764985a9 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -162,7 +162,7 @@ def test_str(self): def test_dtype_str(self): for idx in self.indices.values(): dtype = idx.dtype_str - self.assertIsInstance(dtype, compat.string_types) + assert isinstance(dtype, compat.string_types) self.assertEqual(dtype, str(idx.dtype)) def test_repr_max_seq_item_setting(self): diff --git a/pandas/tests/indexes/datetimes/test_astype.py b/pandas/tests/indexes/datetimes/test_astype.py index 31aecccdd9dad..3d7814b7340bc 100644 --- a/pandas/tests/indexes/datetimes/test_astype.py +++ b/pandas/tests/indexes/datetimes/test_astype.py @@ -126,9 +126,9 @@ def test_index_convert_to_datetime_array(self): def _check_rng(rng): converted = rng.to_pydatetime() - tm.assertIsInstance(converted, np.ndarray) + assert isinstance(converted, np.ndarray) for x, stamp in zip(converted, rng): - tm.assertIsInstance(x, datetime) + assert isinstance(x, datetime) self.assertEqual(x, stamp.to_pydatetime()) self.assertEqual(x.tzinfo, stamp.tzinfo) @@ -146,9 +146,9 @@ def test_index_convert_to_datetime_array_explicit_pytz(self): def _check_rng(rng): converted = rng.to_pydatetime() - tm.assertIsInstance(converted, np.ndarray) + assert isinstance(converted, np.ndarray) for x, stamp in zip(converted, rng): - tm.assertIsInstance(x, datetime) + assert isinstance(x, datetime) self.assertEqual(x, stamp.to_pydatetime()) self.assertEqual(x.tzinfo, stamp.tzinfo) @@ -167,9 +167,9 @@ def test_index_convert_to_datetime_array_dateutil(self): def _check_rng(rng): converted = rng.to_pydatetime() - tm.assertIsInstance(converted, np.ndarray) + assert isinstance(converted, np.ndarray) for x, stamp in zip(converted, rng): - tm.assertIsInstance(x, datetime) + assert isinstance(x, datetime) self.assertEqual(x, stamp.to_pydatetime()) self.assertEqual(x.tzinfo, stamp.tzinfo) diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index f8f445f2dc6a0..3c00fb32649bb 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -281,7 +281,7 @@ def test_daterange_bug_456(self): rng2.offset = BDay() result = rng1.union(rng2) - tm.assertIsInstance(result, DatetimeIndex) + assert isinstance(result, DatetimeIndex) def test_error_with_zero_monthends(self): self.assertRaises(ValueError, date_range, '1/1/2000', '1/1/2001', @@ -537,7 +537,7 @@ def test_daterange_bug_456(self): rng2.offset = CDay() result = rng1.union(rng2) - tm.assertIsInstance(result, DatetimeIndex) + assert isinstance(result, DatetimeIndex) def test_cdaterange(self): rng = cdate_range('2013-05-01', periods=3) diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index 69f5ee0e7dc14..cd7e8cb782f12 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -161,13 +161,13 @@ def test_ufunc_coercions(self): delta = np.timedelta64(1, 'D') for result in [idx + delta, np.add(idx, delta)]: - tm.assertIsInstance(result, DatetimeIndex) + assert isinstance(result, DatetimeIndex) exp = date_range('2011-01-02', periods=3, freq='2D', name='x') tm.assert_index_equal(result, exp) self.assertEqual(result.freq, '2D') for result in [idx - delta, np.subtract(idx, delta)]: - tm.assertIsInstance(result, DatetimeIndex) + assert isinstance(result, DatetimeIndex) exp = date_range('2010-12-31', periods=3, freq='2D', name='x') tm.assert_index_equal(result, exp) self.assertEqual(result.freq, '2D') @@ -175,14 +175,14 @@ def test_ufunc_coercions(self): delta = np.array([np.timedelta64(1, 'D'), np.timedelta64(2, 'D'), np.timedelta64(3, 'D')]) for result in [idx + delta, np.add(idx, delta)]: - tm.assertIsInstance(result, DatetimeIndex) + assert isinstance(result, DatetimeIndex) exp = DatetimeIndex(['2011-01-02', '2011-01-05', '2011-01-08'], freq='3D', name='x') tm.assert_index_equal(result, exp) self.assertEqual(result.freq, '3D') for result in [idx - delta, np.subtract(idx, delta)]: - tm.assertIsInstance(result, DatetimeIndex) + assert isinstance(result, DatetimeIndex) exp = DatetimeIndex(['2010-12-31', '2011-01-01', '2011-01-02'], freq='D', name='x') tm.assert_index_equal(result, exp) @@ -227,7 +227,7 @@ def test_append_join_nondatetimeindex(self): idx = Index(['a', 'b', 'c', 'd']) result = rng.append(idx) - tm.assertIsInstance(result[0], Timestamp) + assert isinstance(result[0], Timestamp) # it works rng.join(idx, how='outer') @@ -394,7 +394,7 @@ def test_iteration_preserves_tz(self): def test_misc_coverage(self): rng = date_range('1/1/2000', periods=5) result = rng.groupby(rng.day) - tm.assertIsInstance(list(result.values())[0][0], Timestamp) + assert isinstance(list(result.values())[0][0], Timestamp) idx = DatetimeIndex(['2000-01-03', '2000-01-01', '2000-01-02']) self.assertFalse(idx.equals(list(idx))) @@ -477,7 +477,7 @@ def test_take(self): for taken in [taken1, taken2]: tm.assert_index_equal(taken, expected) - tm.assertIsInstance(taken, DatetimeIndex) + assert isinstance(taken, DatetimeIndex) self.assertIsNone(taken.freq) self.assertEqual(taken.tz, expected.tz) self.assertEqual(taken.name, expected.name) @@ -559,7 +559,7 @@ def test_groupby_function_tuple_1677(self): monthly_group = df.groupby(lambda x: (x.year, x.month)) result = monthly_group.mean() - tm.assertIsInstance(result.index[0], tuple) + assert isinstance(result.index[0], tuple) def test_append_numpy_bug_1681(self): # another datetime64 bug diff --git a/pandas/tests/indexes/datetimes/test_misc.py b/pandas/tests/indexes/datetimes/test_misc.py index 937e508bfbf9f..d7507360506ca 100644 --- a/pandas/tests/indexes/datetimes/test_misc.py +++ b/pandas/tests/indexes/datetimes/test_misc.py @@ -13,7 +13,7 @@ def test_1700(self): 2345901.5]) r2 = date_range(start=Timestamp('1710-10-01'), periods=5, freq='D').to_julian_date() - self.assertIsInstance(r2, Float64Index) + assert isinstance(r2, Float64Index) tm.assert_index_equal(r1, r2) def test_2000(self): @@ -21,7 +21,7 @@ def test_2000(self): 2451605.5]) r2 = date_range(start=Timestamp('2000-02-27'), periods=5, freq='D').to_julian_date() - self.assertIsInstance(r2, Float64Index) + assert isinstance(r2, Float64Index) tm.assert_index_equal(r1, r2) def test_hour(self): @@ -30,7 +30,7 @@ def test_hour(self): 2451601.625, 2451601.6666666666666666]) r2 = date_range(start=Timestamp('2000-02-27'), periods=5, freq='H').to_julian_date() - self.assertIsInstance(r2, Float64Index) + assert isinstance(r2, Float64Index) tm.assert_index_equal(r1, r2) def test_minute(self): @@ -39,7 +39,7 @@ def test_minute(self): 2451601.5020833333333333, 2451601.5027777777777777]) r2 = date_range(start=Timestamp('2000-02-27'), periods=5, freq='T').to_julian_date() - self.assertIsInstance(r2, Float64Index) + assert isinstance(r2, Float64Index) tm.assert_index_equal(r1, r2) def test_second(self): @@ -48,7 +48,7 @@ def test_second(self): 2451601.5000347222222222, 2451601.5000462962962962]) r2 = date_range(start=Timestamp('2000-02-27'), periods=5, freq='S').to_julian_date() - self.assertIsInstance(r2, Float64Index) + assert isinstance(r2, Float64Index) tm.assert_index_equal(r1, r2) diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py index 315141fac8a8a..f04207caef6ab 100644 --- a/pandas/tests/indexes/datetimes/test_ops.py +++ b/pandas/tests/indexes/datetimes/test_ops.py @@ -938,7 +938,7 @@ def test_1700(self): 2345901.5]) r2 = date_range(start=Timestamp('1710-10-01'), periods=5, freq='D').to_julian_date() - self.assertIsInstance(r2, Float64Index) + assert isinstance(r2, Float64Index) tm.assert_index_equal(r1, r2) def test_2000(self): @@ -946,7 +946,7 @@ def test_2000(self): 2451605.5]) r2 = date_range(start=Timestamp('2000-02-27'), periods=5, freq='D').to_julian_date() - self.assertIsInstance(r2, Float64Index) + assert isinstance(r2, Float64Index) tm.assert_index_equal(r1, r2) def test_hour(self): @@ -955,7 +955,7 @@ def test_hour(self): 2451601.625, 2451601.6666666666666666]) r2 = date_range(start=Timestamp('2000-02-27'), periods=5, freq='H').to_julian_date() - self.assertIsInstance(r2, Float64Index) + assert isinstance(r2, Float64Index) tm.assert_index_equal(r1, r2) def test_minute(self): @@ -964,7 +964,7 @@ def test_minute(self): 2451601.5020833333333333, 2451601.5027777777777777]) r2 = date_range(start=Timestamp('2000-02-27'), periods=5, freq='T').to_julian_date() - self.assertIsInstance(r2, Float64Index) + assert isinstance(r2, Float64Index) tm.assert_index_equal(r1, r2) def test_second(self): @@ -973,7 +973,7 @@ def test_second(self): 2451601.5000347222222222, 2451601.5000462962962962]) r2 = date_range(start=Timestamp('2000-02-27'), periods=5, freq='S').to_julian_date() - self.assertIsInstance(r2, Float64Index) + assert isinstance(r2, Float64Index) tm.assert_index_equal(r1, r2) @@ -1144,7 +1144,7 @@ def test_getitem(self): fancy_indexed = self.rng[[4, 3, 2, 1, 0]] self.assertEqual(len(fancy_indexed), 5) - tm.assertIsInstance(fancy_indexed, DatetimeIndex) + assert isinstance(fancy_indexed, DatetimeIndex) self.assertIsNone(fancy_indexed.freq) # 32-bit vs. 64-bit platforms @@ -1239,7 +1239,7 @@ def test_getitem(self): fancy_indexed = self.rng[[4, 3, 2, 1, 0]] self.assertEqual(len(fancy_indexed), 5) - tm.assertIsInstance(fancy_indexed, DatetimeIndex) + assert isinstance(fancy_indexed, DatetimeIndex) self.assertIsNone(fancy_indexed.freq) # 32-bit vs. 64-bit platforms diff --git a/pandas/tests/indexes/datetimes/test_partial_slcing.py b/pandas/tests/indexes/datetimes/test_partial_slcing.py index a960f5cf9235a..f20e684459e02 100644 --- a/pandas/tests/indexes/datetimes/test_partial_slcing.py +++ b/pandas/tests/indexes/datetimes/test_partial_slcing.py @@ -150,7 +150,7 @@ def test_partial_slicing_dataframe(self): ts_string = timestamp.strftime(formats[rnum]) # make ts_string as precise as index result = df['a'][ts_string] - self.assertIsInstance(result, np.int64) + assert isinstance(result, np.int64) self.assertEqual(result, expected) self.assertRaises(KeyError, df.__getitem__, ts_string) @@ -177,7 +177,7 @@ def test_partial_slicing_dataframe(self): for fmt in formats[rnum + 1:]: ts_string = index[1].strftime(fmt) result = df['a'][ts_string] - self.assertIsInstance(result, np.int64) + assert isinstance(result, np.int64) self.assertEqual(result, 2) self.assertRaises(KeyError, df.__getitem__, ts_string) diff --git a/pandas/tests/indexes/datetimes/test_setops.py b/pandas/tests/indexes/datetimes/test_setops.py index 31e59aab6b1eb..3191b0e2c586d 100644 --- a/pandas/tests/indexes/datetimes/test_setops.py +++ b/pandas/tests/indexes/datetimes/test_setops.py @@ -184,11 +184,11 @@ def test_datetimeindex_union_join_empty(self): empty = Index([]) result = dti.union(empty) - tm.assertIsInstance(result, DatetimeIndex) + assert isinstance(result, DatetimeIndex) self.assertIs(result, result) result = dti.join(empty) - tm.assertIsInstance(result, DatetimeIndex) + assert isinstance(result, DatetimeIndex) def test_join_nonunique(self): idx1 = to_datetime(['2012-11-06 16:00:11.477563', @@ -210,21 +210,21 @@ def test_union(self): right = self.rng[5:10] the_union = left.union(right) - tm.assertIsInstance(the_union, DatetimeIndex) + assert isinstance(the_union, DatetimeIndex) # non-overlapping, gap in middle left = self.rng[:5] right = self.rng[10:] the_union = left.union(right) - tm.assertIsInstance(the_union, Index) + assert isinstance(the_union, Index) # non-overlapping, no gap left = self.rng[:5] right = self.rng[5:10] the_union = left.union(right) - tm.assertIsInstance(the_union, DatetimeIndex) + assert isinstance(the_union, DatetimeIndex) # order does not matter tm.assert_index_equal(right.union(left), the_union) @@ -233,7 +233,7 @@ def test_union(self): rng = date_range(START, END, freq=BMonthEnd()) the_union = self.rng.union(rng) - tm.assertIsInstance(the_union, DatetimeIndex) + assert isinstance(the_union, DatetimeIndex) def test_outer_join(self): # should just behave as union @@ -243,14 +243,14 @@ def test_outer_join(self): right = self.rng[5:10] the_join = left.join(right, how='outer') - tm.assertIsInstance(the_join, DatetimeIndex) + assert isinstance(the_join, DatetimeIndex) # non-overlapping, gap in middle left = self.rng[:5] right = self.rng[10:] the_join = left.join(right, how='outer') - tm.assertIsInstance(the_join, DatetimeIndex) + assert isinstance(the_join, DatetimeIndex) self.assertIsNone(the_join.freq) # non-overlapping, no gap @@ -258,13 +258,13 @@ def test_outer_join(self): right = self.rng[5:10] the_join = left.join(right, how='outer') - tm.assertIsInstance(the_join, DatetimeIndex) + assert isinstance(the_join, DatetimeIndex) # overlapping, but different offset rng = date_range(START, END, freq=BMonthEnd()) the_join = self.rng.join(rng, how='outer') - tm.assertIsInstance(the_join, DatetimeIndex) + assert isinstance(the_join, DatetimeIndex) self.assertIsNone(the_join.freq) def test_union_not_cacheable(self): @@ -287,7 +287,7 @@ def test_intersection(self): the_int = rng1.intersection(rng2) expected = rng[10:25] tm.assert_index_equal(the_int, expected) - tm.assertIsInstance(the_int, DatetimeIndex) + assert isinstance(the_int, DatetimeIndex) self.assertEqual(the_int.offset, rng.offset) the_int = rng1.intersection(rng2.view(DatetimeIndex)) @@ -354,21 +354,21 @@ def test_union(self): right = self.rng[5:10] the_union = left.union(right) - tm.assertIsInstance(the_union, DatetimeIndex) + assert isinstance(the_union, DatetimeIndex) # non-overlapping, gap in middle left = self.rng[:5] right = self.rng[10:] the_union = left.union(right) - tm.assertIsInstance(the_union, Index) + assert isinstance(the_union, Index) # non-overlapping, no gap left = self.rng[:5] right = self.rng[5:10] the_union = left.union(right) - tm.assertIsInstance(the_union, DatetimeIndex) + assert isinstance(the_union, DatetimeIndex) # order does not matter tm.assert_index_equal(right.union(left), the_union) @@ -377,7 +377,7 @@ def test_union(self): rng = date_range(START, END, freq=BMonthEnd()) the_union = self.rng.union(rng) - tm.assertIsInstance(the_union, DatetimeIndex) + assert isinstance(the_union, DatetimeIndex) def test_outer_join(self): # should just behave as union @@ -387,14 +387,14 @@ def test_outer_join(self): right = self.rng[5:10] the_join = left.join(right, how='outer') - tm.assertIsInstance(the_join, DatetimeIndex) + assert isinstance(the_join, DatetimeIndex) # non-overlapping, gap in middle left = self.rng[:5] right = self.rng[10:] the_join = left.join(right, how='outer') - tm.assertIsInstance(the_join, DatetimeIndex) + assert isinstance(the_join, DatetimeIndex) self.assertIsNone(the_join.freq) # non-overlapping, no gap @@ -402,13 +402,13 @@ def test_outer_join(self): right = self.rng[5:10] the_join = left.join(right, how='outer') - tm.assertIsInstance(the_join, DatetimeIndex) + assert isinstance(the_join, DatetimeIndex) # overlapping, but different offset rng = date_range(START, END, freq=BMonthEnd()) the_join = self.rng.join(rng, how='outer') - tm.assertIsInstance(the_join, DatetimeIndex) + assert isinstance(the_join, DatetimeIndex) self.assertIsNone(the_join.freq) def test_intersection_bug(self): diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index 8e1721041f105..faebd4b2761f1 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -391,15 +391,15 @@ def test_unit_consistency(self): expected = Timestamp('1970-05-09 14:25:11') result = pd.to_datetime(11111111, unit='s', errors='raise') self.assertEqual(result, expected) - self.assertIsInstance(result, Timestamp) + assert isinstance(result, Timestamp) result = pd.to_datetime(11111111, unit='s', errors='coerce') self.assertEqual(result, expected) - self.assertIsInstance(result, Timestamp) + assert isinstance(result, Timestamp) result = pd.to_datetime(11111111, unit='s', errors='ignore') self.assertEqual(result, expected) - self.assertIsInstance(result, Timestamp) + assert isinstance(result, Timestamp) def test_unit_with_numeric(self): @@ -761,7 +761,7 @@ def test_string_na_nat_conversion(self): tm.assert_almost_equal(result, expected) result2 = to_datetime(strings) - tm.assertIsInstance(result2, DatetimeIndex) + assert isinstance(result2, DatetimeIndex) tm.assert_numpy_array_equal(result, result2.values) malformed = np.array(['1/100/2000', np.nan], dtype=object) @@ -1294,7 +1294,7 @@ def test_parsers_time(self): Series(expected_arr, name="test")) res = tools.to_time(np.array(arg)) - self.assertIsInstance(res, list) + assert isinstance(res, list) assert res == expected_arr def test_parsers_monthfreq(self): diff --git a/pandas/tests/indexes/period/test_construction.py b/pandas/tests/indexes/period/test_construction.py index dd7455e48752b..4e53ac56ec187 100644 --- a/pandas/tests/indexes/period/test_construction.py +++ b/pandas/tests/indexes/period/test_construction.py @@ -185,7 +185,7 @@ def test_constructor_dtype(self): def test_constructor_empty(self): idx = pd.PeriodIndex([], freq='M') - tm.assertIsInstance(idx, PeriodIndex) + assert isinstance(idx, PeriodIndex) self.assertEqual(len(idx), 0) self.assertEqual(idx.freq, 'M') @@ -463,7 +463,7 @@ def test_map_with_string_constructor(self): res = index.map(t) # should return an Index - tm.assertIsInstance(res, Index) + assert isinstance(res, Index) # preserve element types self.assertTrue(all(isinstance(resi, t) for resi in res)) diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py index 593dc6f77d3f9..419a917415f98 100644 --- a/pandas/tests/indexes/period/test_indexing.py +++ b/pandas/tests/indexes/period/test_indexing.py @@ -281,7 +281,7 @@ def test_take_misc(self): for taken in [taken1, taken2]: tm.assert_index_equal(taken, expected) - tm.assertIsInstance(taken, PeriodIndex) + assert isinstance(taken, PeriodIndex) self.assertEqual(taken.freq, index.freq) self.assertEqual(taken.name, expected.name) diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index df4e8b2c0ad11..bb87e780012ce 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -230,7 +230,7 @@ def test_hash_error(self): def test_make_time_series(self): index = PeriodIndex(freq='A', start='1/1/2001', end='12/1/2009') series = Series(1, index=index) - tm.assertIsInstance(series, Series) + assert isinstance(series, Series) def test_shallow_copy_empty(self): @@ -703,7 +703,7 @@ def test_iteration(self): index = PeriodIndex(start='1/1/10', periods=4, freq='B') result = list(index) - tm.assertIsInstance(result[0], Period) + assert isinstance(result[0], Period) self.assertEqual(result[0].freq, index.freq) def test_is_full(self): @@ -731,16 +731,16 @@ def test_with_multi_index(self): s = Series([0, 1, 2, 3], index_as_arrays) - tm.assertIsInstance(s.index.levels[0], PeriodIndex) + assert isinstance(s.index.levels[0], PeriodIndex) - tm.assertIsInstance(s.index.values[0][0], Period) + assert isinstance(s.index.values[0][0], Period) def test_convert_array_of_periods(self): rng = period_range('1/1/2000', periods=20, freq='D') periods = list(rng) result = pd.Index(periods) - tm.assertIsInstance(result, PeriodIndex) + assert isinstance(result, PeriodIndex) def test_append_concat(self): # #1815 @@ -755,7 +755,7 @@ def test_append_concat(self): # drops index result = pd.concat([s1, s2]) - tm.assertIsInstance(result.index, PeriodIndex) + assert isinstance(result.index, PeriodIndex) self.assertEqual(result.index[0], s1.index[0]) def test_pickle_freq(self): diff --git a/pandas/tests/indexes/period/test_setops.py b/pandas/tests/indexes/period/test_setops.py index 29ae429a81027..e142b5179ad55 100644 --- a/pandas/tests/indexes/period/test_setops.py +++ b/pandas/tests/indexes/period/test_setops.py @@ -21,7 +21,7 @@ def test_joins(self): for kind in ['inner', 'outer', 'left', 'right']: joined = index.join(index[:-5], how=kind) - tm.assertIsInstance(joined, PeriodIndex) + assert isinstance(joined, PeriodIndex) self.assertEqual(joined.freq, index.freq) def test_join_self(self): diff --git a/pandas/tests/indexes/period/test_tools.py b/pandas/tests/indexes/period/test_tools.py index aa7a1d60f06ab..49bc4a4cabe59 100644 --- a/pandas/tests/indexes/period/test_tools.py +++ b/pandas/tests/indexes/period/test_tools.py @@ -176,7 +176,8 @@ def setUp(self): def test_tolist(self): index = PeriodIndex(freq='A', start='1/1/2001', end='12/1/2009') rs = index.tolist() - [tm.assertIsInstance(x, Period) for x in rs] + for x in rs: + assert isinstance(x, Period) recon = PeriodIndex(rs) tm.assert_index_equal(index, recon) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 9a4eaaa4355bd..221bd8d50cee6 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -53,7 +53,7 @@ def create_index(self): def test_new_axis(self): new_index = self.dateIndex[None, :] self.assertEqual(new_index.ndim, 2) - tm.assertIsInstance(new_index, np.ndarray) + assert isinstance(new_index, np.ndarray) def test_copy_and_deepcopy(self): super(TestIndex, self).test_copy_and_deepcopy() @@ -75,7 +75,7 @@ def test_constructor(self): # copy arr = np.array(self.strIndex) index = Index(arr, copy=True, name='name') - tm.assertIsInstance(index, Index) + assert isinstance(index, Index) self.assertEqual(index.name, 'name') tm.assert_numpy_array_equal(arr, index.values) arr[0] = "SOMEBIGLONGSTRING" @@ -90,15 +90,15 @@ def test_constructor_corner(self): self.assertRaises(TypeError, Index, 0) def test_construction_list_mixed_tuples(self): - # 10697 - # if we are constructing from a mixed list of tuples, make sure that we - # are independent of the sorting order + # see gh-10697: if we are constructing from a mixed list of tuples, + # make sure that we are independent of the sorting order. idx1 = Index([('A', 1), 'B']) - self.assertIsInstance(idx1, Index) and self.assertNotInstance( - idx1, MultiIndex) + assert isinstance(idx1, Index) + assert not isinstance(idx1, MultiIndex) + idx2 = Index(['B', ('A', 1)]) - self.assertIsInstance(idx2, Index) and self.assertNotInstance( - idx2, MultiIndex) + assert isinstance(idx2, Index) + assert not isinstance(idx2, MultiIndex) def test_constructor_from_index_datetimetz(self): idx = pd.date_range('2015-01-01 10:00', freq='D', periods=3, @@ -263,7 +263,7 @@ def test_index_ctor_infer_periodindex(self): xp = period_range('2012-1-1', freq='M', periods=3) rs = Index(xp) tm.assert_index_equal(rs, xp) - tm.assertIsInstance(rs, PeriodIndex) + assert isinstance(rs, PeriodIndex) def test_constructor_simple_new(self): idx = Index([1, 2, 3, 4, 5], name='int') @@ -510,7 +510,7 @@ def test_asof(self): self.assertEqual(self.dateIndex.asof(d + timedelta(1)), d) d = self.dateIndex[0].to_pydatetime() - tm.assertIsInstance(self.dateIndex.asof(d), Timestamp) + assert isinstance(self.dateIndex.asof(d), Timestamp) def test_asof_datetime_partial(self): idx = pd.date_range('2010-01-01', periods=2, freq='m') @@ -545,7 +545,7 @@ def _check(op): arr_result = op(arr, element) index_result = op(index, element) - self.assertIsInstance(index_result, np.ndarray) + assert isinstance(index_result, np.ndarray) tm.assert_numpy_array_equal(arr_result, index_result) _check(operator.eq) @@ -1465,7 +1465,7 @@ def test_str_attribute(self): idx = Index(['a1', 'a2', 'b1', 'b2']) expected = np.array([True, True, False, False]) tm.assert_numpy_array_equal(idx.str.startswith('a'), expected) - self.assertIsInstance(idx.str.startswith('a'), np.ndarray) + assert isinstance(idx.str.startswith('a'), np.ndarray) s = Series(range(4), index=idx) expected = Series(range(2), index=['a1', 'a2']) tm.assert_series_equal(s[s.index.str.startswith('a')], expected) diff --git a/pandas/tests/indexes/test_interval.py b/pandas/tests/indexes/test_interval.py index 842fab8ea768c..f9ddf936007b2 100644 --- a/pandas/tests/indexes/test_interval.py +++ b/pandas/tests/indexes/test_interval.py @@ -43,11 +43,11 @@ def test_constructors(self): self.assertTrue(expected.equals(actual)) actual = Index([Interval(0, 1), Interval(1, 2)]) - self.assertIsInstance(actual, IntervalIndex) + assert isinstance(actual, IntervalIndex) self.assertTrue(expected.equals(actual)) actual = Index(expected) - self.assertIsInstance(actual, IntervalIndex) + assert isinstance(actual, IntervalIndex) self.assertTrue(expected.equals(actual)) def test_constructors_other(self): diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index f0884ad36c11f..d10cf4e71c916 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -1648,7 +1648,7 @@ def test_difference(self): sortorder=0, names=self.index.names) - tm.assertIsInstance(result, MultiIndex) + assert isinstance(result, MultiIndex) self.assertTrue(result.equals(expected)) self.assertEqual(result.names, self.index.names) @@ -2029,7 +2029,7 @@ def _check_all(other): # some corner cases idx = Index(['three', 'one', 'two']) result = idx.join(self.index, level='second') - tm.assertIsInstance(result, MultiIndex) + assert isinstance(result, MultiIndex) assertRaisesRegexp(TypeError, "Join.*MultiIndex.*ambiguous", self.index.join, self.index, level=1) @@ -2077,11 +2077,11 @@ def test_join_multi(self): def test_reindex(self): result, indexer = self.index.reindex(list(self.index[:4])) - tm.assertIsInstance(result, MultiIndex) + assert isinstance(result, MultiIndex) self.check_level_names(result, self.index[:4].names) result, indexer = self.index.reindex(list(self.index)) - tm.assertIsInstance(result, MultiIndex) + assert isinstance(result, MultiIndex) self.assertIsNone(indexer) self.check_level_names(result, self.index.names) diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py index 495744f6d2763..b14175843ae20 100644 --- a/pandas/tests/indexes/test_numeric.py +++ b/pandas/tests/indexes/test_numeric.py @@ -205,23 +205,23 @@ def test_constructor(self): # explicit construction index = Float64Index([1, 2, 3, 4, 5]) - self.assertIsInstance(index, Float64Index) + assert isinstance(index, Float64Index) expected = np.array([1, 2, 3, 4, 5], dtype='float64') tm.assert_numpy_array_equal(index.values, expected) index = Float64Index(np.array([1, 2, 3, 4, 5])) - self.assertIsInstance(index, Float64Index) + assert isinstance(index, Float64Index) index = Float64Index([1., 2, 3, 4, 5]) - self.assertIsInstance(index, Float64Index) + assert isinstance(index, Float64Index) index = Float64Index(np.array([1., 2, 3, 4, 5])) - self.assertIsInstance(index, Float64Index) + assert isinstance(index, Float64Index) self.assertEqual(index.dtype, float) index = Float64Index(np.array([1., 2, 3, 4, 5]), dtype=np.float32) - self.assertIsInstance(index, Float64Index) + assert isinstance(index, Float64Index) self.assertEqual(index.dtype, np.float64) index = Float64Index(np.array([1, 2, 3, 4, 5]), dtype=np.float32) - self.assertIsInstance(index, Float64Index) + assert isinstance(index, Float64Index) self.assertEqual(index.dtype, np.float64) # nan handling @@ -589,33 +589,33 @@ def test_ufunc_coercions(self): idx = self._holder([1, 2, 3, 4, 5], name='x') result = np.sqrt(idx) - tm.assertIsInstance(result, Float64Index) + assert isinstance(result, Float64Index) exp = Float64Index(np.sqrt(np.array([1, 2, 3, 4, 5])), name='x') tm.assert_index_equal(result, exp) result = np.divide(idx, 2.) - tm.assertIsInstance(result, Float64Index) + assert isinstance(result, Float64Index) exp = Float64Index([0.5, 1., 1.5, 2., 2.5], name='x') tm.assert_index_equal(result, exp) # _evaluate_numeric_binop result = idx + 2. - tm.assertIsInstance(result, Float64Index) + assert isinstance(result, Float64Index) exp = Float64Index([3., 4., 5., 6., 7.], name='x') tm.assert_index_equal(result, exp) result = idx - 2. - tm.assertIsInstance(result, Float64Index) + assert isinstance(result, Float64Index) exp = Float64Index([-1., 0., 1., 2., 3.], name='x') tm.assert_index_equal(result, exp) result = idx * 1. - tm.assertIsInstance(result, Float64Index) + assert isinstance(result, Float64Index) exp = Float64Index([1., 2., 3., 4., 5.], name='x') tm.assert_index_equal(result, exp) result = idx / 2. - tm.assertIsInstance(result, Float64Index) + assert isinstance(result, Float64Index) exp = Float64Index([0.5, 1., 1.5, 2., 2.5], name='x') tm.assert_index_equal(result, exp) @@ -680,11 +680,11 @@ def test_constructor_corner(self): def test_coerce_list(self): # coerce things arr = Index([1, 2, 3, 4]) - tm.assertIsInstance(arr, Int64Index) + assert isinstance(arr, Int64Index) # but not if explicit dtype passed arr = Index([1, 2, 3, 4], dtype=object) - tm.assertIsInstance(arr, Index) + assert isinstance(arr, Index) def test_where(self): i = self.create_index() @@ -757,7 +757,7 @@ def test_join_inner(self): elidx = np.array([1, 6], dtype=np.intp) eridx = np.array([4, 1], dtype=np.intp) - tm.assertIsInstance(res, Int64Index) + assert isinstance(res, Int64Index) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) tm.assert_numpy_array_equal(ridx, eridx) @@ -771,7 +771,7 @@ def test_join_inner(self): elidx = np.array([1, 6], dtype=np.intp) eridx = np.array([1, 4], dtype=np.intp) - tm.assertIsInstance(res, Int64Index) + assert isinstance(res, Int64Index) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) tm.assert_numpy_array_equal(ridx, eridx) @@ -787,7 +787,7 @@ def test_join_left(self): eridx = np.array([-1, 4, -1, -1, -1, -1, 1, -1, -1, -1], dtype=np.intp) - tm.assertIsInstance(res, Int64Index) + assert isinstance(res, Int64Index) tm.assert_index_equal(res, eres) self.assertIsNone(lidx) tm.assert_numpy_array_equal(ridx, eridx) @@ -797,7 +797,7 @@ def test_join_left(self): return_indexers=True) eridx = np.array([-1, 1, -1, -1, -1, -1, 4, -1, -1, -1], dtype=np.intp) - tm.assertIsInstance(res, Int64Index) + assert isinstance(res, Int64Index) tm.assert_index_equal(res, eres) self.assertIsNone(lidx) tm.assert_numpy_array_equal(ridx, eridx) @@ -823,7 +823,7 @@ def test_join_right(self): eres = other elidx = np.array([-1, 6, -1, -1, 1, -1], dtype=np.intp) - tm.assertIsInstance(other, Int64Index) + assert isinstance(other, Int64Index) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) self.assertIsNone(ridx) @@ -833,7 +833,7 @@ def test_join_right(self): return_indexers=True) eres = other_mono elidx = np.array([-1, 1, -1, -1, 6, -1], dtype=np.intp) - tm.assertIsInstance(other, Int64Index) + assert isinstance(other, Int64Index) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) self.assertIsNone(ridx) @@ -893,7 +893,7 @@ def test_join_outer(self): eridx = np.array([-1, 3, 4, -1, 5, -1, 0, -1, -1, 1, -1, -1, -1, 2], dtype=np.intp) - tm.assertIsInstance(res, Int64Index) + assert isinstance(res, Int64Index) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) tm.assert_numpy_array_equal(ridx, eridx) @@ -908,7 +908,7 @@ def test_join_outer(self): dtype=np.intp) eridx = np.array([-1, 0, 1, -1, 2, -1, 3, -1, -1, 4, -1, -1, -1, 5], dtype=np.intp) - tm.assertIsInstance(res, Int64Index) + assert isinstance(res, Int64Index) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) tm.assert_numpy_array_equal(ridx, eridx) @@ -995,7 +995,7 @@ def test_join_inner(self): elidx = np.array([1, 4], dtype=np.intp) eridx = np.array([5, 2], dtype=np.intp) - tm.assertIsInstance(res, UInt64Index) + assert isinstance(res, UInt64Index) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) tm.assert_numpy_array_equal(ridx, eridx) @@ -1010,7 +1010,7 @@ def test_join_inner(self): elidx = np.array([1, 4], dtype=np.intp) eridx = np.array([3, 5], dtype=np.intp) - tm.assertIsInstance(res, UInt64Index) + assert isinstance(res, UInt64Index) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) tm.assert_numpy_array_equal(ridx, eridx) @@ -1027,7 +1027,7 @@ def test_join_left(self): eres = self.index eridx = np.array([-1, 5, -1, -1, 2], dtype=np.intp) - tm.assertIsInstance(res, UInt64Index) + assert isinstance(res, UInt64Index) tm.assert_index_equal(res, eres) self.assertIsNone(lidx) tm.assert_numpy_array_equal(ridx, eridx) @@ -1037,7 +1037,7 @@ def test_join_left(self): return_indexers=True) eridx = np.array([-1, 3, -1, -1, 5], dtype=np.intp) - tm.assertIsInstance(res, UInt64Index) + assert isinstance(res, UInt64Index) tm.assert_index_equal(res, eres) self.assertIsNone(lidx) tm.assert_numpy_array_equal(ridx, eridx) @@ -1070,7 +1070,7 @@ def test_join_right(self): elidx = np.array([-1, -1, 4, -1, -1, 1], dtype=np.intp) tm.assert_numpy_array_equal(lidx, elidx) - tm.assertIsInstance(other, UInt64Index) + assert isinstance(other, UInt64Index) tm.assert_index_equal(res, eres) self.assertIsNone(ridx) @@ -1080,7 +1080,7 @@ def test_join_right(self): eres = other_mono elidx = np.array([-1, -1, -1, 1, -1, 4], dtype=np.intp) - tm.assertIsInstance(other, UInt64Index) + assert isinstance(other, UInt64Index) tm.assert_numpy_array_equal(lidx, elidx) tm.assert_index_equal(res, eres) self.assertIsNone(ridx) @@ -1147,7 +1147,7 @@ def test_join_outer(self): elidx = np.array([0, -1, -1, -1, 1, -1, 2, 3, 4], dtype=np.intp) eridx = np.array([-1, 3, 4, 0, 5, 1, -1, -1, 2], dtype=np.intp) - tm.assertIsInstance(res, UInt64Index) + assert isinstance(res, UInt64Index) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) tm.assert_numpy_array_equal(ridx, eridx) @@ -1161,7 +1161,7 @@ def test_join_outer(self): elidx = np.array([0, -1, -1, -1, 1, -1, 2, 3, 4], dtype=np.intp) eridx = np.array([-1, 0, 1, 2, 3, 4, -1, -1, 5], dtype=np.intp) - tm.assertIsInstance(res, UInt64Index) + assert isinstance(res, UInt64Index) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) tm.assert_numpy_array_equal(ridx, eridx) diff --git a/pandas/tests/indexes/test_range.py b/pandas/tests/indexes/test_range.py index cda47ddc8cd8b..6168deba7e72c 100644 --- a/pandas/tests/indexes/test_range.py +++ b/pandas/tests/indexes/test_range.py @@ -68,7 +68,7 @@ def testit(): def test_constructor(self): index = RangeIndex(5) expected = np.arange(5, dtype=np.int64) - self.assertIsInstance(index, RangeIndex) + assert isinstance(index, RangeIndex) self.assertEqual(index._start, 0) self.assertEqual(index._stop, 5) self.assertEqual(index._step, 1) @@ -77,13 +77,13 @@ def test_constructor(self): index = RangeIndex(1, 5) expected = np.arange(1, 5, dtype=np.int64) - self.assertIsInstance(index, RangeIndex) + assert isinstance(index, RangeIndex) self.assertEqual(index._start, 1) tm.assert_index_equal(Index(expected), index) index = RangeIndex(1, 5, 2) expected = np.arange(1, 5, 2, dtype=np.int64) - self.assertIsInstance(index, RangeIndex) + assert isinstance(index, RangeIndex) self.assertEqual(index._step, 2) tm.assert_index_equal(Index(expected), index) @@ -94,7 +94,7 @@ def test_constructor(self): for index in [RangeIndex(0), RangeIndex(start=0), RangeIndex(stop=0), RangeIndex(0, 0)]: expected = np.empty(0, dtype=np.int64) - self.assertIsInstance(index, RangeIndex) + assert isinstance(index, RangeIndex) self.assertEqual(index._start, 0) self.assertEqual(index._stop, 0) self.assertEqual(index._step, 1) @@ -107,7 +107,7 @@ def test_constructor(self): RangeIndex(start=0, name='Foo'), RangeIndex(stop=0, name='Foo'), RangeIndex(0, 0, name='Foo')]: - self.assertIsInstance(index, RangeIndex) + assert isinstance(index, RangeIndex) self.assertEqual(index.name, 'Foo') # we don't allow on a bare Index @@ -421,7 +421,7 @@ def test_join_outer(self): eridx = np.array([-1, -1, -1, -1, -1, -1, -1, -1, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0], dtype=np.intp) - self.assertIsInstance(res, Int64Index) + assert isinstance(res, Int64Index) self.assertFalse(isinstance(res, RangeIndex)) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) @@ -435,7 +435,7 @@ def test_join_outer(self): noidx_res = self.index.join(other, how='outer') tm.assert_index_equal(res, noidx_res) - self.assertIsInstance(res, Int64Index) + assert isinstance(res, Int64Index) self.assertFalse(isinstance(res, RangeIndex)) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) @@ -458,7 +458,7 @@ def test_join_inner(self): elidx = np.array([8, 9], dtype=np.intp) eridx = np.array([9, 7], dtype=np.intp) - self.assertIsInstance(res, Int64Index) + assert isinstance(res, Int64Index) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) tm.assert_numpy_array_equal(ridx, eridx) @@ -469,7 +469,7 @@ def test_join_inner(self): res, lidx, ridx = self.index.join(other, how='inner', return_indexers=True) - self.assertIsInstance(res, RangeIndex) + assert isinstance(res, RangeIndex) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) tm.assert_numpy_array_equal(ridx, eridx) @@ -483,7 +483,7 @@ def test_join_left(self): eres = self.index eridx = np.array([-1, -1, -1, -1, -1, -1, -1, -1, 9, 7], dtype=np.intp) - self.assertIsInstance(res, RangeIndex) + assert isinstance(res, RangeIndex) tm.assert_index_equal(res, eres) self.assertIsNone(lidx) tm.assert_numpy_array_equal(ridx, eridx) @@ -494,7 +494,7 @@ def test_join_left(self): res, lidx, ridx = self.index.join(other, how='left', return_indexers=True) - self.assertIsInstance(res, RangeIndex) + assert isinstance(res, RangeIndex) tm.assert_index_equal(res, eres) self.assertIsNone(lidx) tm.assert_numpy_array_equal(ridx, eridx) @@ -509,7 +509,7 @@ def test_join_right(self): elidx = np.array([-1, -1, -1, -1, -1, -1, -1, 9, -1, 8, -1], dtype=np.intp) - self.assertIsInstance(other, Int64Index) + assert isinstance(other, Int64Index) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) self.assertIsNone(ridx) @@ -521,7 +521,7 @@ def test_join_right(self): return_indexers=True) eres = other - self.assertIsInstance(other, RangeIndex) + assert isinstance(other, RangeIndex) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) self.assertIsNone(ridx) diff --git a/pandas/tests/indexes/timedeltas/test_ops.py b/pandas/tests/indexes/timedeltas/test_ops.py index 8b5e0e28d4b94..6d8d5f19b98e2 100644 --- a/pandas/tests/indexes/timedeltas/test_ops.py +++ b/pandas/tests/indexes/timedeltas/test_ops.py @@ -352,7 +352,7 @@ def test_subtraction_ops_with_tz(self): def _check(result, expected): self.assertEqual(result, expected) - self.assertIsInstance(result, Timedelta) + assert isinstance(result, Timedelta) # scalars result = ts - ts diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py index 0d219789c5e71..12c9e626ca9e1 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -132,14 +132,14 @@ def test_ufunc_coercions(self): freq='2H', name='x') for result in [idx * 2, np.multiply(idx, 2)]: - tm.assertIsInstance(result, TimedeltaIndex) + assert isinstance(result, TimedeltaIndex) exp = TimedeltaIndex(['4H', '8H', '12H', '16H', '20H'], freq='4H', name='x') tm.assert_index_equal(result, exp) self.assertEqual(result.freq, '4H') for result in [idx / 2, np.divide(idx, 2)]: - tm.assertIsInstance(result, TimedeltaIndex) + assert isinstance(result, TimedeltaIndex) exp = TimedeltaIndex(['1H', '2H', '3H', '4H', '5H'], freq='H', name='x') tm.assert_index_equal(result, exp) @@ -148,7 +148,7 @@ def test_ufunc_coercions(self): idx = TimedeltaIndex(['2H', '4H', '6H', '8H', '10H'], freq='2H', name='x') for result in [-idx, np.negative(idx)]: - tm.assertIsInstance(result, TimedeltaIndex) + assert isinstance(result, TimedeltaIndex) exp = TimedeltaIndex(['-2H', '-4H', '-6H', '-8H', '-10H'], freq='-2H', name='x') tm.assert_index_equal(result, exp) @@ -157,7 +157,7 @@ def test_ufunc_coercions(self): idx = TimedeltaIndex(['-2H', '-1H', '0H', '1H', '2H'], freq='H', name='x') for result in [abs(idx), np.absolute(idx)]: - tm.assertIsInstance(result, TimedeltaIndex) + assert isinstance(result, TimedeltaIndex) exp = TimedeltaIndex(['2H', '1H', '0H', '1H', '2H'], freq=None, name='x') tm.assert_index_equal(result, exp) @@ -205,7 +205,7 @@ def test_take(self): for taken in [taken1, taken2]: tm.assert_index_equal(taken, expected) - tm.assertIsInstance(taken, TimedeltaIndex) + assert isinstance(taken, TimedeltaIndex) self.assertIsNone(taken.freq) self.assertEqual(taken.name, expected.name) @@ -341,7 +341,7 @@ def test_misc_coverage(self): rng = timedelta_range('1 day', periods=5) result = rng.groupby(rng.days) - tm.assertIsInstance(list(result.values())[0][0], Timedelta) + assert isinstance(list(result.values())[0][0], Timedelta) idx = TimedeltaIndex(['3d', '1d', '2d']) self.assertFalse(idx.equals(list(idx))) @@ -468,7 +468,7 @@ def test_append_join_nondatetimeindex(self): idx = Index(['a', 'b', 'c', 'd']) result = rng.append(idx) - tm.assertIsInstance(result[0], Timedelta) + assert isinstance(result[0], Timedelta) # it works rng.join(idx, how='outer') @@ -592,5 +592,5 @@ class TestTimeSeries(tm.TestCase): def test_series_box_timedelta(self): rng = timedelta_range('1 day 1 s', periods=5, freq='h') s = Series(rng) - tm.assertIsInstance(s[1], Timedelta) - tm.assertIsInstance(s.iat[2], Timedelta) + assert isinstance(s[1], Timedelta) + assert isinstance(s.iat[2], Timedelta) diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index 725de7ce20f5c..f2c3a49bc377c 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -353,7 +353,7 @@ def test_chained_getitem_with_lists(self): # 0.12 def check(result, expected): tm.assert_numpy_array_equal(result, expected) - tm.assertIsInstance(result, np.ndarray) + assert isinstance(result, np.ndarray) df = DataFrame({'A': 5 * [np.zeros(3)], 'B': 5 * [np.ones(3)]}) expected = df['A'].iloc[2] diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 20fbaf781d72f..1d471163790d5 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -412,7 +412,7 @@ def test_to_string_unicode_columns(self): buf.getvalue() result = self.frame.to_string() - tm.assertIsInstance(result, compat.text_type) + assert isinstance(result, compat.text_type) def test_to_string_utf8_columns(self): n = u("\u05d0").encode('utf-8') @@ -1129,7 +1129,7 @@ def test_to_string(self): self.assertIsNone(retval) self.assertEqual(buf.getvalue(), s) - tm.assertIsInstance(s, compat.string_types) + assert isinstance(s, compat.string_types) # print in right order result = biggie.to_string(columns=['B', 'A'], col_space=17, diff --git a/pandas/tests/io/formats/test_to_html.py b/pandas/tests/io/formats/test_to_html.py index e90224dcb705a..b2fcfa3fbbaef 100644 --- a/pandas/tests/io/formats/test_to_html.py +++ b/pandas/tests/io/formats/test_to_html.py @@ -1426,7 +1426,7 @@ def test_to_html(self): self.assertIsNone(retval) self.assertEqual(buf.getvalue(), s) - tm.assertIsInstance(s, compat.string_types) + assert isinstance(s, compat.string_types) biggie.to_html(columns=['B', 'A'], col_space=17) biggie.to_html(columns=['B', 'A'], diff --git a/pandas/tests/io/parser/common.py b/pandas/tests/io/parser/common.py index bd50a80b24a47..ca60327d7916c 100644 --- a/pandas/tests/io/parser/common.py +++ b/pandas/tests/io/parser/common.py @@ -105,7 +105,7 @@ def test_squeeze(self): expected = Series([1, 2, 3], name=1, index=idx) result = self.read_table(StringIO(data), sep=',', index_col=0, header=None, squeeze=True) - tm.assertIsInstance(result, Series) + assert isinstance(result, Series) tm.assert_series_equal(result, expected) def test_squeeze_no_view(self): @@ -263,7 +263,7 @@ def test_read_csv_dataframe(self): parse_dates=True) tm.assert_index_equal(df.columns, pd.Index(['A', 'B', 'C', 'D'])) self.assertEqual(df.index.name, 'index') - self.assertIsInstance( + assert isinstance( df.index[0], (datetime, np.datetime64, Timestamp)) self.assertEqual(df.values.dtype, np.float64) tm.assert_frame_equal(df, df2) @@ -274,16 +274,14 @@ def test_read_csv_no_index_name(self): parse_dates=True) tm.assert_index_equal(df.columns, pd.Index(['A', 'B', 'C', 'D', 'E'])) - self.assertIsInstance(df.index[0], - (datetime, np.datetime64, Timestamp)) - self.assertEqual(df.loc[:, ['A', 'B', 'C', 'D']].values.dtype, - np.float64) + assert isinstance(df.index[0], (datetime, np.datetime64, Timestamp)) + assert df.loc[:, ['A', 'B', 'C', 'D']].values.dtype == np.float64 tm.assert_frame_equal(df, df2) def test_read_table_unicode(self): fin = BytesIO(u('\u0141aski, Jan;1').encode('utf-8')) df1 = self.read_table(fin, sep=";", encoding="utf-8", header=None) - tm.assertIsInstance(df1[0].values[0], compat.text_type) + assert isinstance(df1[0].values[0], compat.text_type) def test_read_table_wrong_num_columns(self): # too few! @@ -520,7 +518,7 @@ def test_iterator(self): treader = self.read_table(StringIO(self.data1), sep=',', index_col=0, iterator=True) - tm.assertIsInstance(treader, TextFileReader) + assert isinstance(treader, TextFileReader) # gh-3967: stopping iteration when chunksize is specified data = """A,B,C diff --git a/pandas/tests/io/parser/converters.py b/pandas/tests/io/parser/converters.py index 2659d977ea747..f2b3ce532b59e 100644 --- a/pandas/tests/io/parser/converters.py +++ b/pandas/tests/io/parser/converters.py @@ -39,7 +39,7 @@ def test_converters(self): expected = self.read_csv(StringIO(data)) expected['D'] = expected['D'].map(parse_date) - tm.assertIsInstance(result['D'][0], (datetime, Timestamp)) + assert isinstance(result['D'][0], (datetime, Timestamp)) tm.assert_frame_equal(result, expected) tm.assert_frame_equal(result2, expected) diff --git a/pandas/tests/io/parser/parse_dates.py b/pandas/tests/io/parser/parse_dates.py index b86d85c54f256..a61a1fb39985f 100644 --- a/pandas/tests/io/parser/parse_dates.py +++ b/pandas/tests/io/parser/parse_dates.py @@ -241,7 +241,7 @@ def test_parse_dates_implicit_first_col(self): """ df = self.read_csv(StringIO(data), parse_dates=True) expected = self.read_csv(StringIO(data), index_col=0, parse_dates=True) - self.assertIsInstance( + assert isinstance( df.index[0], (datetime, np.datetime64, Timestamp)) tm.assert_frame_equal(df, expected) @@ -320,13 +320,13 @@ def test_multi_index_parse_dates(self): 20090103,three,c,4,5 """ df = self.read_csv(StringIO(data), index_col=[0, 1], parse_dates=True) - self.assertIsInstance(df.index.levels[0][0], - (datetime, np.datetime64, Timestamp)) + assert isinstance(df.index.levels[0][0], + (datetime, np.datetime64, Timestamp)) # specify columns out of order! df2 = self.read_csv(StringIO(data), index_col=[1, 0], parse_dates=True) - self.assertIsInstance(df2.index.levels[1][0], - (datetime, np.datetime64, Timestamp)) + assert isinstance(df2.index.levels[1][0], + (datetime, np.datetime64, Timestamp)) def test_parse_dates_custom_euroformat(self): text = """foo,bar,baz diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py index 12d5c29cd75e2..cbfffd785ca0d 100644 --- a/pandas/tests/io/test_excel.py +++ b/pandas/tests/io/test_excel.py @@ -2306,12 +2306,12 @@ def test_ExcelWriter_dispatch(self): with ensure_clean('.xlsx') as path: writer = ExcelWriter(path) - tm.assertIsInstance(writer, writer_klass) + assert isinstance(writer, writer_klass) _skip_if_no_xlwt() with ensure_clean('.xls') as path: writer = ExcelWriter(path) - tm.assertIsInstance(writer, _XlwtWriter) + assert isinstance(writer, _XlwtWriter) def test_register_writer(self): # some awkward mocking to test out dispatch and such actually works @@ -2340,7 +2340,7 @@ def check_called(func): with pd.option_context('io.excel.xlsx.writer', 'dummy'): register_writer(DummyClass) writer = ExcelWriter('something.test') - tm.assertIsInstance(writer, DummyClass) + assert isinstance(writer, DummyClass) df = tm.makeCustomDataframe(1, 1) with catch_warnings(record=True): diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index 144431f0b65f9..0d061d516af28 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -158,12 +158,12 @@ def test_spam_with_types(self): def test_spam_no_match(self): dfs = self.read_html(self.spam_data) for df in dfs: - tm.assertIsInstance(df, DataFrame) + assert isinstance(df, DataFrame) def test_banklist_no_match(self): dfs = self.read_html(self.banklist_data, attrs={'id': 'table'}) for df in dfs: - tm.assertIsInstance(df, DataFrame) + assert isinstance(df, DataFrame) def test_spam_header(self): df = self.read_html(self.spam_data, '.*Water.*', header=1)[0] @@ -295,9 +295,9 @@ def test_file_url(self): url = self.banklist_data dfs = self.read_html(file_path_to_url(url), 'First', attrs={'id': 'table'}) - tm.assertIsInstance(dfs, list) + assert isinstance(dfs, list) for df in dfs: - tm.assertIsInstance(df, DataFrame) + assert isinstance(df, DataFrame) @tm.slow def test_invalid_table_attrs(self): @@ -313,34 +313,34 @@ def _bank_data(self, *args, **kwargs): @tm.slow def test_multiindex_header(self): df = self._bank_data(header=[0, 1])[0] - tm.assertIsInstance(df.columns, MultiIndex) + assert isinstance(df.columns, MultiIndex) @tm.slow def test_multiindex_index(self): df = self._bank_data(index_col=[0, 1])[0] - tm.assertIsInstance(df.index, MultiIndex) + assert isinstance(df.index, MultiIndex) @tm.slow def test_multiindex_header_index(self): df = self._bank_data(header=[0, 1], index_col=[0, 1])[0] - tm.assertIsInstance(df.columns, MultiIndex) - tm.assertIsInstance(df.index, MultiIndex) + assert isinstance(df.columns, MultiIndex) + assert isinstance(df.index, MultiIndex) @tm.slow def test_multiindex_header_skiprows_tuples(self): df = self._bank_data(header=[0, 1], skiprows=1, tupleize_cols=True)[0] - tm.assertIsInstance(df.columns, Index) + assert isinstance(df.columns, Index) @tm.slow def test_multiindex_header_skiprows(self): df = self._bank_data(header=[0, 1], skiprows=1)[0] - tm.assertIsInstance(df.columns, MultiIndex) + assert isinstance(df.columns, MultiIndex) @tm.slow def test_multiindex_header_index_skiprows(self): df = self._bank_data(header=[0, 1], index_col=[0, 1], skiprows=1)[0] - tm.assertIsInstance(df.index, MultiIndex) - tm.assertIsInstance(df.columns, MultiIndex) + assert isinstance(df.index, MultiIndex) + assert isinstance(df.columns, MultiIndex) @tm.slow def test_regex_idempotency(self): @@ -348,9 +348,9 @@ def test_regex_idempotency(self): dfs = self.read_html(file_path_to_url(url), match=re.compile(re.compile('Florida')), attrs={'id': 'table'}) - tm.assertIsInstance(dfs, list) + assert isinstance(dfs, list) for df in dfs: - tm.assertIsInstance(df, DataFrame) + assert isinstance(df, DataFrame) def test_negative_skiprows(self): with tm.assertRaisesRegexp(ValueError, @@ -851,8 +851,8 @@ def test_data_fail(self): def test_works_on_valid_markup(self): filename = os.path.join(DATA_PATH, 'valid_markup.html') dfs = self.read_html(filename, index_col=0) - tm.assertIsInstance(dfs, list) - tm.assertIsInstance(dfs[0], DataFrame) + assert isinstance(dfs, list) + assert isinstance(dfs[0], DataFrame) @tm.slow def test_fallback_success(self): diff --git a/pandas/tests/io/test_packers.py b/pandas/tests/io/test_packers.py index 09b951812b674..329748eb5be33 100644 --- a/pandas/tests/io/test_packers.py +++ b/pandas/tests/io/test_packers.py @@ -486,7 +486,7 @@ def test_multi(self): l = [self.frame['float'], self.frame['float'] .A, self.frame['float'].B, None] l_rec = self.encode_decode(l) - self.assertIsInstance(l_rec, tuple) + assert isinstance(l_rec, tuple) check_arbitrary(l, l_rec) def test_iterator(self): diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py index e14c39d1de228..94e4fec07e775 100644 --- a/pandas/tests/io/test_pickle.py +++ b/pandas/tests/io/test_pickle.py @@ -169,7 +169,7 @@ def compare_frame_cat_and_float(result, expected, typ, version): def compare_index_period(result, expected, typ, version): tm.assert_index_equal(result, expected) - tm.assertIsInstance(result.freq, MonthEnd) + assert isinstance(result.freq, MonthEnd) assert result.freq == MonthEnd() assert result.freqstr == 'M' tm.assert_index_equal(result.shift(2), expected.shift(2)) diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index bbeb141baf5df..1287686874a58 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -3876,7 +3876,7 @@ def f(): # valid result = store.select_column('df', 'index') tm.assert_almost_equal(result.values, Series(df.index).values) - self.assertIsInstance(result, Series) + assert isinstance(result, Series) # not a data indexable column self.assertRaises( @@ -3951,7 +3951,7 @@ def test_coordinates(self): result = store.select('df', where=c) expected = df.loc[3:4, :] tm.assert_frame_equal(result, expected) - self.assertIsInstance(c, Index) + assert isinstance(c, Index) # multiple tables _maybe_remove(store, 'df1') @@ -4396,7 +4396,7 @@ def test_pytables_native_read(self): tm.get_data_path('legacy_hdf/pytables_native.h5'), mode='r') as store: d2 = store['detector/readout'] - self.assertIsInstance(d2, DataFrame) + assert isinstance(d2, DataFrame) def test_pytables_native2_read(self): # fails on win/3.5 oddly @@ -4408,7 +4408,7 @@ def test_pytables_native2_read(self): mode='r') as store: str(store) d1 = store['detector'] - self.assertIsInstance(d1, DataFrame) + assert isinstance(d1, DataFrame) def test_legacy_table_read(self): # legacy table types diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 9ddd81ae53062..7ffe054978b9b 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -352,11 +352,11 @@ def test_encoding(self): if compat.PY3: expected = raw.kreis1849[0] self.assertEqual(result, expected) - self.assertIsInstance(result, compat.string_types) + assert isinstance(result, compat.string_types) else: expected = raw.kreis1849.str.decode("latin-1")[0] self.assertEqual(result, expected) - self.assertIsInstance(result, unicode) # noqa + assert isinstance(result, unicode) # noqa with tm.ensure_clean() as path: encoded.to_stata(path, encoding='latin-1', write_index=False) diff --git a/pandas/tests/plotting/common.py b/pandas/tests/plotting/common.py index 3e2021d7a7f45..22f471a01b9d2 100644 --- a/pandas/tests/plotting/common.py +++ b/pandas/tests/plotting/common.py @@ -439,13 +439,13 @@ def _check_box_return_type(self, returned, return_type, expected_keys=None, self.assertTrue(isinstance(returned, types[return_type])) if return_type == 'both': - self.assertIsInstance(returned.ax, Axes) - self.assertIsInstance(returned.lines, dict) + assert isinstance(returned.ax, Axes) + assert isinstance(returned.lines, dict) else: # should be fixed when the returning default is changed if return_type is None: for r in self._flatten_visible(returned): - self.assertIsInstance(r, Axes) + assert isinstance(r, Axes) return self.assertTrue(isinstance(returned, Series)) @@ -460,8 +460,8 @@ def _check_box_return_type(self, returned, return_type, expected_keys=None, elif return_type == 'both': if check_ax_title: self.assertEqual(value.ax.get_title(), key) - self.assertIsInstance(value.ax, Axes) - self.assertIsInstance(value.lines, dict) + assert isinstance(value.ax, Axes) + assert isinstance(value.lines, dict) elif return_type == 'dict': line = value['medians'][0] axes = line.axes if self.mpl_ge_1_5_0 else line.get_axes() diff --git a/pandas/tests/plotting/test_boxplot_method.py b/pandas/tests/plotting/test_boxplot_method.py index db5d1c0356ec1..8755ce419ae20 100644 --- a/pandas/tests/plotting/test_boxplot_method.py +++ b/pandas/tests/plotting/test_boxplot_method.py @@ -228,7 +228,7 @@ def test_grouped_box_return_type(self): # old style: return_type=None result = df.boxplot(by='gender') - self.assertIsInstance(result, np.ndarray) + assert isinstance(result, np.ndarray) self._check_box_return_type( result, None, expected_keys=['height', 'weight', 'category']) diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index d950cc98b4aad..803907c60d0d0 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -507,7 +507,7 @@ def test_gaps(self): self.assertEqual(len(lines), 1) l = lines[0] data = l.get_xydata() - tm.assertIsInstance(data, np.ma.core.MaskedArray) + assert isinstance(data, np.ma.core.MaskedArray) mask = data.mask self.assertTrue(mask[5:25, 1].all()) plt.close(ax.get_figure()) @@ -521,7 +521,7 @@ def test_gaps(self): self.assertEqual(len(lines), 1) l = lines[0] data = l.get_xydata() - tm.assertIsInstance(data, np.ma.core.MaskedArray) + assert isinstance(data, np.ma.core.MaskedArray) mask = data.mask self.assertTrue(mask[2:5, 1].all()) plt.close(ax.get_figure()) @@ -535,7 +535,7 @@ def test_gaps(self): self.assertEqual(len(lines), 1) l = lines[0] data = l.get_xydata() - tm.assertIsInstance(data, np.ma.core.MaskedArray) + assert isinstance(data, np.ma.core.MaskedArray) mask = data.mask self.assertTrue(mask[2:5, 1].all()) @@ -556,7 +556,7 @@ def test_gap_upsample(self): tm._skip_if_mpl_1_5() - tm.assertIsInstance(data, np.ma.core.MaskedArray) + assert isinstance(data, np.ma.core.MaskedArray) mask = data.mask self.assertTrue(mask[5:25, 1].all()) diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index c82065be922c3..448201960b3d1 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -1248,7 +1248,7 @@ def test_boxplot_subplots_return_type(self): # normal style: return_type=None result = df.plot.box(subplots=True) - self.assertIsInstance(result, Series) + assert isinstance(result, Series) self._check_box_return_type(result, None, expected_keys=[ 'height', 'weight', 'category']) diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index 09739653d28ad..75c0efaee85c4 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -272,20 +272,20 @@ def test_concatlike_common_coerce_to_pandas_object(self): res = dti.append(tdi) tm.assert_index_equal(res, exp) - tm.assertIsInstance(res[0], pd.Timestamp) - tm.assertIsInstance(res[-1], pd.Timedelta) + assert isinstance(res[0], pd.Timestamp) + assert isinstance(res[-1], pd.Timedelta) dts = pd.Series(dti) tds = pd.Series(tdi) res = dts.append(tds) tm.assert_series_equal(res, pd.Series(exp, index=[0, 1, 0, 1])) - tm.assertIsInstance(res.iloc[0], pd.Timestamp) - tm.assertIsInstance(res.iloc[-1], pd.Timedelta) + assert isinstance(res.iloc[0], pd.Timestamp) + assert isinstance(res.iloc[-1], pd.Timedelta) res = pd.concat([dts, tds]) tm.assert_series_equal(res, pd.Series(exp, index=[0, 1, 0, 1])) - tm.assertIsInstance(res.iloc[0], pd.Timestamp) - tm.assertIsInstance(res.iloc[-1], pd.Timedelta) + assert isinstance(res.iloc[0], pd.Timestamp) + assert isinstance(res.iloc[-1], pd.Timedelta) def test_concatlike_datetimetz(self): # GH 7795 @@ -1861,7 +1861,7 @@ def test_default_index(self): s1 = pd.Series([1, 2, 3], name='x') s2 = pd.Series([4, 5, 6], name='y') res = pd.concat([s1, s2], axis=1, ignore_index=True) - self.assertIsInstance(res.columns, pd.RangeIndex) + assert isinstance(res.columns, pd.RangeIndex) exp = pd.DataFrame([[1, 4], [2, 5], [3, 6]]) # use check_index_type=True to check the result have # RangeIndex (default index) @@ -1872,7 +1872,7 @@ def test_default_index(self): s1 = pd.Series([1, 2, 3]) s2 = pd.Series([4, 5, 6]) res = pd.concat([s1, s2], axis=1, ignore_index=False) - self.assertIsInstance(res.columns, pd.RangeIndex) + assert isinstance(res.columns, pd.RangeIndex) exp = pd.DataFrame([[1, 4], [2, 5], [3, 6]]) exp.columns = pd.RangeIndex(2) tm.assert_frame_equal(res, exp, check_index_type=True, diff --git a/pandas/tests/reshape/test_merge.py b/pandas/tests/reshape/test_merge.py index 1d2ded5c70042..8aff478bee5fd 100644 --- a/pandas/tests/reshape/test_merge.py +++ b/pandas/tests/reshape/test_merge.py @@ -459,7 +459,7 @@ def _constructor(self): nad = NotADataFrame(self.df) result = nad.merge(self.df2, on='key1') - tm.assertIsInstance(result, NotADataFrame) + assert isinstance(result, NotADataFrame) def test_join_append_timedeltas(self): diff --git a/pandas/tests/reshape/test_merge_ordered.py b/pandas/tests/reshape/test_merge_ordered.py index e4a41ea9a28eb..e445ad9323b51 100644 --- a/pandas/tests/reshape/test_merge_ordered.py +++ b/pandas/tests/reshape/test_merge_ordered.py @@ -69,7 +69,7 @@ def _constructor(self): nad = NotADataFrame(self.left) result = nad.merge(self.right, on='key') - tm.assertIsInstance(result, NotADataFrame) + assert isinstance(result, NotADataFrame) def test_empty_sequence_concat(self): # GH 9157 diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 7d122baa8ae64..0624505ae619b 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -384,7 +384,7 @@ def _check_output(result, values_col, index=['A', 'B'], # no rows rtable = self.data.pivot_table(columns=['AA', 'BB'], margins=True, aggfunc=np.mean) - tm.assertIsInstance(rtable, Series) + assert isinstance(rtable, Series) table = self.data.pivot_table(index=['AA', 'BB'], margins=True, aggfunc='mean') diff --git a/pandas/tests/scalar/test_period.py b/pandas/tests/scalar/test_period.py index 4c6784fb1732b..4978b801c741b 100644 --- a/pandas/tests/scalar/test_period.py +++ b/pandas/tests/scalar/test_period.py @@ -20,7 +20,7 @@ def test_is_leap_year(self): for freq in ['A', 'M', 'D', 'H']: p = Period('2000-01-01 00:00:00', freq=freq) self.assertTrue(p.is_leap_year) - self.assertIsInstance(p.is_leap_year, bool) + assert isinstance(p.is_leap_year, bool) p = Period('1999-01-01 00:00:00', freq=freq) self.assertFalse(p.is_leap_year) @@ -35,17 +35,17 @@ def test_quarterly_negative_ordinals(self): p = Period(ordinal=-1, freq='Q-DEC') self.assertEqual(p.year, 1969) self.assertEqual(p.quarter, 4) - self.assertIsInstance(p, Period) + assert isinstance(p, Period) p = Period(ordinal=-2, freq='Q-DEC') self.assertEqual(p.year, 1969) self.assertEqual(p.quarter, 3) - self.assertIsInstance(p, Period) + assert isinstance(p, Period) p = Period(ordinal=-2, freq='M') self.assertEqual(p.year, 1969) self.assertEqual(p.month, 11) - self.assertIsInstance(p, Period) + assert isinstance(p, Period) def test_period_cons_quarterly(self): # bugs in scikits.timeseries @@ -69,7 +69,7 @@ def test_period_cons_annual(self): stamp = exp.to_timestamp('D', how='end') + timedelta(days=30) p = Period(stamp, freq=freq) self.assertEqual(p, exp + 1) - self.assertIsInstance(p, Period) + assert isinstance(p, Period) def test_period_cons_weekly(self): for num in range(10, 17): @@ -80,13 +80,13 @@ def test_period_cons_weekly(self): result = Period(daystr, freq=freq) expected = Period(daystr, freq='D').asfreq(freq) self.assertEqual(result, expected) - self.assertIsInstance(result, Period) + assert isinstance(result, Period) def test_period_from_ordinal(self): p = pd.Period('2011-01', freq='M') res = pd.Period._from_ordinal(p.ordinal, freq='M') self.assertEqual(p, res) - self.assertIsInstance(res, Period) + assert isinstance(res, Period) def test_period_cons_nat(self): p = Period('NaT', freq='M') @@ -524,8 +524,8 @@ def test_period_deprecated_freq(self): # check supported freq-aliases still works p1 = Period('2016-03-01 09:00', freq=exp) p2 = Period(ordinal=1, freq=exp) - tm.assertIsInstance(p1, Period) - tm.assertIsInstance(p2, Period) + assert isinstance(p1, Period) + assert isinstance(p2, Period) def test_hash(self): self.assertEqual(hash(Period('2011-01', freq='M')), @@ -565,7 +565,7 @@ def test_strftime(self): p = Period('2000-1-1 12:34:12', freq='S') res = p.strftime('%Y-%m-%d %H:%M:%S') self.assertEqual(res, '2000-01-01 12:34:12') - tm.assertIsInstance(res, text_type) # GH3363 + assert isinstance(res, text_type) # GH3363 def test_sub_delta(self): left, right = Period('2011', freq='A'), Period('2007', freq='A') diff --git a/pandas/tests/scalar/test_timedelta.py b/pandas/tests/scalar/test_timedelta.py index 227297709098f..5b81237c7c000 100644 --- a/pandas/tests/scalar/test_timedelta.py +++ b/pandas/tests/scalar/test_timedelta.py @@ -1,4 +1,6 @@ """ test the scalar Timedelta """ +import pytest + import numpy as np from datetime import timedelta @@ -585,27 +587,26 @@ def test_implementation_limits(self): # GH 12727 # timedelta limits correspond to int64 boundaries - self.assertTrue(min_td.value == np.iinfo(np.int64).min + 1) - self.assertTrue(max_td.value == np.iinfo(np.int64).max) + assert min_td.value == np.iinfo(np.int64).min + 1 + assert max_td.value == np.iinfo(np.int64).max # Beyond lower limit, a NAT before the Overflow - self.assertIsInstance(min_td - Timedelta(1, 'ns'), - NaTType) + assert isinstance(min_td - Timedelta(1, 'ns'), NaTType) - with tm.assertRaises(OverflowError): + with pytest.raises(OverflowError): min_td - Timedelta(2, 'ns') - with tm.assertRaises(OverflowError): + with pytest.raises(OverflowError): max_td + Timedelta(1, 'ns') # Same tests using the internal nanosecond values td = Timedelta(min_td.value - 1, 'ns') - self.assertIsInstance(td, NaTType) + assert isinstance(td, NaTType) - with tm.assertRaises(OverflowError): + with pytest.raises(OverflowError): Timedelta(min_td.value - 2, 'ns') - with tm.assertRaises(OverflowError): + with pytest.raises(OverflowError): Timedelta(max_td.value + 1, 'ns') def test_timedelta_arithmetic(self): diff --git a/pandas/tests/scalar/test_timestamp.py b/pandas/tests/scalar/test_timestamp.py index e39375141ad5f..d891032fb1f8e 100644 --- a/pandas/tests/scalar/test_timestamp.py +++ b/pandas/tests/scalar/test_timestamp.py @@ -1087,7 +1087,7 @@ def test_is_leap_year(self): for tz in [None, 'UTC', 'US/Eastern', 'Asia/Tokyo']: dt = Timestamp('2000-01-01 00:00:00', tz=tz) self.assertTrue(dt.is_leap_year) - self.assertIsInstance(dt.is_leap_year, bool) + assert isinstance(dt.is_leap_year, bool) dt = Timestamp('1999-01-01 00:00:00', tz=tz) self.assertFalse(dt.is_leap_year) @@ -1416,13 +1416,13 @@ def test_series_box_timestamp(self): rng = date_range('20090415', '20090519', freq='B') s = Series(rng) - tm.assertIsInstance(s[5], Timestamp) + assert isinstance(s[5], Timestamp) rng = date_range('20090415', '20090519', freq='B') s = Series(rng, index=rng) - tm.assertIsInstance(s[5], Timestamp) + assert isinstance(s[5], Timestamp) - tm.assertIsInstance(s.iat[5], Timestamp) + assert isinstance(s.iat[5], Timestamp) def test_frame_setitem_timestamp(self): # 2155 diff --git a/pandas/tests/series/test_alter_axes.py b/pandas/tests/series/test_alter_axes.py index cec944590c961..5cac86560dba2 100644 --- a/pandas/tests/series/test_alter_axes.py +++ b/pandas/tests/series/test_alter_axes.py @@ -31,7 +31,7 @@ def test_setindex(self): # works series = self.series.copy() series.index = np.arange(len(series)) - tm.assertIsInstance(series.index, Index) + assert isinstance(series.index, Index) def test_rename(self): renamer = lambda x: x.strftime('%Y%m%d') @@ -137,13 +137,13 @@ def test_reset_index(self): rs = s.reset_index(level=[0, 2], drop=True) tm.assert_index_equal(rs.index, Index(index.get_level_values(1))) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) def test_reset_index_range(self): # GH 12071 s = pd.Series(range(2), name='A', dtype='int64') series_result = s.reset_index() - tm.assertIsInstance(series_result.index, RangeIndex) + assert isinstance(series_result.index, RangeIndex) series_expected = pd.DataFrame([[0, 0], [1, 1]], columns=['index', 'A'], index=RangeIndex(stop=2)) diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index 4f6908178583f..666fca2d791fe 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -962,7 +962,7 @@ def test_clip(self): result = self.ts.clip(-0.5, 0.5) expected = np.clip(self.ts, -0.5, 0.5) assert_series_equal(result, expected) - tm.assertIsInstance(expected, Series) + assert isinstance(expected, Series) def test_clip_types_and_nulls(self): @@ -1460,7 +1460,7 @@ def test_reshape_non_2d(self): result = a.reshape(2, 2) expected = a.values.reshape(2, 2) tm.assert_numpy_array_equal(result, expected) - self.assertIsInstance(result, type(expected)) + assert isinstance(result, type(expected)) def test_reshape_2d_return_array(self): x = Series(np.random.random(201), name='x') @@ -1496,7 +1496,7 @@ def test_numpy_reshape(self): result = np.reshape(a, (2, 2)) expected = a.values.reshape(2, 2) tm.assert_numpy_array_equal(result, expected) - self.assertIsInstance(result, type(expected)) + assert isinstance(result, type(expected)) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = np.reshape(a, a.shape) diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index a3e7f9c3fd65f..bc867cc8e0436 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -166,7 +166,7 @@ def test_iter_box(self): s = pd.Series(vals) self.assertEqual(s.dtype, 'datetime64[ns]') for res, exp in zip(s, vals): - self.assertIsInstance(res, pd.Timestamp) + assert isinstance(res, pd.Timestamp) self.assertEqual(res, exp) self.assertIsNone(res.tz) @@ -175,7 +175,7 @@ def test_iter_box(self): s = pd.Series(vals) self.assertEqual(s.dtype, 'datetime64[ns, US/Eastern]') for res, exp in zip(s, vals): - self.assertIsInstance(res, pd.Timestamp) + assert isinstance(res, pd.Timestamp) self.assertEqual(res, exp) self.assertEqual(res.tz, exp.tz) @@ -184,7 +184,7 @@ def test_iter_box(self): s = pd.Series(vals) self.assertEqual(s.dtype, 'timedelta64[ns]') for res, exp in zip(s, vals): - self.assertIsInstance(res, pd.Timedelta) + assert isinstance(res, pd.Timedelta) self.assertEqual(res, exp) # period (object dtype, not boxed) @@ -193,7 +193,7 @@ def test_iter_box(self): s = pd.Series(vals) self.assertEqual(s.dtype, 'object') for res, exp in zip(s, vals): - self.assertIsInstance(res, pd.Period) + assert isinstance(res, pd.Period) self.assertEqual(res, exp) self.assertEqual(res.freq, 'M') diff --git a/pandas/tests/series/test_apply.py b/pandas/tests/series/test_apply.py index 13e30850a1a6f..ac165bd31ef23 100644 --- a/pandas/tests/series/test_apply.py +++ b/pandas/tests/series/test_apply.py @@ -72,7 +72,7 @@ def test_apply_args(self): result = s.apply(str.split, args=(',', )) self.assertEqual(result[0], ['foo', 'bar']) - tm.assertIsInstance(result[0], list) + assert isinstance(result[0], list) def test_apply_box(self): # ufunc will not be boxed. Same test cases as the test_map_box @@ -387,7 +387,7 @@ def test_map_decimal(self): result = self.series.map(lambda x: Decimal(str(x))) self.assertEqual(result.dtype, np.object_) - tm.assertIsInstance(result[0], Decimal) + assert isinstance(result[0], Decimal) def test_map_na_exclusion(self): s = Series([1.5, np.nan, 3, np.nan, 5]) diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index a69bcf03d40ad..151ad1863851b 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -234,7 +234,7 @@ def test_constructor_corner(self): df = tm.makeTimeDataFrame() objs = [df, df] s = Series(objs, index=[0, 1]) - tm.assertIsInstance(s, Series) + assert isinstance(s, Series) def test_constructor_sanitize(self): s = Series(np.array([1., 1., 8.]), dtype='i8') @@ -469,7 +469,7 @@ def test_constructor_with_datetime_tz(self): # export result = s.values - self.assertIsInstance(result, np.ndarray) + assert isinstance(result, np.ndarray) self.assertTrue(result.dtype == 'datetime64[ns]') exp = pd.DatetimeIndex(result) diff --git a/pandas/tests/series/test_datetime_values.py b/pandas/tests/series/test_datetime_values.py index ec64c4ec15bc0..ce82507ce8330 100644 --- a/pandas/tests/series/test_datetime_values.py +++ b/pandas/tests/series/test_datetime_values.py @@ -68,7 +68,7 @@ def compare(s, name): getattr(s.dt, prop) result = s.dt.to_pydatetime() - self.assertIsInstance(result, np.ndarray) + assert isinstance(result, np.ndarray) self.assertTrue(result.dtype == object) result = s.dt.tz_localize('US/Eastern') @@ -138,7 +138,7 @@ def compare(s, name): getattr(s.dt, prop) result = s.dt.to_pydatetime() - self.assertIsInstance(result, np.ndarray) + assert isinstance(result, np.ndarray) self.assertTrue(result.dtype == object) result = s.dt.tz_convert('CET') @@ -169,15 +169,15 @@ def compare(s, name): getattr(s.dt, prop) result = s.dt.components - self.assertIsInstance(result, DataFrame) + assert isinstance(result, DataFrame) tm.assert_index_equal(result.index, s.index) result = s.dt.to_pytimedelta() - self.assertIsInstance(result, np.ndarray) + assert isinstance(result, np.ndarray) self.assertTrue(result.dtype == object) result = s.dt.total_seconds() - self.assertIsInstance(result, pd.Series) + assert isinstance(result, pd.Series) self.assertTrue(result.dtype == 'float64') freq_result = s.dt.freq @@ -369,7 +369,7 @@ def test_dt_accessor_api(self): self.assertIs(Series.dt, CombinedDatetimelikeProperties) s = Series(date_range('2000-01-01', periods=3)) - self.assertIsInstance(s.dt, DatetimeProperties) + assert isinstance(s.dt, DatetimeProperties) for s in [Series(np.arange(5)), Series(list('abcde')), Series(np.random.randn(5))]: diff --git a/pandas/tests/series/test_indexing.py b/pandas/tests/series/test_indexing.py index 855c1d2b795f7..f1b9aaf1b9e46 100644 --- a/pandas/tests/series/test_indexing.py +++ b/pandas/tests/series/test_indexing.py @@ -561,7 +561,7 @@ def test_getitem_setitem_integers(self): def test_getitem_box_float64(self): value = self.ts[5] - tm.assertIsInstance(value, np.float64) + assert isinstance(value, np.float64) def test_getitem_ambiguous_keyerror(self): s = Series(lrange(10), index=lrange(0, 20, 2)) @@ -2275,8 +2275,8 @@ def setUp(self): self.dups = Series(np.random.randn(len(dates)), index=dates) def test_constructor(self): - tm.assertIsInstance(self.dups, Series) - tm.assertIsInstance(self.dups.index, DatetimeIndex) + assert isinstance(self.dups, Series) + assert isinstance(self.dups.index, DatetimeIndex) def test_is_unique_monotonic(self): self.assertFalse(self.dups.index.is_unique) diff --git a/pandas/tests/series/test_io.py b/pandas/tests/series/test_io.py index 42b8e9368a21e..d45a6ba347c3e 100644 --- a/pandas/tests/series/test_io.py +++ b/pandas/tests/series/test_io.py @@ -105,7 +105,7 @@ def test_to_csv_path_is_none(self): # DataFrame.to_csv() which returned string s = Series([1, 2, 3]) csv_str = s.to_csv(path=None) - self.assertIsInstance(csv_str, str) + assert isinstance(csv_str, str) class TestSeriesIO(TestData, tm.TestCase): @@ -184,19 +184,19 @@ def test_tolist_np_int(self): # GH10904 for t in ['int8', 'int16', 'int32', 'int64']: s = pd.Series([1], dtype=t) - self.assertIsInstance(s.tolist()[0], (int, long)) + assert isinstance(s.tolist()[0], (int, long)) def test_tolist_np_uint(self): # GH10904 for t in ['uint8', 'uint16']: s = pd.Series([1], dtype=t) - self.assertIsInstance(s.tolist()[0], int) + assert isinstance(s.tolist()[0], int) for t in ['uint32', 'uint64']: s = pd.Series([1], dtype=t) - self.assertIsInstance(s.tolist()[0], long) + assert isinstance(s.tolist()[0], long) def test_tolist_np_float(self): # GH10904 for t in ['float16', 'float32', 'float64']: s = pd.Series([1], dtype=t) - self.assertIsInstance(s.tolist()[0], float) + assert isinstance(s.tolist()[0], float) diff --git a/pandas/tests/series/test_operators.py b/pandas/tests/series/test_operators.py index 4b50c9d006f4e..ce22b29ee5299 100644 --- a/pandas/tests/series/test_operators.py +++ b/pandas/tests/series/test_operators.py @@ -275,7 +275,7 @@ def test_operators_timedelta64(self): # scalar Timestamp on rhs maxa = df['A'].max() - tm.assertIsInstance(maxa, Timestamp) + assert isinstance(maxa, Timestamp) resultb = df['A'] - df['A'].max() self.assertEqual(resultb.dtype, 'timedelta64[ns]') @@ -562,11 +562,11 @@ def test_timedelta64_conversions(self): # astype s = Series(date_range('20130101', periods=3)) result = s.astype(object) - self.assertIsInstance(result.iloc[0], datetime) + assert isinstance(result.iloc[0], datetime) self.assertTrue(result.dtype == np.object_) result = s1.astype(object) - self.assertIsInstance(result.iloc[0], timedelta) + assert isinstance(result.iloc[0], timedelta) self.assertTrue(result.dtype == np.object_) def test_timedelta64_equal_timedelta_supported_ops(self): diff --git a/pandas/tests/series/test_subclass.py b/pandas/tests/series/test_subclass.py index 3b1b8aca426e1..677bf2ee3e557 100644 --- a/pandas/tests/series/test_subclass.py +++ b/pandas/tests/series/test_subclass.py @@ -13,24 +13,24 @@ def test_indexing_sliced(self): res = s.loc[['a', 'b']] exp = tm.SubclassedSeries([1, 2], index=list('ab')) tm.assert_series_equal(res, exp) - tm.assertIsInstance(res, tm.SubclassedSeries) + assert isinstance(res, tm.SubclassedSeries) res = s.iloc[[2, 3]] exp = tm.SubclassedSeries([3, 4], index=list('cd')) tm.assert_series_equal(res, exp) - tm.assertIsInstance(res, tm.SubclassedSeries) + assert isinstance(res, tm.SubclassedSeries) res = s.loc[['a', 'b']] exp = tm.SubclassedSeries([1, 2], index=list('ab')) tm.assert_series_equal(res, exp) - tm.assertIsInstance(res, tm.SubclassedSeries) + assert isinstance(res, tm.SubclassedSeries) def test_to_frame(self): s = tm.SubclassedSeries([1, 2, 3, 4], index=list('abcd'), name='xxx') res = s.to_frame() exp = tm.SubclassedDataFrame({'xxx': [1, 2, 3, 4]}, index=list('abcd')) tm.assert_frame_equal(res, exp) - tm.assertIsInstance(res, tm.SubclassedDataFrame) + assert isinstance(res, tm.SubclassedDataFrame) class TestSparseSeriesSubclassing(tm.TestCase): diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index da6e16fcea238..78e55420bb3c8 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -392,7 +392,7 @@ def test_timeseries_coercion(self): idx = tm.makeDateIndex(10000) ser = Series(np.random.randn(len(idx)), idx.astype(object)) self.assertTrue(ser.index.is_all_dates) - self.assertIsInstance(ser.index, DatetimeIndex) + assert isinstance(ser.index, DatetimeIndex) def test_empty_series_ops(self): # see issue #13844 @@ -883,8 +883,8 @@ def test_min_max(self): the_min = rng2.min() the_max = rng2.max() - tm.assertIsInstance(the_min, Timestamp) - tm.assertIsInstance(the_max, Timestamp) + assert isinstance(the_min, Timestamp) + assert isinstance(the_max, Timestamp) self.assertEqual(the_min, rng[0]) self.assertEqual(the_max, rng[-1]) diff --git a/pandas/tests/sparse/test_arithmetics.py b/pandas/tests/sparse/test_arithmetics.py index eb926082a7b7c..ae2e152917bbd 100644 --- a/pandas/tests/sparse/test_arithmetics.py +++ b/pandas/tests/sparse/test_arithmetics.py @@ -67,9 +67,9 @@ def _check_numeric_ops(self, a, b, a_dense, b_dense): self._assert((b_dense ** a).to_dense(), b_dense ** a_dense) def _check_bool_result(self, res): - tm.assertIsInstance(res, self._klass) + assert isinstance(res, self._klass) self.assertEqual(res.dtype, np.bool) - self.assertIsInstance(res.fill_value, bool) + assert isinstance(res.fill_value, bool) def _check_comparison_ops(self, a, b, a_dense, b_dense): with np.errstate(invalid='ignore'): diff --git a/pandas/tests/sparse/test_array.py b/pandas/tests/sparse/test_array.py index 2dedcb12d0660..653656fe1e539 100644 --- a/pandas/tests/sparse/test_array.py +++ b/pandas/tests/sparse/test_array.py @@ -521,19 +521,19 @@ def _check_op(op, first, second): res = op(first, second) exp = SparseArray(op(first.values, second.values), fill_value=first.fill_value) - tm.assertIsInstance(res, SparseArray) + assert isinstance(res, SparseArray) assert_almost_equal(res.values, exp.values) res2 = op(first, second.values) - tm.assertIsInstance(res2, SparseArray) + assert isinstance(res2, SparseArray) tm.assert_sp_array_equal(res, res2) res3 = op(first.values, second) - tm.assertIsInstance(res3, SparseArray) + assert isinstance(res3, SparseArray) tm.assert_sp_array_equal(res, res3) res4 = op(first, 4) - tm.assertIsInstance(res4, SparseArray) + assert isinstance(res4, SparseArray) # ignore this if the actual op raises (e.g. pow) try: diff --git a/pandas/tests/sparse/test_combine_concat.py b/pandas/tests/sparse/test_combine_concat.py index 81655daec6164..57b4065744e32 100644 --- a/pandas/tests/sparse/test_combine_concat.py +++ b/pandas/tests/sparse/test_combine_concat.py @@ -69,7 +69,7 @@ def test_concat_axis1_different_fill(self): res = pd.concat([sparse1, sparse2], axis=1) exp = pd.concat([pd.Series(val1, name='x'), pd.Series(val2, name='y')], axis=1) - self.assertIsInstance(res, pd.SparseDataFrame) + assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res.to_dense(), exp) def test_concat_different_kind(self): @@ -234,12 +234,12 @@ def test_concat_different_columns(self): # each columns keeps its fill_value, thus compare in dense res = pd.concat([sparse, sparse3]) exp = pd.concat([self.dense1, self.dense3]) - self.assertIsInstance(res, pd.SparseDataFrame) + assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res.to_dense(), exp) res = pd.concat([sparse3, sparse]) exp = pd.concat([self.dense3, self.dense1]) - self.assertIsInstance(res, pd.SparseDataFrame) + assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res.to_dense(), exp) def test_concat_series(self): @@ -309,12 +309,12 @@ def test_concat_axis1(self): # each columns keeps its fill_value, thus compare in dense res = pd.concat([sparse, sparse3], axis=1) exp = pd.concat([self.dense1, self.dense3], axis=1) - self.assertIsInstance(res, pd.SparseDataFrame) + assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res.to_dense(), exp) res = pd.concat([sparse3, sparse], axis=1) exp = pd.concat([self.dense3, self.dense1], axis=1) - self.assertIsInstance(res, pd.SparseDataFrame) + assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res.to_dense(), exp) def test_concat_sparse_dense(self): @@ -322,32 +322,32 @@ def test_concat_sparse_dense(self): res = pd.concat([sparse, self.dense2]) exp = pd.concat([self.dense1, self.dense2]) - self.assertIsInstance(res, pd.SparseDataFrame) + assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res.to_dense(), exp) res = pd.concat([self.dense2, sparse]) exp = pd.concat([self.dense2, self.dense1]) - self.assertIsInstance(res, pd.SparseDataFrame) + assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res.to_dense(), exp) sparse = self.dense1.to_sparse(fill_value=0) res = pd.concat([sparse, self.dense2]) exp = pd.concat([self.dense1, self.dense2]) - self.assertIsInstance(res, pd.SparseDataFrame) + assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res.to_dense(), exp) res = pd.concat([self.dense2, sparse]) exp = pd.concat([self.dense2, self.dense1]) - self.assertIsInstance(res, pd.SparseDataFrame) + assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res.to_dense(), exp) res = pd.concat([self.dense3, sparse], axis=1) exp = pd.concat([self.dense3, self.dense1], axis=1) - self.assertIsInstance(res, pd.SparseDataFrame) + assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res, exp) res = pd.concat([sparse, self.dense3], axis=1) exp = pd.concat([self.dense1, self.dense3], axis=1) - self.assertIsInstance(res, pd.SparseDataFrame) + assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res, exp) diff --git a/pandas/tests/sparse/test_frame.py b/pandas/tests/sparse/test_frame.py index 52f0f6014dd79..d5df25e82de13 100644 --- a/pandas/tests/sparse/test_frame.py +++ b/pandas/tests/sparse/test_frame.py @@ -86,7 +86,7 @@ def test_as_matrix(self): def test_copy(self): cp = self.frame.copy() - tm.assertIsInstance(cp, SparseDataFrame) + assert isinstance(cp, SparseDataFrame) tm.assert_sp_frame_equal(cp, self.frame) # as of v0.15.0 @@ -95,9 +95,9 @@ def test_copy(self): def test_constructor(self): for col, series in compat.iteritems(self.frame): - tm.assertIsInstance(series, SparseSeries) + assert isinstance(series, SparseSeries) - tm.assertIsInstance(self.iframe['A'].sp_index, IntIndex) + assert isinstance(self.iframe['A'].sp_index, IntIndex) # constructed zframe from matrix above self.assertEqual(self.zframe['A'].fill_value, 0) @@ -110,7 +110,7 @@ def test_constructor(self): # construct no data sdf = SparseDataFrame(columns=np.arange(10), index=np.arange(10)) for col, series in compat.iteritems(sdf): - tm.assertIsInstance(series, SparseSeries) + assert isinstance(series, SparseSeries) # construct from nested dict data = {} @@ -178,9 +178,9 @@ def test_constructor_from_series(self): # GH 2873 x = Series(np.random.randn(10000), name='a') x = x.to_sparse(fill_value=0) - tm.assertIsInstance(x, SparseSeries) + assert isinstance(x, SparseSeries) df = SparseDataFrame(x) - tm.assertIsInstance(df, SparseDataFrame) + assert isinstance(df, SparseDataFrame) x = Series(np.random.randn(10000), name='a') y = Series(np.random.randn(10000), name='b') @@ -289,13 +289,13 @@ def test_dense_to_sparse(self): df = DataFrame({'A': [nan, nan, nan, 1, 2], 'B': [1, 2, nan, nan, nan]}) sdf = df.to_sparse() - tm.assertIsInstance(sdf, SparseDataFrame) + assert isinstance(sdf, SparseDataFrame) self.assertTrue(np.isnan(sdf.default_fill_value)) - tm.assertIsInstance(sdf['A'].sp_index, BlockIndex) + assert isinstance(sdf['A'].sp_index, BlockIndex) tm.assert_frame_equal(sdf.to_dense(), df) sdf = df.to_sparse(kind='integer') - tm.assertIsInstance(sdf['A'].sp_index, IntIndex) + assert isinstance(sdf['A'].sp_index, IntIndex) df = DataFrame({'A': [0, 0, 0, 1, 2], 'B': [1, 2, 0, 0, 0]}, dtype=float) @@ -342,7 +342,7 @@ def _compare_to_dense(a, b, da, db, op): if isinstance(a, DataFrame) and isinstance(db, DataFrame): mixed_result = op(a, db) - tm.assertIsInstance(mixed_result, SparseDataFrame) + assert isinstance(mixed_result, SparseDataFrame) tm.assert_sp_frame_equal(mixed_result, sparse_result, exact_indices=False) @@ -388,7 +388,7 @@ def test_op_corners(self): self.assertTrue(empty.empty) foo = self.frame + self.empty - tm.assertIsInstance(foo.index, DatetimeIndex) + assert isinstance(foo.index, DatetimeIndex) tm.assert_frame_equal(foo, self.frame * np.nan) foo = self.empty + self.frame @@ -474,7 +474,7 @@ def _check_frame(frame, orig): # insert SparseSeries frame['E'] = frame['A'] - tm.assertIsInstance(frame['E'], SparseSeries) + assert isinstance(frame['E'], SparseSeries) tm.assert_sp_series_equal(frame['E'], frame['A'], check_names=False) @@ -488,7 +488,7 @@ def _check_frame(frame, orig): # insert Series frame['F'] = frame['A'].to_dense() - tm.assertIsInstance(frame['F'], SparseSeries) + assert isinstance(frame['F'], SparseSeries) tm.assert_sp_series_equal(frame['F'], frame['A'], check_names=False) @@ -501,7 +501,7 @@ def _check_frame(frame, orig): # insert ndarray frame['H'] = np.random.randn(N) - tm.assertIsInstance(frame['H'], SparseSeries) + assert isinstance(frame['H'], SparseSeries) to_sparsify = np.random.randn(N) to_sparsify[N // 2:] = frame.default_fill_value @@ -580,7 +580,7 @@ def test_append(self): def test_apply(self): applied = self.frame.apply(np.sqrt) - tm.assertIsInstance(applied, SparseDataFrame) + assert isinstance(applied, SparseDataFrame) tm.assert_almost_equal(applied.values, np.sqrt(self.frame.values)) applied = self.fill_frame.apply(np.sqrt) @@ -588,7 +588,7 @@ def test_apply(self): # agg / broadcast broadcasted = self.frame.apply(np.sum, broadcast=True) - tm.assertIsInstance(broadcasted, SparseDataFrame) + assert isinstance(broadcasted, SparseDataFrame) exp = self.frame.to_dense().apply(np.sum, broadcast=True) tm.assert_frame_equal(broadcasted.to_dense(), exp) @@ -609,7 +609,7 @@ def test_apply_nonuq(self): # dtype must be kept self.assertEqual(res.dtype, np.int64) # ToDo: apply must return subclassed dtype - self.assertIsInstance(res, pd.Series) + assert isinstance(res, pd.Series) tm.assert_series_equal(res.to_dense(), exp) # df.T breaks @@ -622,7 +622,7 @@ def test_apply_nonuq(self): def test_applymap(self): # just test that it works result = self.frame.applymap(lambda x: x * 2) - tm.assertIsInstance(result, SparseDataFrame) + assert isinstance(result, SparseDataFrame) def test_astype(self): sparse = pd.SparseDataFrame({'A': SparseArray([1, 2, 3, 4], @@ -1118,7 +1118,7 @@ def test_isnull(self): 'B': [0, np.nan, 0, 2, np.nan]}, default_fill_value=0.) res = df.isnull() - tm.assertIsInstance(res, pd.SparseDataFrame) + assert isinstance(res, pd.SparseDataFrame) exp = pd.DataFrame({'A': [False, False, False, False, True], 'B': [False, True, False, False, True]}) tm.assert_frame_equal(res.to_dense(), exp) @@ -1140,7 +1140,7 @@ def test_isnotnull(self): 'B': [0, np.nan, 0, 2, np.nan]}, default_fill_value=0.) res = df.isnotnull() - tm.assertIsInstance(res, pd.SparseDataFrame) + assert isinstance(res, pd.SparseDataFrame) exp = pd.DataFrame({'A': [True, True, True, True, False], 'B': [True, False, True, True, False]}) tm.assert_frame_equal(res.to_dense(), exp) @@ -1266,11 +1266,11 @@ def test_comparison_op_scalar(self): # comparison changes internal repr, compare with dense res = sparse > 1 - tm.assertIsInstance(res, pd.SparseDataFrame) + assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res.to_dense(), df > 1) res = sparse != 0 - tm.assertIsInstance(res, pd.SparseDataFrame) + assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res.to_dense(), df != 0) diff --git a/pandas/tests/sparse/test_libsparse.py b/pandas/tests/sparse/test_libsparse.py index e5a17d3d117fe..1990e29a4b901 100644 --- a/pandas/tests/sparse/test_libsparse.py +++ b/pandas/tests/sparse/test_libsparse.py @@ -243,27 +243,27 @@ class TestSparseIndexCommon(tm.TestCase): def test_int_internal(self): idx = _make_index(4, np.array([2, 3], dtype=np.int32), kind='integer') - self.assertIsInstance(idx, IntIndex) + assert isinstance(idx, IntIndex) self.assertEqual(idx.npoints, 2) tm.assert_numpy_array_equal(idx.indices, np.array([2, 3], dtype=np.int32)) idx = _make_index(4, np.array([], dtype=np.int32), kind='integer') - self.assertIsInstance(idx, IntIndex) + assert isinstance(idx, IntIndex) self.assertEqual(idx.npoints, 0) tm.assert_numpy_array_equal(idx.indices, np.array([], dtype=np.int32)) idx = _make_index(4, np.array([0, 1, 2, 3], dtype=np.int32), kind='integer') - self.assertIsInstance(idx, IntIndex) + assert isinstance(idx, IntIndex) self.assertEqual(idx.npoints, 4) tm.assert_numpy_array_equal(idx.indices, np.array([0, 1, 2, 3], dtype=np.int32)) def test_block_internal(self): idx = _make_index(4, np.array([2, 3], dtype=np.int32), kind='block') - self.assertIsInstance(idx, BlockIndex) + assert isinstance(idx, BlockIndex) self.assertEqual(idx.npoints, 2) tm.assert_numpy_array_equal(idx.blocs, np.array([2], dtype=np.int32)) @@ -271,7 +271,7 @@ def test_block_internal(self): np.array([2], dtype=np.int32)) idx = _make_index(4, np.array([], dtype=np.int32), kind='block') - self.assertIsInstance(idx, BlockIndex) + assert isinstance(idx, BlockIndex) self.assertEqual(idx.npoints, 0) tm.assert_numpy_array_equal(idx.blocs, np.array([], dtype=np.int32)) @@ -280,7 +280,7 @@ def test_block_internal(self): idx = _make_index(4, np.array([0, 1, 2, 3], dtype=np.int32), kind='block') - self.assertIsInstance(idx, BlockIndex) + assert isinstance(idx, BlockIndex) self.assertEqual(idx.npoints, 4) tm.assert_numpy_array_equal(idx.blocs, np.array([0], dtype=np.int32)) @@ -289,7 +289,7 @@ def test_block_internal(self): idx = _make_index(4, np.array([0, 2, 3], dtype=np.int32), kind='block') - self.assertIsInstance(idx, BlockIndex) + assert isinstance(idx, BlockIndex) self.assertEqual(idx.npoints, 3) tm.assert_numpy_array_equal(idx.blocs, np.array([0, 2], dtype=np.int32)) @@ -391,7 +391,7 @@ class TestBlockIndex(tm.TestCase): def test_block_internal(self): idx = _make_index(4, np.array([2, 3], dtype=np.int32), kind='block') - self.assertIsInstance(idx, BlockIndex) + assert isinstance(idx, BlockIndex) self.assertEqual(idx.npoints, 2) tm.assert_numpy_array_equal(idx.blocs, np.array([2], dtype=np.int32)) @@ -399,7 +399,7 @@ def test_block_internal(self): np.array([2], dtype=np.int32)) idx = _make_index(4, np.array([], dtype=np.int32), kind='block') - self.assertIsInstance(idx, BlockIndex) + assert isinstance(idx, BlockIndex) self.assertEqual(idx.npoints, 0) tm.assert_numpy_array_equal(idx.blocs, np.array([], dtype=np.int32)) @@ -408,7 +408,7 @@ def test_block_internal(self): idx = _make_index(4, np.array([0, 1, 2, 3], dtype=np.int32), kind='block') - self.assertIsInstance(idx, BlockIndex) + assert isinstance(idx, BlockIndex) self.assertEqual(idx.npoints, 4) tm.assert_numpy_array_equal(idx.blocs, np.array([0], dtype=np.int32)) @@ -416,7 +416,7 @@ def test_block_internal(self): np.array([4], dtype=np.int32)) idx = _make_index(4, np.array([0, 2, 3], dtype=np.int32), kind='block') - self.assertIsInstance(idx, BlockIndex) + assert isinstance(idx, BlockIndex) self.assertEqual(idx.npoints, 3) tm.assert_numpy_array_equal(idx.blocs, np.array([0, 2], dtype=np.int32)) @@ -514,20 +514,20 @@ def test_check_integrity(self): def test_int_internal(self): idx = _make_index(4, np.array([2, 3], dtype=np.int32), kind='integer') - self.assertIsInstance(idx, IntIndex) + assert isinstance(idx, IntIndex) self.assertEqual(idx.npoints, 2) tm.assert_numpy_array_equal(idx.indices, np.array([2, 3], dtype=np.int32)) idx = _make_index(4, np.array([], dtype=np.int32), kind='integer') - self.assertIsInstance(idx, IntIndex) + assert isinstance(idx, IntIndex) self.assertEqual(idx.npoints, 0) tm.assert_numpy_array_equal(idx.indices, np.array([], dtype=np.int32)) idx = _make_index(4, np.array([0, 1, 2, 3], dtype=np.int32), kind='integer') - self.assertIsInstance(idx, IntIndex) + assert isinstance(idx, IntIndex) self.assertEqual(idx.npoints, 4) tm.assert_numpy_array_equal(idx.indices, np.array([0, 1, 2, 3], dtype=np.int32)) @@ -546,7 +546,7 @@ def _check_case(xloc, xlen, yloc, ylen, eloc, elen): # see if survive the round trip xbindex = xindex.to_int_index().to_block_index() ybindex = yindex.to_int_index().to_block_index() - tm.assertIsInstance(xbindex, BlockIndex) + assert isinstance(xbindex, BlockIndex) self.assertTrue(xbindex.equals(xindex)) self.assertTrue(ybindex.equals(yindex)) diff --git a/pandas/tests/sparse/test_series.py b/pandas/tests/sparse/test_series.py index 2c3c79c675dcc..8ccc9e1131f60 100644 --- a/pandas/tests/sparse/test_series.py +++ b/pandas/tests/sparse/test_series.py @@ -230,9 +230,9 @@ def test_to_dense_preserve_name(self): def test_constructor(self): # test setup guys self.assertTrue(np.isnan(self.bseries.fill_value)) - tm.assertIsInstance(self.bseries.sp_index, BlockIndex) + assert isinstance(self.bseries.sp_index, BlockIndex) self.assertTrue(np.isnan(self.iseries.fill_value)) - tm.assertIsInstance(self.iseries.sp_index, IntIndex) + assert isinstance(self.iseries.sp_index, IntIndex) self.assertEqual(self.zbseries.fill_value, 0) tm.assert_numpy_array_equal(self.zbseries.values.values, @@ -258,7 +258,7 @@ def _check_const(sparse, name): # Sparse time series works date_index = bdate_range('1/1/2000', periods=len(self.bseries)) s5 = SparseSeries(self.bseries, index=date_index) - tm.assertIsInstance(s5, SparseSeries) + assert isinstance(s5, SparseSeries) # pass Series bseries2 = SparseSeries(self.bseries.to_dense()) @@ -456,13 +456,13 @@ def test_set_value(self): def test_getitem_slice(self): idx = self.bseries.index res = self.bseries[::2] - tm.assertIsInstance(res, SparseSeries) + assert isinstance(res, SparseSeries) expected = self.bseries.reindex(idx[::2]) tm.assert_sp_series_equal(res, expected) res = self.bseries[:5] - tm.assertIsInstance(res, SparseSeries) + assert isinstance(res, SparseSeries) tm.assert_sp_series_equal(res, self.bseries.reindex(idx[:5])) res = self.bseries[5:] @@ -479,7 +479,7 @@ def _compare_with_dense(sp): def _compare(idx): dense_result = dense.take(idx).values sparse_result = sp.take(idx) - self.assertIsInstance(sparse_result, SparseSeries) + assert isinstance(sparse_result, SparseSeries) tm.assert_almost_equal(dense_result, sparse_result.values.values) @@ -1161,7 +1161,7 @@ def test_concat_axis1_different_fill(self): res = pd.concat([sparse1, sparse2], axis=1) exp = pd.concat([pd.Series(val1, name='x'), pd.Series(val2, name='y')], axis=1) - self.assertIsInstance(res, pd.SparseDataFrame) + assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res.to_dense(), exp) def test_concat_different_kind(self): @@ -1280,7 +1280,7 @@ def test_isnull(self): s = pd.SparseSeries([np.nan, 0., 1., 2., 0.], name='xxx', fill_value=0.) res = s.isnull() - tm.assertIsInstance(res, pd.SparseSeries) + assert isinstance(res, pd.SparseSeries) exp = pd.Series([True, False, False, False, False], name='xxx') tm.assert_series_equal(res.to_dense(), exp) @@ -1297,7 +1297,7 @@ def test_isnotnull(self): s = pd.SparseSeries([np.nan, 0., 1., 2., 0.], name='xxx', fill_value=0.) res = s.isnotnull() - tm.assertIsInstance(res, pd.SparseSeries) + assert isinstance(res, pd.SparseSeries) exp = pd.Series([False, True, True, True, True], name='xxx') tm.assert_series_equal(res.to_dense(), exp) diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 27305f51e5129..3b916f0b6792f 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -310,13 +310,13 @@ def test_ints(self): arr = np.random.randint(0, 100, size=50) result = algos.unique(arr) - tm.assertIsInstance(result, np.ndarray) + assert isinstance(result, np.ndarray) def test_objects(self): arr = np.random.randint(0, 100, size=50).astype('O') result = algos.unique(arr) - tm.assertIsInstance(result, np.ndarray) + assert isinstance(result, np.ndarray) def test_object_refcount_bug(self): lst = ['A', 'B', 'C', 'D', 'E'] @@ -588,7 +588,7 @@ def test_value_counts(self): arr = np.random.randn(4) factor = cut(arr, 4) - # tm.assertIsInstance(factor, n) + # assert isinstance(factor, n) result = algos.value_counts(factor) breaks = [-1.194, -0.535, 0.121, 0.777, 1.433] expected_index = pd.IntervalIndex.from_breaks( diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index 27a4f7e8ff003..4b9c27d23273d 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -80,7 +80,7 @@ def test_slicing_maintains_type(self): def check_result(self, result, expected, klass=None): klass = klass or self.klass - self.assertIsInstance(result, klass) + assert isinstance(result, klass) self.assertEqual(result, expected) @@ -432,7 +432,7 @@ def test_value_counts_unique_nunique(self): # datetimetz Series returns array of Timestamp self.assertEqual(result[0], orig[0]) for r in result: - self.assertIsInstance(r, pd.Timestamp) + assert isinstance(r, pd.Timestamp) tm.assert_numpy_array_equal(result, orig._values.asobject.values) else: diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index 9c0a52efe9ba8..65ef841e624e2 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -3193,7 +3193,7 @@ def test_slicing_and_getting_ops(self): # row res_row = df.iloc[2, :] tm.assert_series_equal(res_row, exp_row) - tm.assertIsInstance(res_row["cats"], compat.string_types) + assert isinstance(res_row["cats"], compat.string_types) # col res_col = df.iloc[:, 0] @@ -3213,7 +3213,7 @@ def test_slicing_and_getting_ops(self): # row res_row = df.loc["j", :] tm.assert_series_equal(res_row, exp_row) - tm.assertIsInstance(res_row["cats"], compat.string_types) + assert isinstance(res_row["cats"], compat.string_types) # col res_col = df.loc[:, "cats"] @@ -3234,7 +3234,7 @@ def test_slicing_and_getting_ops(self): # row res_row = df.loc["j", :] tm.assert_series_equal(res_row, exp_row) - tm.assertIsInstance(res_row["cats"], compat.string_types) + assert isinstance(res_row["cats"], compat.string_types) # col res_col = df.loc[:, "cats"] @@ -3268,7 +3268,7 @@ def test_slicing_and_getting_ops(self): # i : int, slice, or sequence of integers res_row = df.iloc[2] tm.assert_series_equal(res_row, exp_row) - tm.assertIsInstance(res_row["cats"], compat.string_types) + assert isinstance(res_row["cats"], compat.string_types) res_df = df.iloc[slice(2, 4)] tm.assert_frame_equal(res_df, exp_df) @@ -4220,7 +4220,7 @@ def test_cat_accessor_api(self): from pandas.core.categorical import CategoricalAccessor self.assertIs(Series.cat, CategoricalAccessor) s = Series(list('aabbcde')).astype('category') - self.assertIsInstance(s.cat, CategoricalAccessor) + assert isinstance(s.cat, CategoricalAccessor) invalid = Series([1]) with tm.assertRaisesRegexp(AttributeError, "only use .cat accessor"): @@ -4240,7 +4240,7 @@ def test_str_accessor_api_for_categorical(self): s = Series(list('aabb')) s = s + " " + s c = s.astype('category') - self.assertIsInstance(c.str, StringMethods) + assert isinstance(c.str, StringMethods) # str functions, which need special arguments special_func_defs = [ @@ -4331,7 +4331,7 @@ def test_dt_accessor_api_for_categorical(self): ("Period", get_ops(PeriodIndex), s_pr, c_pr), ("Timedelta", get_ops(TimedeltaIndex), s_tdr, c_tdr)] - self.assertIsInstance(c_dr.dt, Properties) + assert isinstance(c_dr.dt, Properties) special_func_defs = [ ('strftime', ("%Y-%m-%d",), {}), @@ -4414,18 +4414,18 @@ class TestCategoricalSubclassing(tm.TestCase): def test_constructor(self): sc = tm.SubclassedCategorical(['a', 'b', 'c']) - self.assertIsInstance(sc, tm.SubclassedCategorical) + assert isinstance(sc, tm.SubclassedCategorical) tm.assert_categorical_equal(sc, Categorical(['a', 'b', 'c'])) def test_from_array(self): sc = tm.SubclassedCategorical.from_codes([1, 0, 2], ['a', 'b', 'c']) - self.assertIsInstance(sc, tm.SubclassedCategorical) + assert isinstance(sc, tm.SubclassedCategorical) exp = Categorical.from_codes([1, 0, 2], ['a', 'b', 'c']) tm.assert_categorical_equal(sc, exp) def test_map(self): sc = tm.SubclassedCategorical(['a', 'b', 'c']) res = sc.map(lambda x: x.upper()) - self.assertIsInstance(res, tm.SubclassedCategorical) + assert isinstance(res, tm.SubclassedCategorical) exp = Categorical(['A', 'B', 'C']) tm.assert_categorical_equal(res, exp) diff --git a/pandas/tests/test_join.py b/pandas/tests/test_join.py index 6723494d1529b..e9e7ffba7fe54 100644 --- a/pandas/tests/test_join.py +++ b/pandas/tests/test_join.py @@ -23,9 +23,9 @@ def test_outer_join_indexer(self): empty = np.array([], dtype=dtype) result, lindexer, rindexer = indexer(left, right) - tm.assertIsInstance(result, np.ndarray) - tm.assertIsInstance(lindexer, np.ndarray) - tm.assertIsInstance(rindexer, np.ndarray) + assert isinstance(result, np.ndarray) + assert isinstance(lindexer, np.ndarray) + assert isinstance(rindexer, np.ndarray) tm.assert_numpy_array_equal(result, np.arange(5, dtype=dtype)) exp = np.array([0, 1, 2, -1, -1], dtype=np.int64) tm.assert_numpy_array_equal(lindexer, exp) diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index 75e2c2162c781..d56366ca8a545 100755 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -114,7 +114,7 @@ def test_dataframe_constructor(self): multi = DataFrame(np.random.randn(4, 4), index=[np.array(['a', 'a', 'b', 'b']), np.array(['x', 'y', 'x', 'y'])]) - tm.assertIsInstance(multi.index, MultiIndex) + assert isinstance(multi.index, MultiIndex) assert not isinstance(multi.columns, MultiIndex) multi = DataFrame(np.random.randn(4, 4), @@ -661,7 +661,7 @@ def test_setitem_change_dtype(self): s = dft['foo', 'two'] dft['foo', 'two'] = s > s.median() tm.assert_series_equal(dft['foo', 'two'], s > s.median()) - # tm.assertIsInstance(dft._data.blocks[1].items, MultiIndex) + # assert isinstance(dft._data.blocks[1].items, MultiIndex) reindexed = dft.reindex(columns=[('foo', 'two')]) tm.assert_series_equal(reindexed['foo', 'two'], s > s.median()) @@ -728,12 +728,12 @@ def test_reset_index_with_drop(self): self.assertEqual(len(deleveled.columns), len(self.ymd.columns)) deleveled = self.series.reset_index() - tm.assertIsInstance(deleveled, DataFrame) + assert isinstance(deleveled, DataFrame) self.assertEqual(len(deleveled.columns), len(self.series.index.levels) + 1) deleveled = self.series.reset_index(drop=True) - tm.assertIsInstance(deleveled, Series) + assert isinstance(deleveled, Series) def test_count_level(self): def _check_counts(frame, axis=0): @@ -1285,7 +1285,7 @@ def test_reorder_levels(self): def test_insert_index(self): df = self.ymd[:5].T df[2000, 1, 10] = df[2000, 1, 7] - tm.assertIsInstance(df.columns, MultiIndex) + assert isinstance(df.columns, MultiIndex) self.assertTrue((df[2000, 1, 10] == df[2000, 1, 7]).all()) def test_alignment(self): @@ -1918,7 +1918,7 @@ def test_indexing_ambiguity_bug_1678(self): result = frame.iloc[:, 1] exp = frame.loc[:, ('Ohio', 'Red')] - tm.assertIsInstance(result, Series) + assert isinstance(result, Series) tm.assert_series_equal(result, exp) def test_nonunique_assignment_1750(self): @@ -2073,8 +2073,8 @@ def test_datetimeindex(self): for d1, d2 in itertools.product( [date1, date2, date3], [date1, date2, date3]): index = pd.MultiIndex.from_product([[d1], [d2]]) - self.assertIsInstance(index.levels[0], pd.DatetimeIndex) - self.assertIsInstance(index.levels[1], pd.DatetimeIndex) + assert isinstance(index.levels[0], pd.DatetimeIndex) + assert isinstance(index.levels[1], pd.DatetimeIndex) def test_constructor_with_tz(self): diff --git a/pandas/tests/test_resample.py b/pandas/tests/test_resample.py index de240114aa60a..2a8696af36268 100644 --- a/pandas/tests/test_resample.py +++ b/pandas/tests/test_resample.py @@ -70,12 +70,12 @@ def test_api(self): r = self.series.resample('H') result = r.mean() - self.assertIsInstance(result, Series) + assert isinstance(result, Series) self.assertEqual(len(result), 217) r = self.series.to_frame().resample('H') result = r.mean() - self.assertIsInstance(result, DataFrame) + assert isinstance(result, DataFrame) self.assertEqual(len(result), 217) def test_api_changes_v018(self): @@ -84,7 +84,7 @@ def test_api_changes_v018(self): # to .resample(......).how() r = self.series.resample('H') - self.assertIsInstance(r, DatetimeIndexResampler) + assert isinstance(r, DatetimeIndexResampler) for how in ['sum', 'mean', 'prod', 'min', 'max', 'var', 'std']: with tm.assert_produces_warning(FutureWarning, @@ -146,7 +146,7 @@ def f(): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - self.assertIsInstance(getattr(r, op)(2), pd.Series) + assert isinstance(getattr(r, op)(2), pd.Series) # unary numeric ops for op in ['__pos__', '__neg__', '__abs__', '__inv__']: @@ -157,7 +157,7 @@ def f(): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - self.assertIsInstance(getattr(r, op)(), pd.Series) + assert isinstance(getattr(r, op)(), pd.Series) # comparison ops for op in ['__lt__', '__le__', '__gt__', '__ge__', '__eq__', '__ne__']: @@ -165,7 +165,7 @@ def f(): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - self.assertIsInstance(getattr(r, op)(2), pd.Series) + assert isinstance(getattr(r, op)(2), pd.Series) # IPython introspection shouldn't trigger warning GH 13618 for op in ['_repr_json', '_repr_latex', @@ -1344,10 +1344,10 @@ def test_resample_ohlc_result(self): s = Series(range(len(index)), index=index) a = s.loc[:'4-15-2000'].resample('30T').ohlc() - self.assertIsInstance(a, DataFrame) + assert isinstance(a, DataFrame) b = s.loc[:'4-14-2000'].resample('30T').ohlc() - self.assertIsInstance(b, DataFrame) + assert isinstance(b, DataFrame) # GH12348 # raising on odd period @@ -1412,7 +1412,7 @@ def test_resample_reresample(self): bs = s.resample('B', closed='right', label='right').mean() result = bs.resample('8H').mean() self.assertEqual(len(result), 22) - tm.assertIsInstance(result.index.freq, offsets.DateOffset) + assert isinstance(result.index.freq, offsets.DateOffset) self.assertEqual(result.index.freq, offsets.Hour(8)) def test_resample_timestamp_to_period(self): @@ -1811,7 +1811,7 @@ def test_upsample_apply_functions(self): ts = Series(np.random.randn(len(rng)), index=rng) result = ts.resample('20min').aggregate(['mean', 'sum']) - tm.assertIsInstance(result, DataFrame) + assert isinstance(result, DataFrame) def test_resample_not_monotonic(self): rng = pd.date_range('2012-06-12', periods=200, freq='h') diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index a4c64482629ba..1aa69ce6b231e 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -24,7 +24,7 @@ def test_api(self): # GH 6106, GH 9322 self.assertIs(Series.str, strings.StringMethods) - self.assertIsInstance(Series(['']).str, strings.StringMethods) + assert isinstance(Series(['']).str, strings.StringMethods) # GH 9184 invalid = Series([1]) @@ -39,7 +39,7 @@ def test_iter(self): for s in ds.str: # iter must yield a Series - tm.assertIsInstance(s, Series) + assert isinstance(s, Series) # indices of each yielded Series should be equal to the index of # the original Series @@ -134,7 +134,7 @@ def test_count(self): result = Series(values).str.count('f[o]+') exp = Series([1, 2, NA, 4]) - tm.assertIsInstance(result, Series) + assert isinstance(result, Series) tm.assert_series_equal(result, exp) # mixed @@ -145,7 +145,7 @@ def test_count(self): rs = Series(mixed).str.count('a') xp = Series([1, NA, 0, NA, NA, 0, NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_series_equal(rs, xp) # unicode @@ -157,7 +157,7 @@ def test_count(self): result = Series(values).str.count('f[o]+') exp = Series([1, 2, NA, 4]) - tm.assertIsInstance(result, Series) + assert isinstance(result, Series) tm.assert_series_equal(result, exp) def test_contains(self): @@ -199,7 +199,7 @@ def test_contains(self): rs = Series(mixed).str.contains('o') xp = Series([False, NA, False, NA, NA, True, NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_series_equal(rs, xp) # unicode @@ -243,7 +243,7 @@ def test_startswith(self): tm.assert_numpy_array_equal(rs, xp) rs = Series(mixed).str.startswith('f') - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) xp = Series([False, NA, False, NA, NA, True, NA, NA, NA]) tm.assert_series_equal(rs, xp) @@ -274,7 +274,7 @@ def test_endswith(self): rs = Series(mixed).str.endswith('f') xp = Series([False, NA, False, NA, NA, False, NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_series_equal(rs, xp) # unicode @@ -326,7 +326,7 @@ def test_lower_upper(self): mixed = mixed.str.upper() rs = Series(mixed).str.lower() xp = Series(['a', NA, 'b', NA, NA, 'foo', NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_series_equal(rs, xp) # unicode @@ -405,7 +405,7 @@ def test_replace(self): rs = Series(mixed).str.replace('BAD[_]*', '') xp = Series(['a', NA, 'b', NA, NA, 'foo', NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) # unicode @@ -485,7 +485,7 @@ def test_replace_compiled_regex(self): rs = Series(mixed).str.replace(pat, '') xp = Series(['a', NA, 'b', NA, NA, 'foo', NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) # unicode @@ -545,7 +545,7 @@ def test_repeat(self): rs = Series(mixed).str.repeat(3) xp = Series(['aaa', NA, 'bbb', NA, NA, 'foofoofoo', NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_series_equal(rs, xp) # unicode @@ -591,7 +591,7 @@ def test_match(self): 'foo', None, 1, 2.]) rs = Series(mixed).str.match('.*(BAD[_]+).*(BAD)') xp = Series([True, NA, True, NA, NA, False, NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_series_equal(rs, xp) # unicode @@ -809,7 +809,7 @@ def test_extract_expand_True(self): # single group renames series/index properly s_or_idx = klass(['A1', 'A2']) result_df = s_or_idx.str.extract(r'(?PA)\d', expand=True) - tm.assertIsInstance(result_df, DataFrame) + assert isinstance(result_df, DataFrame) result_series = result_df['uno'] assert_series_equal(result_series, Series(['A', 'A'], name='uno')) @@ -1410,7 +1410,7 @@ def test_join(self): rs = Series(mixed).str.split('_').str.join('_') xp = Series(['a_b', NA, 'asdf_cas_asdf', NA, NA, 'foo', NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) # unicode @@ -1432,7 +1432,7 @@ def test_len(self): rs = Series(mixed).str.len() xp = Series([3, NA, 13, NA, NA, 3, NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) # unicode @@ -1457,7 +1457,7 @@ def test_findall(self): rs = Series(mixed).str.findall('BAD[_]*') xp = Series([['BAD__', 'BAD'], NA, [], NA, NA, ['BAD'], NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) # unicode @@ -1616,7 +1616,7 @@ def test_pad(self): rs = Series(mixed).str.pad(5, side='left') xp = Series([' a', NA, ' b', NA, NA, ' ee', NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) mixed = Series(['a', NA, 'b', True, datetime.today(), 'ee', None, 1, 2. @@ -1625,7 +1625,7 @@ def test_pad(self): rs = Series(mixed).str.pad(5, side='right') xp = Series(['a ', NA, 'b ', NA, NA, 'ee ', NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) mixed = Series(['a', NA, 'b', True, datetime.today(), 'ee', None, 1, 2. @@ -1634,7 +1634,7 @@ def test_pad(self): rs = Series(mixed).str.pad(5, side='both') xp = Series([' a ', NA, ' b ', NA, NA, ' ee ', NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) # unicode @@ -1746,19 +1746,19 @@ def test_center_ljust_rjust(self): rs = Series(mixed).str.center(5) xp = Series([' a ', NA, ' b ', NA, NA, ' c ', ' eee ', NA, NA, NA ]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) rs = Series(mixed).str.ljust(5) xp = Series(['a ', NA, 'b ', NA, NA, 'c ', 'eee ', NA, NA, NA ]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) rs = Series(mixed).str.rjust(5) xp = Series([' a', NA, ' b', NA, NA, ' c', ' eee', NA, NA, NA ]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) # unicode @@ -1870,11 +1870,11 @@ def test_split(self): result = mixed.str.split('_') exp = Series([['a', 'b', 'c'], NA, ['d', 'e', 'f'], NA, NA, NA, NA, NA ]) - tm.assertIsInstance(result, Series) + assert isinstance(result, Series) tm.assert_almost_equal(result, exp) result = mixed.str.split('_', expand=False) - tm.assertIsInstance(result, Series) + assert isinstance(result, Series) tm.assert_almost_equal(result, exp) # unicode @@ -1915,11 +1915,11 @@ def test_rsplit(self): result = mixed.str.rsplit('_') exp = Series([['a', 'b', 'c'], NA, ['d', 'e', 'f'], NA, NA, NA, NA, NA ]) - tm.assertIsInstance(result, Series) + assert isinstance(result, Series) tm.assert_almost_equal(result, exp) result = mixed.str.rsplit('_', expand=False) - tm.assertIsInstance(result, Series) + assert isinstance(result, Series) tm.assert_almost_equal(result, exp) # unicode @@ -2293,7 +2293,7 @@ def test_slice(self): rs = Series(mixed).str.slice(2, 5) xp = Series(['foo', NA, 'bar', NA, NA, NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) rs = Series(mixed).str.slice(2, 5, -1) @@ -2371,19 +2371,19 @@ def test_strip_lstrip_rstrip_mixed(self): rs = Series(mixed).str.strip() xp = Series(['aa', NA, 'bb', NA, NA, NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) rs = Series(mixed).str.lstrip() xp = Series(['aa ', NA, 'bb \t\n', NA, NA, NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) rs = Series(mixed).str.rstrip() xp = Series([' aa', NA, ' bb', NA, NA, NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) def test_strip_lstrip_rstrip_unicode(self): @@ -2472,7 +2472,7 @@ def test_get(self): rs = Series(mixed).str.split('_').str.get(1) xp = Series(['b', NA, 'd', NA, NA, NA, NA, NA]) - tm.assertIsInstance(rs, Series) + assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) # unicode diff --git a/pandas/tests/test_testing.py b/pandas/tests/test_testing.py index 7b3b9d4e3049f..fc9a828c18f0e 100644 --- a/pandas/tests/test_testing.py +++ b/pandas/tests/test_testing.py @@ -681,15 +681,6 @@ def test_frame_equal_message(self): by_blocks=True) -class TestIsInstance(tm.TestCase): - - def test_isinstance(self): - - expected = "Expected type " - with assertRaisesRegexp(AssertionError, expected): - tm.assertIsInstance(1, pd.Series) - - class TestAssertCategoricalEqual(unittest.TestCase): def test_categorical_equal_message(self): diff --git a/pandas/tests/test_window.py b/pandas/tests/test_window.py index 87220a7a1cc2f..98724fe665e58 100644 --- a/pandas/tests/test_window.py +++ b/pandas/tests/test_window.py @@ -1380,7 +1380,7 @@ def get_result(obj, window, min_periods=None, freq=None, center=False): series_result = get_result(self.series, window=50) frame_result = get_result(self.frame, window=50) - tm.assertIsInstance(series_result, Series) + assert isinstance(series_result, Series) self.assertEqual(type(frame_result), DataFrame) # check time_rule works @@ -1692,7 +1692,7 @@ def _check_ew_ndarray(self, func, preserve_nan=False, name=None): def _check_ew_structures(self, func, name): series_result = getattr(self.series.ewm(com=10), name)() - tm.assertIsInstance(series_result, Series) + assert isinstance(series_result, Series) frame_result = getattr(self.frame.ewm(com=10), name)() self.assertEqual(type(frame_result), DataFrame) @@ -2908,7 +2908,7 @@ def _check_expanding_ndarray(self, func, static_comp, has_min_periods=True, def _check_expanding_structures(self, func): series_result = func(self.series) - tm.assertIsInstance(series_result, Series) + assert isinstance(series_result, Series) frame_result = func(self.frame) self.assertEqual(type(frame_result), DataFrame) diff --git a/pandas/tests/tseries/test_offsets.py b/pandas/tests/tseries/test_offsets.py index 9dd398f055a67..64f978124f8e7 100644 --- a/pandas/tests/tseries/test_offsets.py +++ b/pandas/tests/tseries/test_offsets.py @@ -84,7 +84,7 @@ def test_normalize_date(): def test_to_m8(): valb = datetime(2007, 10, 1) valu = _to_m8(valb) - tm.assertIsInstance(valu, np.datetime64) + assert isinstance(valu, np.datetime64) # assert valu == np.datetime64(datetime(2007,10,1)) # def test_datetime64_box(): @@ -146,7 +146,7 @@ def test_apply_out_of_range(self): offset = self._get_offset(self._offset, value=10000) result = Timestamp('20080101') + offset - self.assertIsInstance(result, datetime) + assert isinstance(result, datetime) self.assertIsNone(result.tzinfo) tm._skip_if_no_pytz() @@ -155,7 +155,7 @@ def test_apply_out_of_range(self): for tz in self.timezones: t = Timestamp('20080101', tz=tz) result = t + offset - self.assertIsInstance(result, datetime) + assert isinstance(result, datetime) self.assertEqual(t.tzinfo, result.tzinfo) except (tslib.OutOfBoundsDatetime): @@ -219,7 +219,7 @@ def test_return_type(self): # make sure that we are returning a Timestamp result = Timestamp('20080101') + offset - self.assertIsInstance(result, Timestamp) + assert isinstance(result, Timestamp) # make sure that we are returning NaT self.assertTrue(NaT + offset is NaT) diff --git a/pandas/tests/tseries/test_timezones.py b/pandas/tests/tseries/test_timezones.py index 0b68a5165983d..f99ef2898d0f9 100644 --- a/pandas/tests/tseries/test_timezones.py +++ b/pandas/tests/tseries/test_timezones.py @@ -279,7 +279,7 @@ def test_astimezone(self): expected = utc.tz_convert(self.tzstr('US/Eastern')) result = utc.astimezone(self.tzstr('US/Eastern')) self.assertEqual(expected, result) - tm.assertIsInstance(result, Timestamp) + assert isinstance(result, Timestamp) def test_create_with_tz(self): stamp = Timestamp('3/11/2012 05:00', tz=self.tzstr('US/Eastern')) @@ -1397,11 +1397,11 @@ def test_join_utc_convert(self): for how in ['inner', 'outer', 'left', 'right']: result = left.join(left[:-5], how=how) - tm.assertIsInstance(result, DatetimeIndex) + assert isinstance(result, DatetimeIndex) self.assertEqual(result.tz, left.tz) result = left.join(right[:-5], how=how) - tm.assertIsInstance(result, DatetimeIndex) + assert isinstance(result, DatetimeIndex) self.assertEqual(result.tz.zone, 'UTC') def test_join_aware(self): diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 025068f9bcc67..c54def2b4ef5e 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -191,11 +191,35 @@ def assert_almost_equal(left, right, check_exact=False, **kwargs) -def assert_dict_equal(left, right, compare_keys=True): +def _check_isinstance(left, right, cls): + """ + Helper method for our assert_* methods that ensures that + the two objects being compared have the right type before + proceeding with the comparison. + + Parameters + ---------- + left : The first object being compared. + right : The second object being compared. + cls : The class type to check against. + + Raises + ------ + AssertionError : Either `left` or `right` is not an instance of `cls`. + """ - assertIsInstance(left, dict, '[dict] ') - assertIsInstance(right, dict, '[dict] ') + err_msg = "{0} Expected type {1}, found {2} instead" + cls_name = cls.__name__ + if not isinstance(left, cls): + raise AssertionError(err_msg.format(cls_name, cls, type(left))) + if not isinstance(right, cls): + raise AssertionError(err_msg.format(cls_name, cls, type(right))) + + +def assert_dict_equal(left, right, compare_keys=True): + + _check_isinstance(left, right, dict) return libtesting.assert_dict_equal(left, right, compare_keys=compare_keys) @@ -883,8 +907,7 @@ def _get_ilevel_values(index, level): return values # instance validation - assertIsInstance(left, Index, '[index] ') - assertIsInstance(right, Index, '[index] ') + _check_isinstance(left, right, Index) # class / dtype comparison _check_types(left, right, obj=obj) @@ -1060,18 +1083,9 @@ def assertIsNone(expr, msg=''): return assertIs(expr, None, msg) -def assertIsInstance(obj, cls, msg=''): - """Test that obj is an instance of cls - (which can be a class or a tuple of classes, - as supported by isinstance()).""" - if not isinstance(obj, cls): - err_msg = "{0}Expected type {1}, found {2} instead" - raise AssertionError(err_msg.format(msg, cls, type(obj))) - - def assert_categorical_equal(left, right, check_dtype=True, obj='Categorical', check_category_order=True): - """Test that categoricals are eqivalent + """Test that Categoricals are equivalent. Parameters ---------- @@ -1088,8 +1102,7 @@ def assert_categorical_equal(left, right, check_dtype=True, values are compared. The ordered attribute is checked regardless. """ - assertIsInstance(left, pd.Categorical, '[Categorical] ') - assertIsInstance(right, pd.Categorical, '[Categorical] ') + _check_isinstance(left, right, Categorical) if check_category_order: assert_index_equal(left.categories, right.categories, @@ -1149,11 +1162,10 @@ def assert_numpy_array_equal(left, right, strict_nan=False, """ # instance validation - # to show a detailed erorr message when classes are different + # Show a detailed error message when classes are different assert_class_equal(left, right, obj=obj) # both classes must be an np.ndarray - assertIsInstance(left, np.ndarray, '[ndarray] ') - assertIsInstance(right, np.ndarray, '[ndarray] ') + _check_isinstance(left, right, np.ndarray) def _get_base(obj): return obj.base if getattr(obj, 'base', None) is not None else obj @@ -1241,13 +1253,12 @@ def assert_series_equal(left, right, check_dtype=True, """ # instance validation - assertIsInstance(left, Series, '[Series] ') - assertIsInstance(right, Series, '[Series] ') + _check_isinstance(left, right, Series) if check_series_type: # ToDo: There are some tests using rhs is sparse # lhs is dense. Should use assert_class_equal in future - assertIsInstance(left, type(right)) + assert isinstance(left, type(right)) # assert_class_equal(left, right, obj=obj) # length comparison @@ -1362,13 +1373,12 @@ def assert_frame_equal(left, right, check_dtype=True, """ # instance validation - assertIsInstance(left, DataFrame, '[DataFrame] ') - assertIsInstance(right, DataFrame, '[DataFrame] ') + _check_isinstance(left, right, DataFrame) if check_frame_type: # ToDo: There are some tests using rhs is SparseDataFrame # lhs is DataFrame. Should use assert_class_equal in future - assertIsInstance(left, type(right)) + assert isinstance(left, type(right)) # assert_class_equal(left, right, obj=obj) # shape comparison @@ -1507,17 +1517,14 @@ def assert_sp_array_equal(left, right, check_dtype=True): Whether to check the data dtype is identical. """ - assertIsInstance(left, pd.SparseArray, '[SparseArray]') - assertIsInstance(right, pd.SparseArray, '[SparseArray]') + _check_isinstance(left, right, pd.SparseArray) assert_numpy_array_equal(left.sp_values, right.sp_values, check_dtype=check_dtype) # SparseIndex comparison - assertIsInstance( - left.sp_index, pd.core.sparse.libsparse.SparseIndex, '[SparseIndex]') - assertIsInstance( - right.sp_index, pd.core.sparse.libsparse.SparseIndex, '[SparseIndex]') + assert isinstance(left.sp_index, pd.core.sparse.libsparse.SparseIndex) + assert isinstance(right.sp_index, pd.core.sparse.libsparse.SparseIndex) if not left.sp_index.equals(right.sp_index): raise_assert_detail('SparseArray.index', 'index are not equal', @@ -1550,8 +1557,7 @@ def assert_sp_series_equal(left, right, check_dtype=True, exact_indices=True, Specify the object name being compared, internally used to show the appropriate assertion message. """ - assertIsInstance(left, pd.SparseSeries, '[SparseSeries]') - assertIsInstance(right, pd.SparseSeries, '[SparseSeries]') + _check_isinstance(left, right, pd.SparseSeries) if check_series_type: assert_class_equal(left, right, obj=obj) @@ -1588,8 +1594,7 @@ def assert_sp_frame_equal(left, right, check_dtype=True, exact_indices=True, Specify the object name being compared, internally used to show the appropriate assertion message. """ - assertIsInstance(left, pd.SparseDataFrame, '[SparseDataFrame]') - assertIsInstance(right, pd.SparseDataFrame, '[SparseDataFrame]') + _check_isinstance(left, right, pd.SparseDataFrame) if check_frame_type: assert_class_equal(left, right, obj=obj) @@ -1620,8 +1625,8 @@ def assert_sp_frame_equal(left, right, check_dtype=True, exact_indices=True, def assert_sp_list_equal(left, right): - assertIsInstance(left, pd.SparseList, '[SparseList]') - assertIsInstance(right, pd.SparseList, '[SparseList]') + assert isinstance(left, pd.SparseList) + assert isinstance(right, pd.SparseList) assert_sp_array_equal(left.to_array(), right.to_array())