diff --git a/pandas/tests/api/test_types.py b/pandas/tests/api/test_types.py index 3468a4db617b0..9a7e42cb9c4e2 100644 --- a/pandas/tests/api/test_types.py +++ b/pandas/tests/api/test_types.py @@ -42,9 +42,11 @@ def check_deprecation(self, fold, fnew): expected = fnew('foo') assert result == expected except TypeError: - pytest.raises(TypeError, lambda: fnew('foo')) + with pytest.raises(TypeError): + fnew('foo') except AttributeError: - pytest.raises(AttributeError, lambda: fnew('foo')) + with pytest.raises(AttributeError): + fnew('foo') def test_deprecated_from_api_types(self): diff --git a/pandas/tests/arrays/categorical/test_api.py b/pandas/tests/arrays/categorical/test_api.py index ec90995e6084b..505c2a8eab7cd 100644 --- a/pandas/tests/arrays/categorical/test_api.py +++ b/pandas/tests/arrays/categorical/test_api.py @@ -157,23 +157,17 @@ def test_reorder_categories(self): # not all "old" included in "new" cat = Categorical(["a", "b", "c", "a"], ordered=True) - def f(): + with pytest.raises(ValueError): cat.reorder_categories(["a"]) - pytest.raises(ValueError, f) - # still not all "old" in "new" - def f(): + with pytest.raises(ValueError): cat.reorder_categories(["a", "b", "d"]) - pytest.raises(ValueError, f) - # all "old" included in "new", but too long - def f(): + with pytest.raises(ValueError): cat.reorder_categories(["a", "b", "c", "d"]) - pytest.raises(ValueError, f) - def test_add_categories(self): cat = Categorical(["a", "b", "c", "a"], ordered=True) old = cat.copy() @@ -195,11 +189,9 @@ def test_add_categories(self): assert res is None # new is in old categories - def f(): + with pytest.raises(ValueError): cat.add_categories(["d"]) - pytest.raises(ValueError, f) - # GH 9927 cat = Categorical(list("abc"), ordered=True) expected = Categorical( @@ -351,11 +343,9 @@ def test_remove_categories(self): assert res is None # removal is not in categories - def f(): + with pytest.raises(ValueError): cat.remove_categories(["c"]) - pytest.raises(ValueError, f) - def test_remove_unused_categories(self): c = Categorical(["a", "b", "c", "d", "a"], categories=["a", "b", "c", "d", "e"]) @@ -461,20 +451,16 @@ def test_codes_immutable(self): tm.assert_numpy_array_equal(c.codes, exp) # Assignments to codes should raise - def f(): + with pytest.raises(ValueError): c.codes = np.array([0, 1, 2, 0, 1], dtype='int8') - pytest.raises(ValueError, f) - # changes in the codes array should raise # np 1.6.1 raises RuntimeError rather than ValueError codes = c.codes - def f(): + with pytest.raises(ValueError): codes[4] = 1 - pytest.raises(ValueError, f) - # But even after getting the codes, the original array should still be # writeable! c[4] = "a" diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py index f1475c5022a86..79e10de2b8aaf 100644 --- a/pandas/tests/arrays/categorical/test_constructors.py +++ b/pandas/tests/arrays/categorical/test_constructors.py @@ -77,8 +77,8 @@ def test_constructor_unsortable(self): assert not factor.ordered # this however will raise as cannot be sorted - pytest.raises( - TypeError, lambda: Categorical(arr, ordered=True)) + with pytest.raises(TypeError): + Categorical(arr, ordered=True) def test_constructor_interval(self): result = Categorical([Interval(1, 2), Interval(2, 3), Interval(3, 6)], @@ -99,16 +99,12 @@ def test_constructor(self): tm.assert_numpy_array_equal(c2.__array__(), exp_arr) # categories must be unique - def f(): + with pytest.raises(ValueError): Categorical([1, 2], [1, 2, 2]) - pytest.raises(ValueError, f) - - def f(): + with pytest.raises(ValueError): Categorical(["a", "b"], ["a", "b", "b"]) - pytest.raises(ValueError, f) - # The default should be unordered c1 = Categorical(["a", "b", "c", "a"]) assert not c1.ordered @@ -421,35 +417,25 @@ def test_constructor_with_categorical_categories(self): def test_from_codes(self): # too few categories - def f(): + with pytest.raises(ValueError): Categorical.from_codes([1, 2], [1, 2]) - pytest.raises(ValueError, f) - # no int codes - def f(): + with pytest.raises(ValueError): Categorical.from_codes(["a"], [1, 2]) - pytest.raises(ValueError, f) - # no unique categories - def f(): + with pytest.raises(ValueError): Categorical.from_codes([0, 1, 2], ["a", "a", "b"]) - pytest.raises(ValueError, f) - # NaN categories included - def f(): + with pytest.raises(ValueError): Categorical.from_codes([0, 1, 2], ["a", "b", np.nan]) - pytest.raises(ValueError, f) - # too negative - def f(): + with pytest.raises(ValueError): Categorical.from_codes([-2, 1, 2], ["a", "b", "c"]) - pytest.raises(ValueError, f) - exp = Categorical(["a", "b", "c"], ordered=False) res = Categorical.from_codes([0, 1, 2], ["a", "b", "c"]) tm.assert_categorical_equal(exp, res) diff --git a/pandas/tests/arrays/categorical/test_indexing.py b/pandas/tests/arrays/categorical/test_indexing.py index 4ba934f44a0ac..294344da7c95e 100644 --- a/pandas/tests/arrays/categorical/test_indexing.py +++ b/pandas/tests/arrays/categorical/test_indexing.py @@ -133,17 +133,13 @@ def test_categories_assigments(self): tm.assert_index_equal(s.categories, Index([1, 2, 3])) # lengthen - def f(): + with pytest.raises(ValueError): s.categories = [1, 2, 3, 4] - pytest.raises(ValueError, f) - # shorten - def f(): + with pytest.raises(ValueError): s.categories = [1, 2] - pytest.raises(ValueError, f) - # Combinations of sorted/unique: @pytest.mark.parametrize("idx_values", [[1, 2, 3, 4], [1, 3, 2, 4], [1, 3, 3, 4], [1, 2, 2, 4]]) diff --git a/pandas/tests/arrays/categorical/test_operators.py b/pandas/tests/arrays/categorical/test_operators.py index f216865faa2ad..9304df58bba95 100644 --- a/pandas/tests/arrays/categorical/test_operators.py +++ b/pandas/tests/arrays/categorical/test_operators.py @@ -76,28 +76,22 @@ def test_comparisons(self): tm.assert_numpy_array_equal(res, exp) # Only categories with same categories can be compared - def f(): + with pytest.raises(TypeError): cat > cat_rev - pytest.raises(TypeError, f) - cat_rev_base2 = Categorical( ["b", "b", "b"], categories=["c", "b", "a", "d"]) - def f(): + with pytest.raises(TypeError): cat_rev > cat_rev_base2 - pytest.raises(TypeError, f) - # Only categories with same ordering information can be compared cat_unorderd = cat.set_ordered(False) assert not (cat > cat).any() - def f(): + with pytest.raises(TypeError): cat > cat_unorderd - pytest.raises(TypeError, f) - # comparison (in both directions) with Series will raise s = Series(["b", "b", "b"]) pytest.raises(TypeError, lambda: cat > s) @@ -194,11 +188,9 @@ def test_comparisons(self, data, reverse, base): tm.assert_numpy_array_equal(res_rev.values, exp_rev2) # Only categories with same categories can be compared - def f(): + with pytest.raises(TypeError): cat > cat_rev - pytest.raises(TypeError, f) - # categorical cannot be compared to Series or numpy array, and also # not the other way around pytest.raises(TypeError, lambda: cat > s) @@ -284,14 +276,16 @@ def test_numeric_like_ops(self): # numpy ops s = Series(Categorical([1, 2, 3, 4])) - pytest.raises(TypeError, lambda: np.sum(s)) + with pytest.raises(TypeError): + np.sum(s) # numeric ops on a Series for op in ['__add__', '__sub__', '__mul__', '__truediv__']: pytest.raises(TypeError, lambda: getattr(s, op)(2)) # invalid ufunc - pytest.raises(TypeError, lambda: np.log(s)) + with pytest.raises(TypeError): + np.log(s) def test_contains(self): # GH21508 diff --git a/pandas/tests/frame/test_apply.py b/pandas/tests/frame/test_apply.py index a3b72d223f957..adf875ccc5b62 100644 --- a/pandas/tests/frame/test_apply.py +++ b/pandas/tests/frame/test_apply.py @@ -57,7 +57,8 @@ def test_apply(self, float_frame): # invalid axis df = DataFrame( [[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=['a', 'a', 'c']) - pytest.raises(ValueError, df.apply, lambda x: x, 2) + with pytest.raises(ValueError): + df.apply(lambda x: x, 2) # GH 9573 df = DataFrame({'c0': ['A', 'A', 'B', 'B'], @@ -890,19 +891,16 @@ def test_agg_transform(self, axis, float_frame): def test_transform_and_agg_err(self, axis, float_frame): # cannot both transform and agg - def f(): + with pytest.raises(ValueError): float_frame.transform(['max', 'min'], axis=axis) - pytest.raises(ValueError, f) - def f(): + with pytest.raises(ValueError): with np.errstate(all='ignore'): float_frame.agg(['max', 'sqrt'], axis=axis) - pytest.raises(ValueError, f) - def f(): + with pytest.raises(ValueError): with np.errstate(all='ignore'): float_frame.transform(['max', 'sqrt'], axis=axis) - pytest.raises(ValueError, f) df = pd.DataFrame({'A': range(5), 'B': 5}) diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index b95dad422e90a..ad2457661292b 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -487,9 +487,9 @@ def test_setitem(self): # so raise/warn smaller = self.frame[:2] - def f(): + with pytest.raises(com.SettingWithCopyError): smaller['col10'] = ['1', '2'] - pytest.raises(com.SettingWithCopyError, f) + assert smaller['col10'].dtype == np.object_ assert (smaller['col10'] == ['1', '2']).all() @@ -1022,9 +1022,9 @@ def test_fancy_getitem_slice_mixed(self): # setting it triggers setting with copy sliced = self.frame.iloc[:, -3:] - def f(): + with pytest.raises(com.SettingWithCopyError): sliced['C'] = 4. - pytest.raises(com.SettingWithCopyError, f) + assert (self.frame['C'] == 4).all() def test_fancy_setitem_int_labels(self): @@ -1555,14 +1555,12 @@ def test_getitem_setitem_float_labels(self): cp = df.copy() - def f(): + with pytest.raises(TypeError): cp.iloc[1.0:5] = 0 - pytest.raises(TypeError, f) - def f(): + with pytest.raises(TypeError): result = cp.iloc[1.0:5] == 0 # noqa - pytest.raises(TypeError, f) assert result.values.all() assert (cp.iloc[0:1] == df.iloc[0:1]).values.all() @@ -1948,9 +1946,9 @@ def test_iloc_row(self): # verify slice is view # setting it makes it raise/warn - def f(): + with pytest.raises(com.SettingWithCopyError): result[2] = 0. - pytest.raises(com.SettingWithCopyError, f) + exp_col = df[2].copy() exp_col[4:8] = 0. assert_series_equal(df[2], exp_col) @@ -1979,9 +1977,9 @@ def test_iloc_col(self): # verify slice is view # and that we are setting a copy - def f(): + with pytest.raises(com.SettingWithCopyError): result[8] = 0. - pytest.raises(com.SettingWithCopyError, f) + assert (df[8] == 0).all() # list of integers @@ -3459,35 +3457,29 @@ def test_assigning_ops(self): tm.assert_frame_equal(df, exp_single_cats_value) # - assign a single value not in the current categories set - def f(): + with pytest.raises(ValueError): df = orig.copy() df.iloc[2, 0] = "c" - pytest.raises(ValueError, f) - # - assign a complete row (mixed values) -> exp_single_row df = orig.copy() df.iloc[2, :] = ["b", 2] tm.assert_frame_equal(df, exp_single_row) # - assign a complete row (mixed values) not in categories set - def f(): + with pytest.raises(ValueError): df = orig.copy() df.iloc[2, :] = ["c", 2] - pytest.raises(ValueError, f) - # - assign multiple rows (mixed values) -> exp_multi_row df = orig.copy() df.iloc[2:4, :] = [["b", 2], ["b", 2]] tm.assert_frame_equal(df, exp_multi_row) - def f(): + with pytest.raises(ValueError): df = orig.copy() df.iloc[2:4, :] = [["c", 2], ["c", 2]] - pytest.raises(ValueError, f) - # assign a part of a column with dtype == categorical -> # exp_parts_cats_col df = orig.copy() @@ -3525,35 +3517,29 @@ def f(): tm.assert_frame_equal(df, exp_single_cats_value) # - assign a single value not in the current categories set - def f(): + with pytest.raises(ValueError): df = orig.copy() df.loc["j", "cats"] = "c" - pytest.raises(ValueError, f) - # - assign a complete row (mixed values) -> exp_single_row df = orig.copy() df.loc["j", :] = ["b", 2] tm.assert_frame_equal(df, exp_single_row) # - assign a complete row (mixed values) not in categories set - def f(): + with pytest.raises(ValueError): df = orig.copy() df.loc["j", :] = ["c", 2] - pytest.raises(ValueError, f) - # - assign multiple rows (mixed values) -> exp_multi_row df = orig.copy() df.loc["j":"k", :] = [["b", 2], ["b", 2]] tm.assert_frame_equal(df, exp_multi_row) - def f(): + with pytest.raises(ValueError): df = orig.copy() df.loc["j":"k", :] = [["c", 2], ["c", 2]] - pytest.raises(ValueError, f) - # assign a part of a column with dtype == categorical -> # exp_parts_cats_col df = orig.copy() @@ -3594,35 +3580,29 @@ def f(): tm.assert_frame_equal(df, exp_single_cats_value) # - assign a single value not in the current categories set - def f(): + with pytest.raises(ValueError): df = orig.copy() df.loc["j", df.columns[0]] = "c" - pytest.raises(ValueError, f) - # - assign a complete row (mixed values) -> exp_single_row df = orig.copy() df.loc["j", :] = ["b", 2] tm.assert_frame_equal(df, exp_single_row) # - assign a complete row (mixed values) not in categories set - def f(): + with pytest.raises(ValueError): df = orig.copy() df.loc["j", :] = ["c", 2] - pytest.raises(ValueError, f) - # - assign multiple rows (mixed values) -> exp_multi_row df = orig.copy() df.loc["j":"k", :] = [["b", 2], ["b", 2]] tm.assert_frame_equal(df, exp_multi_row) - def f(): + with pytest.raises(ValueError): df = orig.copy() df.loc["j":"k", :] = [["c", 2], ["c", 2]] - pytest.raises(ValueError, f) - # assign a part of a column with dtype == categorical -> # exp_parts_cats_col df = orig.copy() @@ -3657,12 +3637,10 @@ def f(): tm.assert_frame_equal(df, exp_single_cats_value) # - assign a single value not in the current categories set - def f(): + with pytest.raises(ValueError): df = orig.copy() df.iat[2, 0] = "c" - pytest.raises(ValueError, f) - # at # - assign a single value -> exp_single_cats_value df = orig.copy() @@ -3670,12 +3648,10 @@ def f(): tm.assert_frame_equal(df, exp_single_cats_value) # - assign a single value not in the current categories set - def f(): + with pytest.raises(ValueError): df = orig.copy() df.at["j", "cats"] = "c" - pytest.raises(ValueError, f) - # fancy indexing catsf = Categorical(["a", "a", "c", "c", "a", "a", "a"], categories=["a", "b", "c"]) @@ -3695,12 +3671,10 @@ def f(): df.at["j", "cats"] = "b" tm.assert_frame_equal(df, exp_single_cats_value) - def f(): + with pytest.raises(ValueError): df = orig.copy() df.at["j", "cats"] = "c" - pytest.raises(ValueError, f) - # Assigning a Category to parts of a int/... column uses the values of # the Catgorical df = DataFrame({"a": [1, 1, 1, 1, 1], "b": list("aaaaa")}) diff --git a/pandas/tests/frame/test_quantile.py b/pandas/tests/frame/test_quantile.py index a7c91dd36b2d2..bbb6c38350219 100644 --- a/pandas/tests/frame/test_quantile.py +++ b/pandas/tests/frame/test_quantile.py @@ -72,9 +72,8 @@ def test_quantile_axis_mixed(self): assert_series_equal(result, expected) # must raise - def f(): + with pytest.raises(TypeError): df.quantile(.5, axis=1, numeric_only=False) - pytest.raises(TypeError, f) def test_quantile_axis_parameter(self): # GH 9543/9544 diff --git a/pandas/tests/generic/test_frame.py b/pandas/tests/generic/test_frame.py index f6d5bf86d1489..25440702a339b 100644 --- a/pandas/tests/generic/test_frame.py +++ b/pandas/tests/generic/test_frame.py @@ -76,8 +76,10 @@ def test_nonzero_single_element(self): assert not df.bool() df = DataFrame([[False, False]]) - pytest.raises(ValueError, lambda: df.bool()) - pytest.raises(ValueError, lambda: bool(df)) + with pytest.raises(ValueError): + df.bool() + with pytest.raises(ValueError): + bool(df) def test_get_numeric_data_preserve_dtype(self): diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index f0d0ac246a251..264f2567e45c1 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -527,9 +527,8 @@ def test_bins_unequal_len(): bins = pd.cut(series.dropna().values, 4) # len(bins) != len(series) here - def f(): + with pytest.raises(ValueError): series.groupby(bins).mean() - pytest.raises(ValueError, f) def test_as_index(): diff --git a/pandas/tests/indexes/datetimes/test_astype.py b/pandas/tests/indexes/datetimes/test_astype.py index a1916979ab536..d47d1016ee653 100644 --- a/pandas/tests/indexes/datetimes/test_astype.py +++ b/pandas/tests/indexes/datetimes/test_astype.py @@ -286,7 +286,8 @@ def test_to_period_tz(self, tz): def test_to_period_nofreq(self): idx = DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-04']) - pytest.raises(ValueError, idx.to_period) + with pytest.raises(ValueError): + idx.to_period() idx = DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03'], freq='infer') diff --git a/pandas/tests/indexes/multi/test_analytics.py b/pandas/tests/indexes/multi/test_analytics.py index a1fb242979a11..499e467421816 100644 --- a/pandas/tests/indexes/multi/test_analytics.py +++ b/pandas/tests/indexes/multi/test_analytics.py @@ -56,11 +56,9 @@ def test_truncate(): def test_where(): i = MultiIndex.from_tuples([('A', 1), ('A', 2)]) - def f(): + with pytest.raises(NotImplementedError): i.where(True) - pytest.raises(NotImplementedError, f) - def test_where_array_like(): i = MultiIndex.from_tuples([('A', 1), ('A', 2)]) @@ -68,9 +66,9 @@ def test_where_array_like(): cond = [False, True] for klass in klasses: - def f(): - return i.where(klass(cond)) - pytest.raises(NotImplementedError, f) + with pytest.raises(NotImplementedError): + i.where(klass(cond)) + # TODO: reshape diff --git a/pandas/tests/indexes/multi/test_sorting.py b/pandas/tests/indexes/multi/test_sorting.py index 5ff97743be444..1a81318e06d8d 100644 --- a/pandas/tests/indexes/multi/test_sorting.py +++ b/pandas/tests/indexes/multi/test_sorting.py @@ -63,7 +63,8 @@ def test_sortlevel_deterministic(): def test_sort(indices): - pytest.raises(TypeError, indices.sort) + with pytest.raises(TypeError): + indices.sort() def test_numpy_argsort(idx): diff --git a/pandas/tests/indexing/multiindex/test_setitem.py b/pandas/tests/indexing/multiindex/test_setitem.py index bc00481ddfd90..91ffd308e6793 100644 --- a/pandas/tests/indexing/multiindex/test_setitem.py +++ b/pandas/tests/indexing/multiindex/test_setitem.py @@ -132,11 +132,9 @@ def test_multiindex_setitem(self): tm.assert_frame_equal(df.loc[['bar']], expected) # raise because these have differing levels - def f(): + with pytest.raises(TypeError): df.loc['bar'] *= 2 - pytest.raises(TypeError, f) - # from SO # http://stackoverflow.com/questions/24572040/pandas-access-the-level-of-multiindex-for-inplace-operation df_orig = DataFrame.from_dict({'price': { @@ -195,18 +193,14 @@ def test_multiindex_assignment(self): tm.assert_series_equal(df.ix[4, 'c'], exp) # invalid assignments - def f(): + with pytest.raises(ValueError): with catch_warnings(record=True): df.ix[4, 'c'] = [0, 1, 2, 3] - pytest.raises(ValueError, f) - - def f(): + with pytest.raises(ValueError): with catch_warnings(record=True): df.ix[4, 'c'] = [0] - pytest.raises(ValueError, f) - # groupby example NUM_ROWS = 100 NUM_COLS = 10 diff --git a/pandas/tests/indexing/multiindex/test_slice.py b/pandas/tests/indexing/multiindex/test_slice.py index 10f1b22b49dce..596fe5d564a40 100644 --- a/pandas/tests/indexing/multiindex/test_slice.py +++ b/pandas/tests/indexing/multiindex/test_slice.py @@ -100,11 +100,9 @@ def test_per_axis_per_level_getitem(self): expected = df.iloc[[2, 3]] tm.assert_frame_equal(result, expected) - def f(): + with pytest.raises(ValueError): df.loc[(slice(None), np.array([True, False])), :] - pytest.raises(ValueError, f) - # ambiguous cases # these can be multiply interpreted (e.g. in this case # as df.loc[slice(None),[1]] as well @@ -307,11 +305,9 @@ def test_per_axis_per_level_doc_examples(self): tm.assert_frame_equal(result, expected) # not sorted - def f(): + with pytest.raises(UnsortedIndexError): df.loc['A1', ('a', slice('foo'))] - pytest.raises(UnsortedIndexError, f) - # GH 16734: not sorted, but no real slicing tm.assert_frame_equal(df.loc['A1', (slice(None), 'foo')], df.loc['A1'].iloc[:, [0, 2]]) @@ -361,21 +357,15 @@ def test_loc_axis_arguments(self): tm.assert_frame_equal(result, expected) # invalid axis - def f(): + with pytest.raises(ValueError): df.loc(axis=-1)[:, :, ['C1', 'C3']] - pytest.raises(ValueError, f) - - def f(): + with pytest.raises(ValueError): df.loc(axis=2)[:, :, ['C1', 'C3']] - pytest.raises(ValueError, f) - - def f(): + with pytest.raises(ValueError): df.loc(axis='foo')[:, :, ['C1', 'C3']] - pytest.raises(ValueError, f) - def test_per_axis_per_level_setitem(self): # test index maker @@ -475,18 +465,14 @@ def test_per_axis_per_level_setitem(self): # not enough values df = df_orig.copy() - def f(): + with pytest.raises(ValueError): df.loc[(slice(None), 1), (slice(None), ['foo'])] = np.array( [[100], [100, 100]], dtype='int64') - pytest.raises(ValueError, f) - - def f(): + with pytest.raises(ValueError): df.loc[(slice(None), 1), (slice(None), ['foo'])] = np.array( [100, 100, 100, 100], dtype='int64') - pytest.raises(ValueError, f) - # with an alignable rhs df = df_orig.copy() df.loc[(slice(None), 1), (slice(None), ['foo'])] = df.loc[(slice( diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index 4236a80bc98f1..3c36dee310a28 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -37,12 +37,10 @@ def test_setitem_ndarray_1d(self): df['bar'] = np.zeros(10, dtype=np.complex) # invalid - def f(): + with pytest.raises(ValueError): df.loc[df.index[2:5], 'bar'] = np.array([2.33j, 1.23 + 0.1j, 2.2, 1.0]) - pytest.raises(ValueError, f) - # valid df.loc[df.index[2:6], 'bar'] = np.array([2.33j, 1.23 + 0.1j, 2.2, 1.0]) @@ -57,11 +55,9 @@ def f(): df['foo'] = np.zeros(10, dtype=np.float64) df['bar'] = np.zeros(10, dtype=np.complex) - def f(): + with pytest.raises(ValueError): df[2:5] = np.arange(1, 4) * 1j - pytest.raises(ValueError, f) - def test_inf_upcast(self): # GH 16957 # We should be able to use np.inf as a key diff --git a/pandas/tests/indexing/test_panel.py b/pandas/tests/indexing/test_panel.py index f8bc2b932df9d..34708e1148c90 100644 --- a/pandas/tests/indexing/test_panel.py +++ b/pandas/tests/indexing/test_panel.py @@ -64,11 +64,9 @@ def test_iloc_getitem_panel(self): with pytest.raises(IndexError): p.iloc[tuple([10, 5])] - def f(): + with pytest.raises(IndexError): p.iloc[0, [True, True], [0, 1, 2]] - pytest.raises(IndexError, f) - # trying to use a label with pytest.raises(ValueError): p.iloc[tuple(['j', 'D'])] @@ -88,16 +86,12 @@ def f(): result = p.iloc[0, [True, True, True], [0, 1]] tm.assert_frame_equal(result, expected) - def f(): + with pytest.raises(IndexError): p.iloc[0, [True, True, True], [0, 1, 2]] - pytest.raises(IndexError, f) - - def f(): + with pytest.raises(IndexError): p.iloc[0, [True, True, True], [2]] - pytest.raises(IndexError, f) - def test_iloc_panel_issue(self): with catch_warnings(record=True): @@ -210,12 +204,10 @@ def test_panel_assignment(self): # TODO: unused? # expected = wp.loc[['Item1', 'Item2'], :, ['A', 'B']] - def f(): + with pytest.raises(NotImplementedError): wp.loc[['Item1', 'Item2'], :, ['A', 'B']] = wp2.loc[ ['Item1', 'Item2'], :, ['A', 'B']] - pytest.raises(NotImplementedError, f) - # to_assign = wp2.loc[['Item1', 'Item2'], :, ['A', 'B']] # wp.loc[['Item1', 'Item2'], :, ['A', 'B']] = to_assign # result = wp.loc[['Item1', 'Item2'], :, ['A', 'B']] diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py index f27b556366d88..b863afe02c2e8 100644 --- a/pandas/tests/indexing/test_partial.py +++ b/pandas/tests/indexing/test_partial.py @@ -48,16 +48,12 @@ def test_partial_setting(self): # iloc/iat raise s = s_orig.copy() - def f(): + with pytest.raises(IndexError): s.iloc[3] = 5. - pytest.raises(IndexError, f) - - def f(): + with pytest.raises(IndexError): s.iat[3] = 5. - pytest.raises(IndexError, f) - # ## frame ## df_orig = DataFrame( @@ -66,16 +62,12 @@ def f(): # iloc/iat raise df = df_orig.copy() - def f(): + with pytest.raises(IndexError): df.iloc[4, 2] = 5. - pytest.raises(IndexError, f) - - def f(): + with pytest.raises(IndexError): df.iat[4, 2] = 5. - pytest.raises(IndexError, f) - # row setting where it exists expected = DataFrame(dict({'A': [0, 4, 4], 'B': [1, 5, 5]})) df = df_orig.copy() @@ -208,11 +200,9 @@ def test_partial_setting_mixed_dtype(self): # list-like must conform df = DataFrame(columns=['A', 'B']) - def f(): + with pytest.raises(ValueError): df.loc[0] = [1, 2, 3] - pytest.raises(ValueError, f) - # TODO: #15657, these are left as object and not coerced df = DataFrame(columns=['A', 'B']) df.loc[3] = [6, 7] @@ -417,30 +407,22 @@ def test_partial_set_invalid(self): df = orig.copy() # don't allow not string inserts - def f(): + with pytest.raises(TypeError): with catch_warnings(record=True): df.loc[100.0, :] = df.ix[0] - pytest.raises(TypeError, f) - - def f(): + with pytest.raises(TypeError): with catch_warnings(record=True): df.loc[100, :] = df.ix[0] - pytest.raises(TypeError, f) - - def f(): + with pytest.raises(TypeError): with catch_warnings(record=True): df.ix[100.0, :] = df.ix[0] - pytest.raises(TypeError, f) - - def f(): + with pytest.raises(ValueError): with catch_warnings(record=True): df.ix[100, :] = df.ix[0] - pytest.raises(ValueError, f) - # allow object conversion here df = orig.copy() with catch_warnings(record=True): @@ -481,21 +463,15 @@ def test_partial_set_empty_frame(self): # frame df = DataFrame() - def f(): + with pytest.raises(ValueError): df.loc[1] = 1 - pytest.raises(ValueError, f) - - def f(): + with pytest.raises(ValueError): df.loc[1] = Series([1], index=['foo']) - pytest.raises(ValueError, f) - - def f(): + with pytest.raises(ValueError): df.loc[:, 1] = 1 - pytest.raises(ValueError, f) - # these work as they don't really change # anything but the index # GH5632 diff --git a/pandas/tests/resample/test_resample_api.py b/pandas/tests/resample/test_resample_api.py index 43c087a932a7e..69684daf05f3d 100644 --- a/pandas/tests/resample/test_resample_api.py +++ b/pandas/tests/resample/test_resample_api.py @@ -438,14 +438,12 @@ def test_agg_misc(): # errors # invalid names in the agg specification for t in cases: - def f(): + with pytest.raises(KeyError): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): t[['A']].agg({'A': ['sum', 'std'], 'B': ['mean', 'std']}) - pytest.raises(KeyError, f) - def test_agg_nested_dicts(): diff --git a/pandas/tests/reshape/merge/test_multi.py b/pandas/tests/reshape/merge/test_multi.py index aa32948468907..7e8b5b1120bc6 100644 --- a/pandas/tests/reshape/merge/test_multi.py +++ b/pandas/tests/reshape/merge/test_multi.py @@ -505,19 +505,15 @@ def test_join_multi_levels(self): # invalid cases household.index.name = 'foo' - def f(): + with pytest.raises(ValueError): household.join(portfolio, how='inner') - pytest.raises(ValueError, f) - portfolio2 = portfolio.copy() portfolio2.index.set_names(['household_id', 'foo']) - def f(): + with pytest.raises(ValueError): portfolio2.join(portfolio, how='inner') - pytest.raises(ValueError, f) - def test_join_multi_levels2(self): # some more advanced merges diff --git a/pandas/tests/series/indexing/test_boolean.py b/pandas/tests/series/indexing/test_boolean.py index b94104a89627a..9d024bffa3240 100644 --- a/pandas/tests/series/indexing/test_boolean.py +++ b/pandas/tests/series/indexing/test_boolean.py @@ -49,16 +49,12 @@ def test_getitem_boolean_empty(): # invalid because of the boolean indexer # that's empty or not-aligned - def f(): + with pytest.raises(IndexingError): s[Series([], dtype=bool)] - pytest.raises(IndexingError, f) - - def f(): + with pytest.raises(IndexingError): s[Series([True], dtype=bool)] - pytest.raises(IndexingError, f) - def test_getitem_boolean_object(test_data): # using column from DataFrame @@ -210,16 +206,12 @@ def test_where_unsafe(): s = Series(np.arange(10)) mask = s > 5 - def f(): + with pytest.raises(ValueError): s[mask] = [5, 4, 3, 2, 1] - pytest.raises(ValueError, f) - - def f(): + with pytest.raises(ValueError): s[mask] = [0] * 5 - pytest.raises(ValueError, f) - # dtype changes s = Series([1, 2, 3, 4]) result = s.where(s > 2, np.nan) @@ -360,11 +352,9 @@ def test_where_setitem_invalid(): # slice s = Series(list('abc')) - def f(): + with pytest.raises(ValueError): s[0:3] = list(range(27)) - pytest.raises(ValueError, f) - s[0:3] = list(range(3)) expected = Series([0, 1, 2]) assert_series_equal(s.astype(np.int64), expected, ) @@ -372,11 +362,9 @@ def f(): # slice with step s = Series(list('abcdef')) - def f(): + with pytest.raises(ValueError): s[0:4:2] = list(range(27)) - pytest.raises(ValueError, f) - s = Series(list('abcdef')) s[0:4:2] = list(range(2)) expected = Series([0, 'b', 1, 'd', 'e', 'f']) @@ -385,11 +373,9 @@ def f(): # neg slices s = Series(list('abcdef')) - def f(): + with pytest.raises(ValueError): s[:-1] = list(range(27)) - pytest.raises(ValueError, f) - s[-3:-1] = list(range(2)) expected = Series(['a', 'b', 'c', 0, 1, 'f']) assert_series_equal(s, expected) @@ -397,18 +383,14 @@ def f(): # list s = Series(list('abc')) - def f(): + with pytest.raises(ValueError): s[[0, 1, 2]] = list(range(27)) - pytest.raises(ValueError, f) - s = Series(list('abc')) - def f(): + with pytest.raises(ValueError): s[[0, 1, 2]] = list(range(2)) - pytest.raises(ValueError, f) - # scalar s = Series(list('abc')) s[0] = list(range(10)) diff --git a/pandas/tests/series/indexing/test_numeric.py b/pandas/tests/series/indexing/test_numeric.py index da0e15b8a96fc..8a4fdc7e12e4d 100644 --- a/pandas/tests/series/indexing/test_numeric.py +++ b/pandas/tests/series/indexing/test_numeric.py @@ -96,11 +96,9 @@ def test_delitem(): # empty s = Series() - def f(): + with pytest.raises(KeyError): del s[0] - pytest.raises(KeyError, f) - # only 1 left, del, add, del s = Series(1) del s[0] @@ -207,11 +205,9 @@ def test_setitem_float_labels(): def test_slice_float_get_set(test_data): pytest.raises(TypeError, lambda: test_data.ts[4.0:10.0]) - def f(): + with pytest.raises(TypeError): test_data.ts[4.0:10.0] = 0 - pytest.raises(TypeError, f) - pytest.raises(TypeError, test_data.ts.__getitem__, slice(4.5, 10.0)) pytest.raises(TypeError, test_data.ts.__setitem__, slice(4.5, 10.0), 0) diff --git a/pandas/tests/series/test_apply.py b/pandas/tests/series/test_apply.py index f4c8ebe64630c..90cf6916df0d1 100644 --- a/pandas/tests/series/test_apply.py +++ b/pandas/tests/series/test_apply.py @@ -216,24 +216,20 @@ def test_transform(self, string_series): def test_transform_and_agg_error(self, string_series): # we are trying to transform with an aggregator - def f(): + with pytest.raises(ValueError): string_series.transform(['min', 'max']) - pytest.raises(ValueError, f) - def f(): + with pytest.raises(ValueError): with np.errstate(all='ignore'): string_series.agg(['sqrt', 'max']) - pytest.raises(ValueError, f) - def f(): + with pytest.raises(ValueError): with np.errstate(all='ignore'): string_series.transform(['sqrt', 'max']) - pytest.raises(ValueError, f) - def f(): + with pytest.raises(ValueError): with np.errstate(all='ignore'): string_series.agg({'foo': np.sqrt, 'bar': 'sum'}) - pytest.raises(ValueError, f) def test_demo(self): # demonstration tests diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index f5d33c3e09a97..ced7d0e75fd7d 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -132,21 +132,15 @@ def test_invalid_delegation(self): delegate = self.Delegate(self.Delegator()) - def f(): + with pytest.raises(TypeError): delegate.foo - pytest.raises(TypeError, f) - - def f(): + with pytest.raises(TypeError): delegate.foo = 5 - pytest.raises(TypeError, f) - - def f(): + with pytest.raises(TypeError): delegate.foo() - pytest.raises(TypeError, f) - @pytest.mark.skipif(PYPY, reason="not relevant for PyPy") def test_memory_usage(self): # Delegate does not implement memory_usage. @@ -1067,10 +1061,9 @@ class T(NoNewAttributesMixin): assert "__frozen" in dir(t) assert getattr(t, "__frozen") - def f(): + with pytest.raises(AttributeError): t.b = "test" - pytest.raises(AttributeError, f) assert not hasattr(t, "b") diff --git a/pandas/tests/test_lib.py b/pandas/tests/test_lib.py index 3e34b48fb6795..d0812eae80f2d 100644 --- a/pandas/tests/test_lib.py +++ b/pandas/tests/test_lib.py @@ -24,8 +24,8 @@ def test_max_len_string_array(self): assert libwriters.max_len_string_array(arr) == 3 # raises - pytest.raises(TypeError, - lambda: libwriters.max_len_string_array(arr.astype('U'))) + with pytest.raises(TypeError): + libwriters.max_len_string_array(arr.astype('U')) def test_fast_unique_multiple_list_gen_sort(self): keys = [['p', 'a'], ['n', 'd'], ['a', 's']]