From 51ed9f595a6335b3190934b5d7adba360f0ae300 Mon Sep 17 00:00:00 2001 From: gfyoung Date: Fri, 21 Apr 2017 10:29:13 -0400 Subject: [PATCH] MAINT: Remove assertRaises from testing --- pandas/tests/api/test_types.py | 12 +- pandas/tests/computation/test_compat.py | 3 +- pandas/tests/computation/test_eval.py | 147 ++++---- pandas/tests/dtypes/test_cast.py | 2 +- pandas/tests/dtypes/test_dtypes.py | 53 ++- pandas/tests/frame/test_alter_axes.py | 4 +- pandas/tests/frame/test_analytics.py | 46 +-- pandas/tests/frame/test_api.py | 11 +- pandas/tests/frame/test_apply.py | 10 +- .../tests/frame/test_axis_select_reindex.py | 24 +- pandas/tests/frame/test_block_internals.py | 10 +- pandas/tests/frame/test_constructors.py | 30 +- pandas/tests/frame/test_convert_to.py | 2 +- pandas/tests/frame/test_dtypes.py | 13 +- pandas/tests/frame/test_indexing.py | 91 +++-- pandas/tests/frame/test_missing.py | 27 +- pandas/tests/frame/test_mutate_columns.py | 10 +- pandas/tests/frame/test_nonunique_indexes.py | 11 +- pandas/tests/frame/test_operators.py | 40 +-- pandas/tests/frame/test_quantile.py | 6 +- pandas/tests/frame/test_query_eval.py | 42 +-- pandas/tests/frame/test_replace.py | 12 +- pandas/tests/frame/test_reshape.py | 8 +- pandas/tests/frame/test_sorting.py | 4 +- pandas/tests/frame/test_timeseries.py | 12 +- pandas/tests/frame/test_to_csv.py | 9 +- pandas/tests/frame/test_validate.py | 16 +- pandas/tests/groupby/test_aggregate.py | 17 +- pandas/tests/groupby/test_bin_groupby.py | 18 +- pandas/tests/groupby/test_categorical.py | 4 +- pandas/tests/groupby/test_filters.py | 17 +- pandas/tests/groupby/test_groupby.py | 90 ++--- pandas/tests/groupby/test_timegrouper.py | 8 +- pandas/tests/groupby/test_transform.py | 6 +- pandas/tests/indexes/common.py | 14 +- pandas/tests/indexes/datetimes/test_astype.py | 12 +- .../indexes/datetimes/test_construction.py | 56 +-- .../indexes/datetimes/test_date_range.py | 80 +++-- .../tests/indexes/datetimes/test_datetime.py | 30 +- .../tests/indexes/datetimes/test_indexing.py | 2 +- pandas/tests/indexes/datetimes/test_misc.py | 5 +- pandas/tests/indexes/datetimes/test_ops.py | 24 +- .../indexes/datetimes/test_partial_slicing.py | 21 +- pandas/tests/indexes/datetimes/test_tools.py | 101 +++--- pandas/tests/indexes/period/test_asfreq.py | 5 +- .../tests/indexes/period/test_construction.py | 59 +-- pandas/tests/indexes/period/test_indexing.py | 18 +- pandas/tests/indexes/period/test_ops.py | 22 +- .../indexes/period/test_partial_slicing.py | 8 +- pandas/tests/indexes/period/test_period.py | 22 +- pandas/tests/indexes/period/test_setops.py | 10 +- pandas/tests/indexes/test_base.py | 74 ++-- pandas/tests/indexes/test_category.py | 54 +-- pandas/tests/indexes/test_interval.py | 50 +-- pandas/tests/indexes/test_multi.py | 86 ++--- pandas/tests/indexes/test_numeric.py | 42 +-- pandas/tests/indexes/test_range.py | 30 +- .../tests/indexes/timedeltas/test_astype.py | 16 +- .../indexes/timedeltas/test_construction.py | 18 +- .../tests/indexes/timedeltas/test_indexing.py | 4 +- pandas/tests/indexes/timedeltas/test_ops.py | 78 ++-- .../timedeltas/test_partial_slicing.py | 4 +- .../indexes/timedeltas/test_timedelta.py | 18 +- pandas/tests/indexes/timedeltas/test_tools.py | 12 +- pandas/tests/indexing/test_categorical.py | 34 +- .../indexing/test_chaining_and_caching.py | 2 +- pandas/tests/indexing/test_coercion.py | 6 +- pandas/tests/indexing/test_datetime.py | 4 +- pandas/tests/indexing/test_floats.py | 62 ++-- pandas/tests/indexing/test_iloc.py | 30 +- pandas/tests/indexing/test_indexing.py | 16 +- pandas/tests/indexing/test_ix.py | 10 +- pandas/tests/indexing/test_loc.py | 30 +- pandas/tests/indexing/test_multiindex.py | 30 +- pandas/tests/indexing/test_panel.py | 8 +- pandas/tests/indexing/test_partial.py | 31 +- pandas/tests/indexing/test_scalar.py | 18 +- pandas/tests/io/formats/test_format.py | 10 +- pandas/tests/io/formats/test_style.py | 24 +- pandas/tests/io/formats/test_to_latex.py | 2 +- .../tests/io/json/test_json_table_schema.py | 2 +- pandas/tests/io/json/test_normalize.py | 14 +- pandas/tests/io/json/test_pandas.py | 50 +-- pandas/tests/io/json/test_ujson.py | 16 +- pandas/tests/io/msgpack/test_except.py | 29 +- pandas/tests/io/msgpack/test_limits.py | 25 +- pandas/tests/io/msgpack/test_obj.py | 15 +- pandas/tests/io/msgpack/test_pack.py | 15 +- pandas/tests/io/msgpack/test_sequnpack.py | 22 +- pandas/tests/io/msgpack/test_unpack.py | 2 +- pandas/tests/io/parser/c_parser_only.py | 24 +- pandas/tests/io/parser/common.py | 44 +-- pandas/tests/io/parser/compression.py | 8 +- pandas/tests/io/parser/dtypes.py | 14 +- pandas/tests/io/parser/header.py | 36 +- pandas/tests/io/parser/index_col.py | 10 +- pandas/tests/io/parser/parse_dates.py | 10 +- pandas/tests/io/parser/python_parser_only.py | 8 +- pandas/tests/io/parser/test_network.py | 4 +- pandas/tests/io/parser/test_read_fwf.py | 4 +- pandas/tests/io/parser/test_textreader.py | 12 +- pandas/tests/io/parser/usecols.py | 4 +- pandas/tests/io/sas/test_sas.py | 4 +- pandas/tests/io/test_clipboard.py | 4 +- pandas/tests/io/test_common.py | 3 +- pandas/tests/io/test_excel.py | 18 +- pandas/tests/io/test_html.py | 12 +- pandas/tests/io/test_packers.py | 8 +- pandas/tests/io/test_pytables.py | 336 +++++++++--------- pandas/tests/io/test_sql.py | 90 ++--- pandas/tests/io/test_stata.py | 30 +- pandas/tests/plotting/test_boxplot_method.py | 18 +- pandas/tests/plotting/test_datetimelike.py | 6 +- pandas/tests/plotting/test_frame.py | 56 +-- pandas/tests/plotting/test_hist_method.py | 34 +- pandas/tests/plotting/test_misc.py | 10 +- pandas/tests/plotting/test_series.py | 21 +- pandas/tests/reshape/test_concat.py | 16 +- pandas/tests/reshape/test_hashing.py | 6 +- pandas/tests/reshape/test_join.py | 21 +- pandas/tests/reshape/test_merge.py | 54 +-- pandas/tests/reshape/test_merge_asof.py | 35 +- pandas/tests/reshape/test_pivot.py | 17 +- pandas/tests/reshape/test_reshape.py | 8 +- pandas/tests/reshape/test_tile.py | 19 +- .../tests/reshape/test_union_categoricals.py | 6 +- pandas/tests/scalar/test_interval.py | 2 +- pandas/tests/scalar/test_period.py | 108 +++--- pandas/tests/scalar/test_timedelta.py | 44 +-- pandas/tests/scalar/test_timestamp.py | 125 +++---- pandas/tests/series/test_alter_axes.py | 8 +- pandas/tests/series/test_analytics.py | 28 +- pandas/tests/series/test_api.py | 8 +- pandas/tests/series/test_apply.py | 15 +- pandas/tests/series/test_asof.py | 6 +- pandas/tests/series/test_combine_concat.py | 6 +- pandas/tests/series/test_constructors.py | 32 +- pandas/tests/series/test_datetime_values.py | 4 +- pandas/tests/series/test_indexing.py | 142 ++++---- pandas/tests/series/test_internals.py | 4 +- pandas/tests/series/test_missing.py | 42 +-- pandas/tests/series/test_operators.py | 88 ++--- pandas/tests/series/test_rank.py | 2 +- pandas/tests/series/test_replace.py | 6 +- pandas/tests/series/test_sorting.py | 30 +- pandas/tests/series/test_timeseries.py | 36 +- pandas/tests/series/test_validate.py | 18 +- pandas/tests/sparse/test_array.py | 28 +- pandas/tests/sparse/test_frame.py | 32 +- pandas/tests/sparse/test_indexing.py | 4 +- pandas/tests/sparse/test_libsparse.py | 8 +- pandas/tests/sparse/test_series.py | 25 +- pandas/tests/test_algos.py | 24 +- pandas/tests/test_base.py | 16 +- pandas/tests/test_categorical.py | 222 ++++++------ pandas/tests/test_common.py | 6 +- pandas/tests/test_config.py | 54 +-- pandas/tests/test_lib.py | 4 +- pandas/tests/test_multilevel.py | 32 +- pandas/tests/test_nanops.py | 10 +- pandas/tests/test_panel.py | 80 ++--- pandas/tests/test_panel4d.py | 34 +- pandas/tests/test_panelnd.py | 26 +- pandas/tests/test_resample.py | 63 ++-- pandas/tests/test_strings.py | 21 +- pandas/tests/test_testing.py | 24 +- pandas/tests/test_util.py | 10 +- pandas/tests/test_window.py | 144 ++++---- pandas/tests/tools/test_numeric.py | 2 +- pandas/tests/tseries/test_frequencies.py | 33 +- pandas/tests/tseries/test_holiday.py | 4 +- pandas/tests/tseries/test_offsets.py | 46 +-- pandas/tests/tseries/test_timezones.py | 58 +-- pandas/util/testing.py | 60 +--- 174 files changed, 2633 insertions(+), 2498 deletions(-) diff --git a/pandas/tests/api/test_types.py b/pandas/tests/api/test_types.py index 057f7d8f3e286..3b9148a1c91c6 100644 --- a/pandas/tests/api/test_types.py +++ b/pandas/tests/api/test_types.py @@ -1,5 +1,7 @@ # -*- coding: utf-8 -*- +import pytest + from warnings import catch_warnings import numpy as np @@ -41,13 +43,11 @@ def check_deprecation(self, fold, fnew): try: result = fold('foo') expected = fnew('foo') - self.assertEqual(result, expected) + assert result == expected except TypeError: - self.assertRaises(TypeError, - lambda: fnew('foo')) + pytest.raises(TypeError, lambda: fnew('foo')) except AttributeError: - self.assertRaises(AttributeError, - lambda: fnew('foo')) + pytest.raises(AttributeError, lambda: fnew('foo')) def test_deprecation_core_common(self): @@ -83,7 +83,7 @@ def test_removed_from_core_common(self): for t in ['is_null_datelike_scalar', 'ensure_float']: - self.assertRaises(AttributeError, lambda: getattr(com, t)) + pytest.raises(AttributeError, lambda: getattr(com, t)) def test_moved_infer_dtype(): diff --git a/pandas/tests/computation/test_compat.py b/pandas/tests/computation/test_compat.py index 9ee9f674a1ddd..ed569625177d3 100644 --- a/pandas/tests/computation/test_compat.py +++ b/pandas/tests/computation/test_compat.py @@ -2,7 +2,6 @@ from distutils.version import LooseVersion import pandas as pd -from pandas.util import testing as tm from pandas.core.computation.engines import _engines import pandas.core.computation.expr as expr @@ -39,7 +38,7 @@ def testit(): pytest.skip("no numexpr") else: if ne.__version__ < LooseVersion(_MIN_NUMEXPR_VERSION): - with tm.assertRaises(ImportError): + with pytest.raises(ImportError): testit() else: testit() diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index 0ba4fe61ae78f..eacbd2b390154 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -220,11 +220,11 @@ def check_complex_cmp_op(self, lhs, cmp1, rhs, binop, cmp2): scalar_with_in_notin = (is_scalar(rhs) and (cmp1 in skip_these or cmp2 in skip_these)) if scalar_with_in_notin: - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): pd.eval(ex, engine=self.engine, parser=self.parser) - self.assertRaises(TypeError, pd.eval, ex, engine=self.engine, - parser=self.parser, local_dict={'lhs': lhs, - 'rhs': rhs}) + with pytest.raises(TypeError): + pd.eval(ex, engine=self.engine, parser=self.parser, + local_dict={'lhs': lhs, 'rhs': rhs}) else: lhs_new = _eval_single_bin(lhs, cmp1, rhs, self.engine) rhs_new = _eval_single_bin(lhs, cmp2, rhs, self.engine) @@ -236,9 +236,9 @@ def check_complex_cmp_op(self, lhs, cmp1, rhs, binop, cmp2): # hand side bool ops are fixed. # # try: - # self.assertRaises(Exception, pd.eval, ex, - # local_dict={'lhs': lhs, 'rhs': rhs}, - # engine=self.engine, parser=self.parser) + # pytest.raises(Exception, pd.eval, ex, + # local_dict={'lhs': lhs, 'rhs': rhs}, + # engine=self.engine, parser=self.parser) # except AssertionError: # import ipdb # @@ -273,9 +273,9 @@ def check_operands(left, right, cmp_op): def check_simple_cmp_op(self, lhs, cmp1, rhs): ex = 'lhs {0} rhs'.format(cmp1) if cmp1 in ('in', 'not in') and not is_list_like(rhs): - self.assertRaises(TypeError, pd.eval, ex, engine=self.engine, - parser=self.parser, local_dict={'lhs': lhs, - 'rhs': rhs}) + pytest.raises(TypeError, pd.eval, ex, engine=self.engine, + parser=self.parser, local_dict={'lhs': lhs, + 'rhs': rhs}) else: expected = _eval_single_bin(lhs, cmp1, rhs, self.engine) result = pd.eval(ex, engine=self.engine, parser=self.parser) @@ -328,9 +328,9 @@ def check_floor_division(self, lhs, arith1, rhs): expected = lhs // rhs self.check_equal(res, expected) else: - self.assertRaises(TypeError, pd.eval, ex, local_dict={'lhs': lhs, - 'rhs': rhs}, - engine=self.engine, parser=self.parser) + pytest.raises(TypeError, pd.eval, ex, + local_dict={'lhs': lhs, 'rhs': rhs}, + engine=self.engine, parser=self.parser) def get_expected_pow_result(self, lhs, rhs): try: @@ -353,8 +353,8 @@ def check_pow(self, lhs, arith1, rhs): if (is_scalar(lhs) and is_scalar(rhs) and _is_py3_complex_incompat(result, expected)): - self.assertRaises(AssertionError, tm.assert_numpy_array_equal, - result, expected) + pytest.raises(AssertionError, tm.assert_numpy_array_equal, + result, expected) else: tm.assert_almost_equal(result, expected) @@ -385,9 +385,9 @@ def check_compound_invert_op(self, lhs, cmp1, rhs): ex = '~(lhs {0} rhs)'.format(cmp1) if is_scalar(rhs) and cmp1 in skip_these: - self.assertRaises(TypeError, pd.eval, ex, engine=self.engine, - parser=self.parser, local_dict={'lhs': lhs, - 'rhs': rhs}) + pytest.raises(TypeError, pd.eval, ex, engine=self.engine, + parser=self.parser, local_dict={'lhs': lhs, + 'rhs': rhs}) else: # compound if is_scalar(lhs) and is_scalar(rhs): @@ -417,16 +417,16 @@ def test_frame_invert(self): # float always raises lhs = DataFrame(randn(5, 2)) if self.engine == 'numexpr': - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): result = pd.eval(expr, engine=self.engine, parser=self.parser) else: - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): result = pd.eval(expr, engine=self.engine, parser=self.parser) # int raises on numexpr lhs = DataFrame(randint(5, size=(5, 2))) if self.engine == 'numexpr': - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): result = pd.eval(expr, engine=self.engine, parser=self.parser) else: expect = ~lhs @@ -442,10 +442,10 @@ def test_frame_invert(self): # object raises lhs = DataFrame({'b': ['a', 1, 2.0], 'c': rand(3) > 0.5}) if self.engine == 'numexpr': - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): result = pd.eval(expr, engine=self.engine, parser=self.parser) else: - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): result = pd.eval(expr, engine=self.engine, parser=self.parser) def test_series_invert(self): @@ -456,16 +456,16 @@ def test_series_invert(self): # float raises lhs = Series(randn(5)) if self.engine == 'numexpr': - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): result = pd.eval(expr, engine=self.engine, parser=self.parser) else: - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): result = pd.eval(expr, engine=self.engine, parser=self.parser) # int raises on numexpr lhs = Series(randint(5, size=5)) if self.engine == 'numexpr': - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): result = pd.eval(expr, engine=self.engine, parser=self.parser) else: expect = ~lhs @@ -485,10 +485,10 @@ def test_series_invert(self): # object lhs = Series(['a', 1, 2.0]) if self.engine == 'numexpr': - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): result = pd.eval(expr, engine=self.engine, parser=self.parser) else: - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): result = pd.eval(expr, engine=self.engine, parser=self.parser) def test_frame_negate(self): @@ -509,7 +509,7 @@ def test_frame_negate(self): # bool doesn't work with numexpr but works elsewhere lhs = DataFrame(rand(5, 2) > 0.5) if self.engine == 'numexpr': - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): result = pd.eval(expr, engine=self.engine, parser=self.parser) else: expect = -lhs @@ -534,7 +534,7 @@ def test_series_negate(self): # bool doesn't work with numexpr but works elsewhere lhs = Series(rand(5) > 0.5) if self.engine == 'numexpr': - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): result = pd.eval(expr, engine=self.engine, parser=self.parser) else: expect = -lhs @@ -547,7 +547,7 @@ def test_frame_pos(self): # float lhs = DataFrame(randn(5, 2)) if self.engine == 'python': - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): result = pd.eval(expr, engine=self.engine, parser=self.parser) else: expect = lhs @@ -557,7 +557,7 @@ def test_frame_pos(self): # int lhs = DataFrame(randint(5, size=(5, 2))) if self.engine == 'python': - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): result = pd.eval(expr, engine=self.engine, parser=self.parser) else: expect = lhs @@ -567,7 +567,7 @@ def test_frame_pos(self): # bool doesn't work with numexpr but works elsewhere lhs = DataFrame(rand(5, 2) > 0.5) if self.engine == 'python': - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): result = pd.eval(expr, engine=self.engine, parser=self.parser) else: expect = lhs @@ -580,7 +580,7 @@ def test_series_pos(self): # float lhs = Series(randn(5)) if self.engine == 'python': - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): result = pd.eval(expr, engine=self.engine, parser=self.parser) else: expect = lhs @@ -590,7 +590,7 @@ def test_series_pos(self): # int lhs = Series(randint(5, size=5)) if self.engine == 'python': - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): result = pd.eval(expr, engine=self.engine, parser=self.parser) else: expect = lhs @@ -600,7 +600,7 @@ def test_series_pos(self): # bool doesn't work with numexpr but works elsewhere lhs = Series(rand(5) > 0.5) if self.engine == 'python': - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): result = pd.eval(expr, engine=self.engine, parser=self.parser) else: expect = lhs @@ -608,7 +608,7 @@ def test_series_pos(self): assert_series_equal(expect, result) def test_scalar_unary(self): - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): pd.eval('~1.0', engine=self.engine, parser=self.parser) self.assertEqual( @@ -655,7 +655,7 @@ def test_disallow_scalar_bool_ops(self): x, a, b, df = np.random.randn(3), 1, 2, DataFrame(randn(3, 2)) # noqa for ex in exprs: - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): pd.eval(ex, engine=self.engine, parser=self.parser) def test_identical(self): @@ -745,7 +745,7 @@ def setup_ops(self): def check_chained_cmp_op(self, lhs, cmp1, mid, cmp2, rhs): ex1 = 'lhs {0} mid {1} rhs'.format(cmp1, cmp2) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): pd.eval(ex1, engine=self.engine, parser=self.parser) @@ -1099,8 +1099,8 @@ def test_simple_arith_ops(self): ex3 = '1 {0} (x + 1)'.format(op) if op in ('in', 'not in'): - self.assertRaises(TypeError, pd.eval, ex, - engine=self.engine, parser=self.parser) + pytest.raises(TypeError, pd.eval, ex, + engine=self.engine, parser=self.parser) else: expec = _eval_single_bin(1, op, 1, self.engine) x = self.eval(ex, engine=self.engine, parser=self.parser) @@ -1208,7 +1208,7 @@ def test_truediv(self): def test_failing_subscript_with_name_error(self): df = DataFrame(np.random.randn(5, 3)) # noqa - with tm.assertRaises(NameError): + with pytest.raises(NameError): self.eval('df[x > 2] > 2') def test_lhs_expression_subscript(self): @@ -1234,20 +1234,19 @@ def test_assignment_fails(self): df = DataFrame(np.random.randn(5, 3), columns=list('abc')) df2 = DataFrame(np.random.randn(5, 3)) expr1 = 'df = df2' - self.assertRaises(ValueError, self.eval, expr1, - local_dict={'df': df, 'df2': df2}) + pytest.raises(ValueError, self.eval, expr1, + local_dict={'df': df, 'df2': df2}) def test_assignment_column(self): df = DataFrame(np.random.randn(5, 2), columns=list('ab')) orig_df = df.copy() # multiple assignees - self.assertRaises(SyntaxError, df.eval, 'd c = a + b') + pytest.raises(SyntaxError, df.eval, 'd c = a + b') # invalid assignees - self.assertRaises(SyntaxError, df.eval, 'd,c = a + b') - self.assertRaises( - SyntaxError, df.eval, 'Timestamp("20131001") = a + b') + pytest.raises(SyntaxError, df.eval, 'd,c = a + b') + pytest.raises(SyntaxError, df.eval, 'Timestamp("20131001") = a + b') # single assignment - existing variable expected = orig_df.copy() @@ -1290,7 +1289,7 @@ def f(): # multiple assignment df = orig_df.copy() df.eval('c = a + b', inplace=True) - self.assertRaises(SyntaxError, df.eval, 'c = a = b') + pytest.raises(SyntaxError, df.eval, 'c = a = b') # explicit targets df = orig_df.copy() @@ -1348,7 +1347,7 @@ def test_multi_line_expression(self): self.assertIsNone(ans) # multi-line not valid if not all assignments - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.eval(""" a = b + 2 b - 2""", inplace=False) @@ -1391,7 +1390,7 @@ def test_assignment_in_query(self): # GH 8664 df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}) df_orig = df.copy() - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.query('a = 1') assert_frame_equal(df, df_orig) @@ -1475,19 +1474,19 @@ def test_simple_in_ops(self): parser=self.parser) self.assertTrue(res) else: - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): pd.eval('1 in [1, 2]', engine=self.engine, parser=self.parser) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): pd.eval('2 in (1, 2)', engine=self.engine, parser=self.parser) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): pd.eval('3 in (1, 2)', engine=self.engine, parser=self.parser) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): pd.eval('3 not in (1, 2)', engine=self.engine, parser=self.parser) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): pd.eval('[(3,)] in (1, 2, [(3,)])', engine=self.engine, parser=self.parser) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): pd.eval('[3] not in (1, 2, [[3]])', engine=self.engine, parser=self.parser) @@ -1513,32 +1512,32 @@ def test_check_many_exprs(self): def test_fails_and(self): df = DataFrame(np.random.randn(5, 3)) - self.assertRaises(NotImplementedError, pd.eval, 'df > 2 and df > 3', - local_dict={'df': df}, parser=self.parser, - engine=self.engine) + pytest.raises(NotImplementedError, pd.eval, 'df > 2 and df > 3', + local_dict={'df': df}, parser=self.parser, + engine=self.engine) def test_fails_or(self): df = DataFrame(np.random.randn(5, 3)) - self.assertRaises(NotImplementedError, pd.eval, 'df > 2 or df > 3', - local_dict={'df': df}, parser=self.parser, - engine=self.engine) + pytest.raises(NotImplementedError, pd.eval, 'df > 2 or df > 3', + local_dict={'df': df}, parser=self.parser, + engine=self.engine) def test_fails_not(self): df = DataFrame(np.random.randn(5, 3)) - self.assertRaises(NotImplementedError, pd.eval, 'not df > 2', - local_dict={'df': df}, parser=self.parser, - engine=self.engine) + pytest.raises(NotImplementedError, pd.eval, 'not df > 2', + local_dict={'df': df}, parser=self.parser, + engine=self.engine) def test_fails_ampersand(self): df = DataFrame(np.random.randn(5, 3)) # noqa ex = '(df + 2)[df > 1] > 0 & (df > 0)' - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): pd.eval(ex, parser=self.parser, engine=self.engine) def test_fails_pipe(self): df = DataFrame(np.random.randn(5, 3)) # noqa ex = '(df + 2)[df > 1] > 0 | (df > 0)' - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): pd.eval(ex, parser=self.parser, engine=self.engine) def test_bool_ops_with_constants(self): @@ -1546,7 +1545,7 @@ def test_bool_ops_with_constants(self): ('True', 'False')): ex = '{0} {1} {2}'.format(lhs, op, rhs) if op in ('and', 'or'): - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): self.eval(ex) else: res = self.eval(ex) @@ -1558,7 +1557,7 @@ def test_simple_bool_ops(self): (True, False)): ex = 'lhs {0} rhs'.format(op) if op in ('and', 'or'): - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): pd.eval(ex, engine=self.engine, parser=self.parser) else: res = pd.eval(ex, engine=self.engine, parser=self.parser) @@ -1786,7 +1785,7 @@ def test_syntax_error_exprs(engine, parser): def test_name_error_exprs(engine, parser): e = 's + t' - with tm.assertRaises(NameError): + with pytest.raises(NameError): pd.eval(e, engine=engine, parser=parser) @@ -1847,7 +1846,7 @@ def test_bool_ops_fails_on_scalars(lhs, cmp, rhs, engine, parser): ex2 = 'lhs {0} mid and mid {1} rhs'.format(cmp, cmp) ex3 = '(lhs {0} mid) & (mid {1} rhs)'.format(cmp, cmp) for ex in (ex1, ex2, ex3): - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): pd.eval(ex, engine=engine, parser=parser) @@ -1866,7 +1865,7 @@ def test_negate_lt_eq_le(engine, parser): tm.assert_frame_equal(result, expected) if parser == 'python': - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): df.query('not (cat > 0)', engine=engine, parser=parser) else: result = df.query('not (cat > 0)', engine=engine, parser=parser) @@ -1879,5 +1878,5 @@ def test_validate_bool_args(self): invalid_values = [1, "True", [1, 2, 3], 5.0] for value in invalid_values: - with self.assertRaises(ValueError): + with pytest.raises(ValueError): pd.eval("2+2", inplace=value) diff --git a/pandas/tests/dtypes/test_cast.py b/pandas/tests/dtypes/test_cast.py index f3fdc54d4a3cc..bf3668111b9f9 100644 --- a/pandas/tests/dtypes/test_cast.py +++ b/pandas/tests/dtypes/test_cast.py @@ -293,7 +293,7 @@ def test_numpy_dtypes(self): for src, common in testcases: self.assertEqual(find_common_type(src), common) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): # empty find_common_type([]) diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py index 46569fecf553f..32ec1194639ae 100644 --- a/pandas/tests/dtypes/test_dtypes.py +++ b/pandas/tests/dtypes/test_dtypes.py @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +import pytest + from itertools import product import numpy as np @@ -25,23 +27,18 @@ def test_hash(self): hash(self.dtype) def test_equality_invalid(self): - self.assertRaises(self.dtype == 'foo') - self.assertFalse(is_dtype_equal(self.dtype, np.int64)) + assert not self.dtype == 'foo' + assert not is_dtype_equal(self.dtype, np.int64) def test_numpy_informed(self): + pytest.raises(TypeError, np.dtype, self.dtype) - # np.dtype doesn't know about our new dtype - def f(): - np.dtype(self.dtype) - - self.assertRaises(TypeError, f) - - self.assertNotEqual(self.dtype, np.str_) - self.assertNotEqual(np.str_, self.dtype) + assert not self.dtype == np.str_ + assert not np.str_ == self.dtype def test_pickle(self): result = tm.round_trip_pickle(self.dtype) - self.assertEqual(result, self.dtype) + assert result == self.dtype class TestCategoricalDtype(Base, tm.TestCase): @@ -67,7 +64,7 @@ def test_equality(self): def test_construction_from_string(self): result = CategoricalDtype.construct_from_string('category') self.assertTrue(is_dtype_equal(self.dtype, result)) - self.assertRaises( + pytest.raises( TypeError, lambda: CategoricalDtype.construct_from_string('foo')) def test_is_dtype(self): @@ -116,8 +113,8 @@ def test_hash_vs_equality(self): self.assertTrue(hash(dtype) == hash(dtype3)) def test_construction(self): - self.assertRaises(ValueError, - lambda: DatetimeTZDtype('ms', 'US/Eastern')) + pytest.raises(ValueError, + lambda: DatetimeTZDtype('ms', 'US/Eastern')) def test_subclass(self): a = DatetimeTZDtype('datetime64[ns, US/Eastern]') @@ -148,8 +145,8 @@ def test_construction_from_string(self): result = DatetimeTZDtype.construct_from_string( 'datetime64[ns, US/Eastern]') self.assertTrue(is_dtype_equal(self.dtype, result)) - self.assertRaises(TypeError, - lambda: DatetimeTZDtype.construct_from_string('foo')) + pytest.raises(TypeError, + lambda: DatetimeTZDtype.construct_from_string('foo')) def test_is_dtype(self): self.assertFalse(DatetimeTZDtype.is_dtype(None)) @@ -215,7 +212,7 @@ def test_parser(self): def test_empty(self): dt = DatetimeTZDtype() - with tm.assertRaises(AttributeError): + with pytest.raises(AttributeError): str(dt) @@ -225,7 +222,7 @@ def setUp(self): self.dtype = PeriodDtype('D') def test_construction(self): - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): PeriodDtype('xx') for s in ['period[D]', 'Period[D]', 'D']: @@ -284,16 +281,16 @@ def test_construction_from_string(self): self.assertTrue(is_dtype_equal(self.dtype, result)) result = PeriodDtype.construct_from_string('period[D]') self.assertTrue(is_dtype_equal(self.dtype, result)) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): PeriodDtype.construct_from_string('foo') - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): PeriodDtype.construct_from_string('period[foo]') - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): PeriodDtype.construct_from_string('foo[D]') - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): PeriodDtype.construct_from_string('datetime64[ns]') - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): PeriodDtype.construct_from_string('datetime64[ns, US/Eastern]') def test_is_dtype(self): @@ -348,7 +345,7 @@ def test_basic(self): def test_empty(self): dt = PeriodDtype() - with tm.assertRaises(AttributeError): + with pytest.raises(AttributeError): str(dt) def test_not_string(self): @@ -363,7 +360,7 @@ def setUp(self): self.dtype = IntervalDtype('int64') def test_construction(self): - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): IntervalDtype('xx') for s in ['interval[int64]', 'Interval[int64]', 'int64']: @@ -419,11 +416,11 @@ def test_construction_from_string(self): self.assertTrue(is_dtype_equal(self.dtype, result)) result = IntervalDtype.construct_from_string('interval[int64]') self.assertTrue(is_dtype_equal(self.dtype, result)) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): IntervalDtype.construct_from_string('foo') - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): IntervalDtype.construct_from_string('interval[foo]') - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): IntervalDtype.construct_from_string('foo[int64]') def test_equality(self): diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index 5f1eb8ff46259..f925022b6bd7f 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -2,6 +2,8 @@ from __future__ import print_function +import pytest + from datetime import datetime, timedelta import numpy as np @@ -396,7 +398,7 @@ def test_rename(self): tm.assert_index_equal(renamed.index, pd.Index(['BAR', 'FOO'])) # have to pass something - self.assertRaises(TypeError, self.frame.rename) + pytest.raises(TypeError, self.frame.rename) # partial columns renamed = self.frame.rename(columns={'C': 'foo', 'D': 'bar'}) diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 75a12ebaebf9d..703b93b9ec950 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -586,10 +586,10 @@ def test_numeric_only_flag(self): tm.assert_series_equal(expected, result) # df1 has all numbers, df2 has a letter inside - self.assertRaises(TypeError, lambda: getattr(df1, meth) - (axis=1, numeric_only=False)) - self.assertRaises(TypeError, lambda: getattr(df2, meth) - (axis=1, numeric_only=False)) + pytest.raises(TypeError, lambda: getattr(df1, meth)( + axis=1, numeric_only=False)) + pytest.raises(TypeError, lambda: getattr(df2, meth)( + axis=1, numeric_only=False)) def test_cumsum(self): self.tsframe.loc[5:10, 0] = nan @@ -998,7 +998,7 @@ def test_idxmin(self): skipna=skipna) tm.assert_series_equal(result, expected) - self.assertRaises(ValueError, frame.idxmin, axis=2) + pytest.raises(ValueError, frame.idxmin, axis=2) def test_idxmax(self): frame = self.frame @@ -1012,7 +1012,7 @@ def test_idxmax(self): skipna=skipna) tm.assert_series_equal(result, expected) - self.assertRaises(ValueError, frame.idxmax, axis=2) + pytest.raises(ValueError, frame.idxmax, axis=2) # ---------------------------------------------------------------------- # Logical reductions @@ -1087,7 +1087,7 @@ def wrapper(x): # assert_series_equal(result, comp) # bad axis - self.assertRaises(ValueError, f, axis=2) + pytest.raises(ValueError, f, axis=2) # make sure works on mixed-type frame mixed = self.mixed_frame @@ -1163,10 +1163,10 @@ def test_isin_with_string_scalar(self): df = DataFrame({'vals': [1, 2, 3, 4], 'ids': ['a', 'b', 'f', 'n'], 'ids2': ['a', 'n', 'c', 'n']}, index=['foo', 'bar', 'baz', 'qux']) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): df.isin('a') - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): df.isin('aaa') def test_isin_df(self): @@ -1189,18 +1189,18 @@ def test_isin_df_dupe_values(self): # just cols duped df2 = DataFrame([[0, 2], [12, 4], [2, np.nan], [4, 5]], columns=['B', 'B']) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df1.isin(df2) # just index duped df2 = DataFrame([[0, 2], [12, 4], [2, np.nan], [4, 5]], columns=['A', 'B'], index=[0, 0, 1, 1]) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df1.isin(df2) # cols and index: df2.columns = ['B', 'B'] - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df1.isin(df2) def test_isin_dupe_self(self): @@ -1629,7 +1629,7 @@ def test_round(self): # Round with a list round_list = [1, 2] - with self.assertRaises(TypeError): + with pytest.raises(TypeError): df.round(round_list) # Round with a dictionary @@ -1652,34 +1652,34 @@ def test_round(self): # float input to `decimals` non_int_round_dict = {'col1': 1, 'col2': 0.5} - with self.assertRaises(TypeError): + with pytest.raises(TypeError): df.round(non_int_round_dict) # String input non_int_round_dict = {'col1': 1, 'col2': 'foo'} - with self.assertRaises(TypeError): + with pytest.raises(TypeError): df.round(non_int_round_dict) non_int_round_Series = Series(non_int_round_dict) - with self.assertRaises(TypeError): + with pytest.raises(TypeError): df.round(non_int_round_Series) # List input non_int_round_dict = {'col1': 1, 'col2': [1, 2]} - with self.assertRaises(TypeError): + with pytest.raises(TypeError): df.round(non_int_round_dict) non_int_round_Series = Series(non_int_round_dict) - with self.assertRaises(TypeError): + with pytest.raises(TypeError): df.round(non_int_round_Series) # Non integer Series inputs non_int_round_Series = Series(non_int_round_dict) - with self.assertRaises(TypeError): + with pytest.raises(TypeError): df.round(non_int_round_Series) non_int_round_Series = Series(non_int_round_dict) - with self.assertRaises(TypeError): + with pytest.raises(TypeError): df.round(non_int_round_Series) # Negative numbers @@ -1700,10 +1700,10 @@ def test_round(self): if sys.version < LooseVersion('2.7'): # Rounding with decimal is a ValueError in Python < 2.7 - with self.assertRaises(ValueError): + with pytest.raises(ValueError): df.round(nan_round_Series) else: - with self.assertRaises(TypeError): + with pytest.raises(TypeError): df.round(nan_round_Series) # Make sure this doesn't break existing Series.round @@ -1761,7 +1761,7 @@ def test_round_issue(self): tm.assert_index_equal(rounded.index, dfs.index) decimals = pd.Series([1, 0, 2], index=['A', 'B', 'A']) - self.assertRaises(ValueError, df.round, decimals) + pytest.raises(ValueError, df.round, decimals) def test_built_in_round(self): if not compat.PY3: diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index c8d36e01d5205..879458a38770d 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -1,6 +1,9 @@ # -*- coding: utf-8 -*- from __future__ import print_function + +import pytest + # pylint: disable-msg=W0612,E1101 from copy import deepcopy import sys @@ -106,8 +109,8 @@ def test_column_contains_typeerror(self): def test_not_hashable(self): df = pd.DataFrame([1]) - self.assertRaises(TypeError, hash, df) - self.assertRaises(TypeError, hash, self.empty) + pytest.raises(TypeError, hash, df) + pytest.raises(TypeError, hash, self.empty) def test_new_empty_index(self): df1 = DataFrame(randn(0, 3)) @@ -131,7 +134,7 @@ def test_get_agg_axis(self): idx = self.frame._get_agg_axis(1) self.assertIs(idx, self.frame.index) - self.assertRaises(ValueError, self.frame._get_agg_axis, 2) + pytest.raises(ValueError, self.frame._get_agg_axis, 2) def test_nonzero(self): self.assertTrue(self.empty.empty) @@ -278,7 +281,7 @@ def test_swapaxes(self): assert_frame_equal(df.T, df.swapaxes(0, 1)) assert_frame_equal(df.T, df.swapaxes(1, 0)) assert_frame_equal(df, df.swapaxes(0, 0)) - self.assertRaises(ValueError, df.swapaxes, 2, 5) + pytest.raises(ValueError, df.swapaxes, 2, 5) def test_axis_aliases(self): f = self.frame diff --git a/pandas/tests/frame/test_apply.py b/pandas/tests/frame/test_apply.py index 89bb0e1fdf5b2..d31fb4218adeb 100644 --- a/pandas/tests/frame/test_apply.py +++ b/pandas/tests/frame/test_apply.py @@ -2,6 +2,8 @@ from __future__ import print_function +import pytest + from datetime import datetime import warnings @@ -37,7 +39,7 @@ def test_apply(self): # invalid axis df = DataFrame( [[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=['a', 'a', 'c']) - self.assertRaises(ValueError, df.apply, lambda x: x, 2) + pytest.raises(ValueError, df.apply, lambda x: x, 2) # GH9573 df = DataFrame({'c0': ['A', 'A', 'B', 'B'], @@ -528,17 +530,17 @@ def test_transform_and_agg_err(self): # cannot both transform and agg def f(): self.frame.transform(['max', 'min']) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def f(): with np.errstate(all='ignore'): self.frame.agg(['max', 'sqrt']) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def f(): with np.errstate(all='ignore'): self.frame.transform(['max', 'sqrt']) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) df = pd.DataFrame({'A': range(5), 'B': 5}) diff --git a/pandas/tests/frame/test_axis_select_reindex.py b/pandas/tests/frame/test_axis_select_reindex.py index 9b3dc11ea3be2..2f914472a1152 100644 --- a/pandas/tests/frame/test_axis_select_reindex.py +++ b/pandas/tests/frame/test_axis_select_reindex.py @@ -43,8 +43,8 @@ def test_drop_names(self): self.assertEqual(obj.columns.name, 'second') self.assertEqual(list(df.columns), ['d', 'e', 'f']) - self.assertRaises(ValueError, df.drop, ['g']) - self.assertRaises(ValueError, df.drop, ['g'], 1) + pytest.raises(ValueError, df.drop, ['g']) + pytest.raises(ValueError, df.drop, ['g'], 1) # errors = 'ignore' dropped = df.drop(['g'], errors='ignore') @@ -84,10 +84,10 @@ def test_drop(self): assert_frame_equal(simple.drop( [0, 3], axis='index'), simple.loc[[1, 2], :]) - self.assertRaises(ValueError, simple.drop, 5) - self.assertRaises(ValueError, simple.drop, 'C', 1) - self.assertRaises(ValueError, simple.drop, [1, 5]) - self.assertRaises(ValueError, simple.drop, ['A', 'C'], 1) + pytest.raises(ValueError, simple.drop, 5) + pytest.raises(ValueError, simple.drop, 'C', 1) + pytest.raises(ValueError, simple.drop, [1, 5]) + pytest.raises(ValueError, simple.drop, ['A', 'C'], 1) # errors = 'ignore' assert_frame_equal(simple.drop(5, errors='ignore'), simple) @@ -407,7 +407,7 @@ def test_reindex_dups(self): assert_frame_equal(result, expected) # reindex fails - self.assertRaises(ValueError, df.reindex, index=list(range(len(df)))) + pytest.raises(ValueError, df.reindex, index=list(range(len(df)))) def test_align(self): af, bf = self.frame.align(self.frame) @@ -798,10 +798,10 @@ def test_take(self): assert_frame_equal(result, expected, check_names=False) # illegal indices - self.assertRaises(IndexError, df.take, [3, 1, 2, 30], axis=0) - self.assertRaises(IndexError, df.take, [3, 1, 2, -31], axis=0) - self.assertRaises(IndexError, df.take, [3, 1, 2, 5], axis=1) - self.assertRaises(IndexError, df.take, [3, 1, 2, -5], axis=1) + pytest.raises(IndexError, df.take, [3, 1, 2, 30], axis=0) + pytest.raises(IndexError, df.take, [3, 1, 2, -31], axis=0) + pytest.raises(IndexError, df.take, [3, 1, 2, 5], axis=1) + pytest.raises(IndexError, df.take, [3, 1, 2, -5], axis=1) # mixed-dtype order = [4, 1, 2, 0, 3] @@ -883,7 +883,7 @@ def test_reindex_axis(self): reindexed2 = self.intframe.reindex(index=rows) assert_frame_equal(reindexed1, reindexed2) - self.assertRaises(ValueError, self.intframe.reindex_axis, rows, axis=2) + pytest.raises(ValueError, self.intframe.reindex_axis, rows, axis=2) # no-op case cols = self.frame.columns.copy() diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py index 0b707a2896e95..63c1f0a50fbed 100644 --- a/pandas/tests/frame/test_block_internals.py +++ b/pandas/tests/frame/test_block_internals.py @@ -2,6 +2,8 @@ from __future__ import print_function +import pytest + from datetime import datetime, timedelta import itertools @@ -285,10 +287,10 @@ def f(dtype): columns=["A", "B", "C"], dtype=dtype) - self.assertRaises(NotImplementedError, f, - [("A", "datetime64[h]"), - ("B", "str"), - ("C", "int32")]) + pytest.raises(NotImplementedError, f, + [("A", "datetime64[h]"), + ("B", "str"), + ("C", "int32")]) # these work (though results may be unexpected) f('int64') diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 29d742b2b79e2..d253fc2049462 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -61,8 +61,8 @@ def test_constructor_cast_failure(self): df['foo'] = np.ones((4, 2)).tolist() # this is not ok - self.assertRaises(ValueError, df.__setitem__, tuple(['test']), - np.ones((4, 2))) + pytest.raises(ValueError, df.__setitem__, tuple(['test']), + np.ones((4, 2))) # this is ok df['foo2'] = np.ones((4, 2)).tolist() @@ -232,7 +232,7 @@ def test_constructor_dict(self): # mix dict and array, wrong size - no spec for which error should raise # first - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): DataFrame({'A': {'a': 'a', 'b': 'b'}, 'B': ['a', 'b', 'c']}) # Length-one dict micro-optimization @@ -265,13 +265,13 @@ def test_constructor_dict(self): # GH10856 # dict with scalar values should raise error, even if columns passed - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): DataFrame({'a': 0.7}) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): DataFrame({'a': 0.7}, columns=['a']) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): DataFrame({'a': 0.7}, columns=['b']) def test_constructor_multi_index(self): @@ -1087,7 +1087,7 @@ def test_constructor_Series_named(self): expected = DataFrame({0: s}) tm.assert_frame_equal(df, expected) - self.assertRaises(ValueError, DataFrame, s, columns=[1, 2]) + pytest.raises(ValueError, DataFrame, s, columns=[1, 2]) # #2234 a = Series([], name='x') @@ -1207,9 +1207,9 @@ def test_constructor_column_duplicates(self): [('a', [8]), ('a', [5])], columns=['a', 'a']) tm.assert_frame_equal(idf, edf) - self.assertRaises(ValueError, DataFrame.from_items, - [('a', [8]), ('a', [5]), ('b', [6])], - columns=['b', 'a', 'a']) + pytest.raises(ValueError, DataFrame.from_items, + [('a', [8]), ('a', [5]), ('b', [6])], + columns=['b', 'a', 'a']) def test_constructor_empty_with_string_dtype(self): # GH 9428 @@ -1240,8 +1240,8 @@ def test_constructor_single_value(self): dtype=object), index=[1, 2], columns=['a', 'c'])) - self.assertRaises(ValueError, DataFrame, 'a', [1, 2]) - self.assertRaises(ValueError, DataFrame, 'a', columns=['a', 'c']) + pytest.raises(ValueError, DataFrame, 'a', [1, 2]) + pytest.raises(ValueError, DataFrame, 'a', columns=['a', 'c']) with tm.assertRaisesRegexp(TypeError, 'incompatible data and dtype'): DataFrame('a', [1, 2], ['a', 'c'], float) @@ -1486,7 +1486,7 @@ def check(df): def f(): df.loc[:, np.nan] - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) df = DataFrame([[1, 2, 3], [4, 5, 6]], index=[1, np.nan]) check(df) @@ -1857,8 +1857,8 @@ def test_from_records_bad_index_column(self): tm.assert_index_equal(df1.index, Index(df.C)) # should fail - self.assertRaises(ValueError, DataFrame.from_records, df, index=[2]) - self.assertRaises(KeyError, DataFrame.from_records, df, index=2) + pytest.raises(ValueError, DataFrame.from_records, df, index=[2]) + pytest.raises(KeyError, DataFrame.from_records, df, index=2) def test_from_records_non_tuple(self): class Record(object): diff --git a/pandas/tests/frame/test_convert_to.py b/pandas/tests/frame/test_convert_to.py index 24a0e9c866eaf..64edc52508216 100644 --- a/pandas/tests/frame/test_convert_to.py +++ b/pandas/tests/frame/test_convert_to.py @@ -111,7 +111,7 @@ def test_to_dict_timestamp(self): def test_to_dict_invalid_orient(self): df = DataFrame({'A': [0, 1]}) - self.assertRaises(ValueError, df.to_dict, orient='xinvalid') + pytest.raises(ValueError, df.to_dict, orient='xinvalid') def test_to_records_dt64(self): df = DataFrame([["one", "two", "three"], diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py index c38b411097420..99141e3a8e1c4 100644 --- a/pandas/tests/frame/test_dtypes.py +++ b/pandas/tests/frame/test_dtypes.py @@ -1,6 +1,9 @@ # -*- coding: utf-8 -*- from __future__ import print_function + +import pytest + from datetime import timedelta import numpy as np @@ -146,8 +149,8 @@ def test_select_dtypes_include(self): ei = df[['k']] assert_frame_equal(ri, ei) - self.assertRaises(NotImplementedError, - lambda: df.select_dtypes(include=['period'])) + pytest.raises(NotImplementedError, + lambda: df.select_dtypes(include=['period'])) def test_select_dtypes_exclude(self): df = DataFrame({'a': list('abc'), @@ -470,8 +473,8 @@ def test_astype_dict(self): # error should be raised when using something other than column labels # in the keys of the dtype dict - self.assertRaises(KeyError, df.astype, {'b': str, 2: str}) - self.assertRaises(KeyError, df.astype, {'e': str}) + pytest.raises(KeyError, df.astype, {'b': str, 2: str}) + pytest.raises(KeyError, df.astype, {'e': str}) assert_frame_equal(df, original) # if the dtypes provided are the same as the original dtypes, the @@ -526,7 +529,7 @@ def test_arg_for_errors_in_astype(self): df = DataFrame([1, 2, 3]) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): df.astype(np.float64, errors=True) with tm.assert_produces_warning(FutureWarning): diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index d25a62c5e5932..780cb3d0457bd 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -29,8 +29,7 @@ from pandas.util.testing import (assert_almost_equal, assert_series_equal, assert_frame_equal, - assertRaisesRegexp, - assertRaises) + assertRaisesRegexp) from pandas.core.indexing import IndexingError import pandas.util.testing as tm @@ -410,8 +409,8 @@ def test_getitem_setitem_ix_negative_integers(self): def test_getattr(self): assert_series_equal(self.frame.A, self.frame['A']) - self.assertRaises(AttributeError, getattr, self.frame, - 'NONEXISTENT_NAME') + pytest.raises(AttributeError, getattr, self.frame, + 'NONEXISTENT_NAME') def test_setattr_column(self): df = DataFrame({'foobar': 1}, index=lrange(10)) @@ -436,7 +435,7 @@ def test_setitem(self): self.frame['col6'] = series tm.assert_series_equal(series, self.frame['col6'], check_names=False) - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): self.frame[randn(len(self.frame) + 1)] = 1 # set ndarray @@ -459,7 +458,7 @@ def test_setitem(self): def f(): smaller['col10'] = ['1', '2'] - self.assertRaises(com.SettingWithCopyError, f) + pytest.raises(com.SettingWithCopyError, f) self.assertEqual(smaller['col10'].dtype, np.object_) self.assertTrue((smaller['col10'] == ['1', '2']).all()) @@ -732,7 +731,7 @@ def test_delitem_corner(self): f = self.frame.copy() del f['D'] self.assertEqual(len(f.columns), 3) - self.assertRaises(KeyError, f.__delitem__, 'D') + pytest.raises(KeyError, f.__delitem__, 'D') del f['B'] self.assertEqual(len(f.columns), 2) @@ -774,7 +773,7 @@ def test_getitem_fancy_2d(self): assert_frame_equal(f, exp) with catch_warnings(record=True): - self.assertRaises(ValueError, f.ix.__getitem__, f > 0.5) + pytest.raises(ValueError, f.ix.__getitem__, f > 0.5) def test_slice_floats(self): index = [52195.504153, 52196.303147, 52198.369883] @@ -819,8 +818,8 @@ def test_getitem_setitem_integer_slice_keyerrors(self): # non-monotonic, raise KeyError df2 = df.iloc[lrange(5) + lrange(5, 10)[::-1]] - self.assertRaises(KeyError, df2.loc.__getitem__, slice(3, 11)) - self.assertRaises(KeyError, df2.loc.__setitem__, slice(3, 11), 0) + pytest.raises(KeyError, df2.loc.__getitem__, slice(3, 11)) + pytest.raises(KeyError, df2.loc.__setitem__, slice(3, 11), 0) def test_setitem_fancy_2d(self): @@ -938,7 +937,7 @@ def test_fancy_getitem_slice_mixed(self): def f(): sliced['C'] = 4. - self.assertRaises(com.SettingWithCopyError, f) + pytest.raises(com.SettingWithCopyError, f) self.assertTrue((self.frame['C'] == 4).all()) def test_fancy_setitem_int_labels(self): @@ -999,21 +998,18 @@ def test_fancy_index_int_labels_exceptions(self): with catch_warnings(record=True): # labels that aren't contained - self.assertRaises(KeyError, df.ix.__setitem__, - ([0, 1, 2], [2, 3, 4]), 5) + pytest.raises(KeyError, df.ix.__setitem__, + ([0, 1, 2], [2, 3, 4]), 5) # try to set indices not contained in frame - self.assertRaises(KeyError, - self.frame.ix.__setitem__, - ['foo', 'bar', 'baz'], 1) - self.assertRaises(KeyError, - self.frame.ix.__setitem__, - (slice(None, None), ['E']), 1) + pytest.raises(KeyError, self.frame.ix.__setitem__, + ['foo', 'bar', 'baz'], 1) + pytest.raises(KeyError, self.frame.ix.__setitem__, + (slice(None, None), ['E']), 1) # partial setting now allows this GH2578 - # self.assertRaises(KeyError, - # self.frame.ix.__setitem__, - # (slice(None, None), 'E'), 1) + # pytest.raises(KeyError, self.frame.ix.__setitem__, + # (slice(None, None), 'E'), 1) def test_setitem_fancy_mixed_2d(self): @@ -1357,7 +1353,7 @@ def test_getitem_setitem_fancy_exceptions(self): with assertRaisesRegexp(IndexingError, 'Too many indexers'): ix[:, :, :] - with assertRaises(IndexingError): + with pytest.raises(IndexingError): ix[:, :, :] = 1 def test_getitem_setitem_boolean_misaligned(self): @@ -1423,7 +1419,7 @@ def test_getitem_setitem_float_labels(self): df = DataFrame(np.random.randn(5, 5), index=index) # positional slicing only via iloc! - self.assertRaises(TypeError, lambda: df.iloc[1.0:5]) + pytest.raises(TypeError, lambda: df.iloc[1.0:5]) result = df.iloc[4:5] expected = df.reindex([5.0]) @@ -1434,12 +1430,12 @@ def test_getitem_setitem_float_labels(self): def f(): cp.iloc[1.0:5] = 0 - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def f(): result = cp.iloc[1.0:5] == 0 # noqa - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) self.assertTrue(result.values.all()) self.assertTrue((cp.iloc[0:1] == df.iloc[0:1]).values.all()) @@ -1507,7 +1503,7 @@ def test_setitem_single_column_mixed_datetime(self): # as of GH 3216 this will now work! # try to set with a list like item - # self.assertRaises( + # pytest.raises( # Exception, df.loc.__setitem__, ('d', 'timestamp'), [nan]) def test_setitem_frame(self): @@ -1612,11 +1608,11 @@ def test_getitem_setitem_ix_bool_keyerror(self): # #2199 df = DataFrame({'a': [1, 2, 3]}) - self.assertRaises(KeyError, df.loc.__getitem__, False) - self.assertRaises(KeyError, df.loc.__getitem__, True) + pytest.raises(KeyError, df.loc.__getitem__, False) + pytest.raises(KeyError, df.loc.__getitem__, True) - self.assertRaises(KeyError, df.loc.__setitem__, False, 0) - self.assertRaises(KeyError, df.loc.__setitem__, True, 0) + pytest.raises(KeyError, df.loc.__setitem__, False, 0) + pytest.raises(KeyError, df.loc.__setitem__, True, 0) def test_getitem_list_duplicates(self): # #1943 @@ -1662,10 +1658,10 @@ def testit(df): tm.assert_series_equal(df['mask'], pd.Series(exp_mask, name='mask')) self.assertEqual(df['mask'].dtype, np.bool_) - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): self.frame.lookup(['xyz'], ['A']) - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): self.frame.lookup([self.frame.index[0]], ['xyz']) with tm.assertRaisesRegexp(ValueError, 'same size'): @@ -1699,7 +1695,7 @@ def test_set_value_resize(self): res3 = res.set_value('foobar', 'baz', 5) self.assertTrue(is_float_dtype(res3['baz'])) self.assertTrue(isnull(res3['baz'].drop(['foobar'])).all()) - self.assertRaises(ValueError, res3.set_value, 'foobar', 'baz', 'sam') + pytest.raises(ValueError, res3.set_value, 'foobar', 'baz', 'sam') def test_set_value_with_index_dtype_change(self): df_orig = DataFrame(randn(3, 3), index=lrange(3), columns=list('ABC')) @@ -1731,8 +1727,8 @@ def test_get_set_value_no_partial_indexing(self): # partial w/ MultiIndex raise exception index = MultiIndex.from_tuples([(0, 1), (0, 2), (1, 1), (1, 2)]) df = DataFrame(index=index, columns=lrange(4)) - self.assertRaises(KeyError, df.get_value, 0, 1) - # self.assertRaises(KeyError, df.set_value, 0, 1, 0) + pytest.raises(KeyError, df.get_value, 0, 1) + # pytest.raises(KeyError, df.set_value, 0, 1, 0) def test_single_element_ix_dont_upcast(self): self.frame['E'] = 1 @@ -1783,7 +1779,7 @@ def test_iloc_row(self): # setting it makes it raise/warn def f(): result[2] = 0. - self.assertRaises(com.SettingWithCopyError, f) + pytest.raises(com.SettingWithCopyError, f) exp_col = df[2].copy() exp_col[4:8] = 0. assert_series_equal(df[2], exp_col) @@ -1814,7 +1810,7 @@ def test_iloc_col(self): # and that we are setting a copy def f(): result[8] = 0. - self.assertRaises(com.SettingWithCopyError, f) + pytest.raises(com.SettingWithCopyError, f) self.assertTrue((df[8] == 0).all()) # list of integers @@ -1954,11 +1950,10 @@ def test_non_monotonic_reindex_methods(self): df_rev = pd.DataFrame(data, index=dr[[3, 4, 5] + [0, 1, 2]], columns=list('A')) # index is not monotonic increasing or decreasing - self.assertRaises(ValueError, df_rev.reindex, df.index, method='pad') - self.assertRaises(ValueError, df_rev.reindex, df.index, method='ffill') - self.assertRaises(ValueError, df_rev.reindex, df.index, method='bfill') - self.assertRaises(ValueError, df_rev.reindex, - df.index, method='nearest') + pytest.raises(ValueError, df_rev.reindex, df.index, method='pad') + pytest.raises(ValueError, df_rev.reindex, df.index, method='ffill') + pytest.raises(ValueError, df_rev.reindex, df.index, method='bfill') + pytest.raises(ValueError, df_rev.reindex, df.index, method='nearest') def test_reindex_level(self): from itertools import permutations @@ -2197,7 +2192,7 @@ def test_xs(self): self.assertEqual(xs['A'], 1) self.assertEqual(xs['B'], '1') - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): self.tsframe.xs(self.tsframe.index[0] - BDay()) # xs get column @@ -2423,14 +2418,14 @@ def _check_align(df, cond, other, check_dtypes=True): # invalid conditions df = default_frame err1 = (df + 1).values[0:2, :] - self.assertRaises(ValueError, df.where, cond, err1) + pytest.raises(ValueError, df.where, cond, err1) err2 = cond.iloc[:2, :].values other1 = _safe_add(df) - self.assertRaises(ValueError, df.where, err2, other1) + pytest.raises(ValueError, df.where, err2, other1) - self.assertRaises(ValueError, df.mask, True) - self.assertRaises(ValueError, df.mask, 0) + pytest.raises(ValueError, df.mask, True) + pytest.raises(ValueError, df.mask, 0) # where inplace def _check_set(df, cond, check_dtypes=True): diff --git a/pandas/tests/frame/test_missing.py b/pandas/tests/frame/test_missing.py index 9aca810a4d298..74f1d3292fa4e 100644 --- a/pandas/tests/frame/test_missing.py +++ b/pandas/tests/frame/test_missing.py @@ -2,6 +2,8 @@ from __future__ import print_function +import pytest + from distutils.version import LooseVersion from numpy import nan, random import numpy as np @@ -139,7 +141,7 @@ def test_dropna(self): assert_frame_equal(dropped, expected) # bad input - self.assertRaises(ValueError, df.dropna, axis=3) + pytest.raises(ValueError, df.dropna, axis=3) def test_drop_and_dropna_caching(self): # tst that cacher updates @@ -158,10 +160,10 @@ def test_drop_and_dropna_caching(self): def test_dropna_corner(self): # bad input - self.assertRaises(ValueError, self.frame.dropna, how='foo') - self.assertRaises(TypeError, self.frame.dropna, how=None) + pytest.raises(ValueError, self.frame.dropna, how='foo') + pytest.raises(TypeError, self.frame.dropna, how=None) # non-existent column - 8303 - self.assertRaises(KeyError, self.frame.dropna, subset=['A', 'X']) + pytest.raises(KeyError, self.frame.dropna, subset=['A', 'X']) def test_dropna_multiple_axes(self): df = DataFrame([[1, np.nan, 2, 3], @@ -202,8 +204,8 @@ def test_fillna(self): result = self.mixed_frame.fillna(value=0) result = self.mixed_frame.fillna(method='pad') - self.assertRaises(ValueError, self.tsframe.fillna) - self.assertRaises(ValueError, self.tsframe.fillna, 5, method='ffill') + pytest.raises(ValueError, self.tsframe.fillna) + pytest.raises(ValueError, self.tsframe.fillna, 5, method='ffill') # mixed numeric (but no float16) mf = self.mixed_float.reindex(columns=['A', 'B', 'D']) @@ -482,12 +484,11 @@ def test_fillna_invalid_method(self): def test_fillna_invalid_value(self): # list - self.assertRaises(TypeError, self.frame.fillna, [1, 2]) + pytest.raises(TypeError, self.frame.fillna, [1, 2]) # tuple - self.assertRaises(TypeError, self.frame.fillna, (1, 2)) + pytest.raises(TypeError, self.frame.fillna, (1, 2)) # frame with series - self.assertRaises(ValueError, self.frame.iloc[:, 0].fillna, - self.frame) + pytest.raises(ValueError, self.frame.iloc[:, 0].fillna, self.frame) def test_fillna_col_reordering(self): cols = ["COL." + str(i) for i in range(5, 0, -1)] @@ -545,7 +546,7 @@ def test_interp_bad_method(self): 'B': [1, 4, 9, np.nan], 'C': [1, 2, 3, 5], 'D': list('abcd')}) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.interpolate(method='not_a_method') def test_interp_combo(self): @@ -565,7 +566,7 @@ def test_interp_combo(self): def test_interp_nan_idx(self): df = DataFrame({'A': [1, 2, np.nan, 4], 'B': [np.nan, 2, 3, 4]}) df = df.set_index('A') - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): df.interpolate(method='values') def test_interp_various(self): @@ -693,7 +694,7 @@ def test_interp_raise_on_only_mixed(self): 'C': [np.nan, 2, 5, 7], 'D': [np.nan, np.nan, 9, 9], 'E': [1, 2, 3, 4]}) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): df.interpolate(axis=1) def test_interp_inplace(self): diff --git a/pandas/tests/frame/test_mutate_columns.py b/pandas/tests/frame/test_mutate_columns.py index f8de29cb63ebb..a7da704e73764 100644 --- a/pandas/tests/frame/test_mutate_columns.py +++ b/pandas/tests/frame/test_mutate_columns.py @@ -76,13 +76,13 @@ def test_assign_alphabetical(self): def test_assign_bad(self): df = DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) # non-keyword argument - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): df.assign(lambda x: x.A) - with tm.assertRaises(AttributeError): + with pytest.raises(AttributeError): df.assign(C=df.A, D=df.A + df.C) - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): df.assign(C=lambda df: df.A, D=lambda df: df['A'] + df['C']) - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): df.assign(C=df.A, D=lambda x: x['A'] + x['C']) def test_insert_error_msmgs(self): @@ -147,7 +147,7 @@ def test_insert(self): with assertRaisesRegexp(ValueError, 'already exists'): df.insert(1, 'a', df['b']) - self.assertRaises(ValueError, df.insert, 1, 'c', df['b']) + pytest.raises(ValueError, df.insert, 1, 'c', df['b']) df.columns.name = 'some_name' # preserve columns name field diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py index bb7c7c2bd012d..9d5a99eaf2e9d 100644 --- a/pandas/tests/frame/test_nonunique_indexes.py +++ b/pandas/tests/frame/test_nonunique_indexes.py @@ -2,6 +2,7 @@ from __future__ import print_function +import pytest import numpy as np from pandas.compat import lrange, u @@ -189,8 +190,8 @@ def check(result, expected=None): # reindex is invalid! df = DataFrame([[1, 5, 7.], [1, 5, 7.], [1, 5, 7.]], columns=['bar', 'a', 'a']) - self.assertRaises(ValueError, df.reindex, columns=['bar']) - self.assertRaises(ValueError, df.reindex, columns=['bar', 'foo']) + pytest.raises(ValueError, df.reindex, columns=['bar']) + pytest.raises(ValueError, df.reindex, columns=['bar', 'foo']) # drop df = DataFrame([[1, 5, 7.], [1, 5, 7.], [1, 5, 7.]], @@ -307,7 +308,7 @@ def check(result, expected=None): # boolean with the duplicate raises df = DataFrame(np.arange(12).reshape(3, 4), columns=dups, dtype='float64') - self.assertRaises(ValueError, lambda: df[df.A > 6]) + pytest.raises(ValueError, lambda: df[df.A > 6]) # dup aligining operations should work # GH 5185 @@ -324,7 +325,7 @@ def check(result, expected=None): columns=['A', 'A']) # not-comparing like-labelled - self.assertRaises(ValueError, lambda: df1 == df2) + pytest.raises(ValueError, lambda: df1 == df2) df1r = df1.reindex_like(df2) result = df1r == df2 @@ -411,7 +412,7 @@ def test_columns_with_dups(self): assert_frame_equal(df, expected) # this is an error because we cannot disambiguate the dup columns - self.assertRaises(Exception, lambda x: DataFrame( + pytest.raises(Exception, lambda x: DataFrame( [[1, 2, 'foo', 'bar']], columns=['a', 'a', 'a', 'a'])) # dups across blocks diff --git a/pandas/tests/frame/test_operators.py b/pandas/tests/frame/test_operators.py index 01e930fee959d..ce756ca188bf0 100644 --- a/pandas/tests/frame/test_operators.py +++ b/pandas/tests/frame/test_operators.py @@ -119,12 +119,12 @@ def test_operators_boolean(self): def f(): DataFrame(1.0, index=[1], columns=['A']) | DataFrame( True, index=[1], columns=['A']) - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def f(): DataFrame('foo', index=[1], columns=['A']) | DataFrame( True, index=[1], columns=['A']) - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def test_operators_none_as_na(self): df = DataFrame({"col1": [2, 5.0, 123, None], @@ -157,12 +157,12 @@ def test_comparison_invalid(self): def check(df, df2): for (x, y) in [(df, df2), (df2, df)]: - self.assertRaises(TypeError, lambda: x == y) - self.assertRaises(TypeError, lambda: x != y) - self.assertRaises(TypeError, lambda: x >= y) - self.assertRaises(TypeError, lambda: x > y) - self.assertRaises(TypeError, lambda: x < y) - self.assertRaises(TypeError, lambda: x <= y) + pytest.raises(TypeError, lambda: x == y) + pytest.raises(TypeError, lambda: x != y) + pytest.raises(TypeError, lambda: x >= y) + pytest.raises(TypeError, lambda: x > y) + pytest.raises(TypeError, lambda: x < y) + pytest.raises(TypeError, lambda: x <= y) # GH4968 # invalid date/int comparisons @@ -318,10 +318,10 @@ def _check_unary_op(op): def test_logical_typeerror(self): if not compat.PY3: - self.assertRaises(TypeError, self.frame.__eq__, 'foo') - self.assertRaises(TypeError, self.frame.__lt__, 'foo') - self.assertRaises(TypeError, self.frame.__gt__, 'foo') - self.assertRaises(TypeError, self.frame.__ne__, 'foo') + pytest.raises(TypeError, self.frame.__eq__, 'foo') + pytest.raises(TypeError, self.frame.__lt__, 'foo') + pytest.raises(TypeError, self.frame.__gt__, 'foo') + pytest.raises(TypeError, self.frame.__ne__, 'foo') else: pytest.skip('test_logical_typeerror not tested on PY3') @@ -968,7 +968,7 @@ def test_float_none_comparison(self): df = DataFrame(np.random.randn(8, 3), index=lrange(8), columns=['A', 'B', 'C']) - self.assertRaises(TypeError, df.__eq__, None) + pytest.raises(TypeError, df.__eq__, None) def test_boolean_comparison(self): @@ -1001,8 +1001,8 @@ def test_boolean_comparison(self): result = df.values > b_r assert_numpy_array_equal(result, expected.values) - self.assertRaises(ValueError, df.__gt__, b_c) - self.assertRaises(ValueError, df.values.__gt__, b_c) + pytest.raises(ValueError, df.__gt__, b_c) + pytest.raises(ValueError, df.values.__gt__, b_c) # == expected = DataFrame([[False, False], [True, False], [False, False]]) @@ -1021,7 +1021,7 @@ def test_boolean_comparison(self): result = df.values == b_r assert_numpy_array_equal(result, expected.values) - self.assertRaises(ValueError, lambda: df == b_c) + pytest.raises(ValueError, lambda: df == b_c) self.assertFalse(np.array_equal(df.values, b_c)) # with alignment @@ -1037,8 +1037,8 @@ def test_boolean_comparison(self): assert_frame_equal(result, expected) # not shape compatible - self.assertRaises(ValueError, lambda: df == (2, 2)) - self.assertRaises(ValueError, lambda: df == [2, 2]) + pytest.raises(ValueError, lambda: df == (2, 2)) + pytest.raises(ValueError, lambda: df == [2, 2]) def test_combine_generic(self): df1 = self.frame @@ -1203,7 +1203,7 @@ def test_alignment_non_pandas(self): align(df, val, 'columns') val = np.zeros((3, 3, 3)) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): align(df, val, 'index') - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): align(df, val, 'columns') diff --git a/pandas/tests/frame/test_quantile.py b/pandas/tests/frame/test_quantile.py index 909a1a6a4c917..738ddb89db652 100644 --- a/pandas/tests/frame/test_quantile.py +++ b/pandas/tests/frame/test_quantile.py @@ -77,7 +77,7 @@ def test_quantile_axis_mixed(self): # must raise def f(): df.quantile(.5, axis=1, numeric_only=False) - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def test_quantile_axis_parameter(self): # GH 9543/9544 @@ -100,8 +100,8 @@ def test_quantile_axis_parameter(self): result = df.quantile(.5, axis="columns") assert_series_equal(result, expected) - self.assertRaises(ValueError, df.quantile, 0.1, axis=-1) - self.assertRaises(ValueError, df.quantile, 0.1, axis="column") + pytest.raises(ValueError, df.quantile, 0.1, axis=-1) + pytest.raises(ValueError, df.quantile, 0.1, axis="column") def test_quantile_interpolation(self): # GH #10174 diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py index a531b86699e90..b787d63d3c754 100644 --- a/pandas/tests/frame/test_query_eval.py +++ b/pandas/tests/frame/test_query_eval.py @@ -15,7 +15,6 @@ from pandas.util.testing import (assert_series_equal, assert_frame_equal, - assertRaises, makeCustomDataframe as mkdf) import pandas.util.testing as tm @@ -82,10 +81,10 @@ def test_query_numexpr(self): result = df.eval('A+1', engine='numexpr') assert_series_equal(result, self.expected2, check_names=False) else: - self.assertRaises(ImportError, - lambda: df.query('A>0', engine='numexpr')) - self.assertRaises(ImportError, - lambda: df.eval('A+1', engine='numexpr')) + pytest.raises(ImportError, + lambda: df.query('A>0', engine='numexpr')) + pytest.raises(ImportError, + lambda: df.eval('A+1', engine='numexpr')) class TestDataFrameEval(tm.TestCase, TestData): @@ -384,7 +383,7 @@ def check_raise_on_panel_with_multiindex(self, parser, engine): tm.skip_if_no_ne() p = tm.makePanel(7) p.items = tm.makeCustomIndex(len(p.items), nlevels=2) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): pd.eval('p + 1', parser=parser, engine=engine) def test_raise_on_panel4d_with_multiindex(self): @@ -395,7 +394,7 @@ def check_raise_on_panel4d_with_multiindex(self, parser, engine): tm.skip_if_no_ne() p4d = tm.makePanel4D(7) p4d.items = tm.makeCustomIndex(len(p4d.items), nlevels=2) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): pd.eval('p4d + 1', parser=parser, engine=engine) @@ -500,14 +499,14 @@ def test_date_query_with_non_date(self): ops = '==', '!=', '<', '>', '<=', '>=' for op in ops: - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): df.query('dates %s nondate' % op, parser=parser, engine=engine) def test_query_syntax_error(self): engine, parser = self.engine, self.parser df = DataFrame({"i": lrange(10), "+": lrange(3, 13), "r": lrange(4, 14)}) - with tm.assertRaises(SyntaxError): + with pytest.raises(SyntaxError): df.query('i - +', engine=engine, parser=parser) def test_query_scope(self): @@ -527,11 +526,11 @@ def test_query_scope(self): assert_frame_equal(res, expected) # no local variable c - with tm.assertRaises(UndefinedVariableError): + with pytest.raises(UndefinedVariableError): df.query('@a > b > @c', engine=engine, parser=parser) # no column named 'c' - with tm.assertRaises(UndefinedVariableError): + with pytest.raises(UndefinedVariableError): df.query('@a > b > c', engine=engine, parser=parser) def test_query_doesnt_pickup_local(self): @@ -542,7 +541,7 @@ def test_query_doesnt_pickup_local(self): df = DataFrame(np.random.randint(m, size=(n, 3)), columns=list('abc')) # we don't pick up the local 'sin' - with tm.assertRaises(UndefinedVariableError): + with pytest.raises(UndefinedVariableError): df.query('sin > 5', engine=engine, parser=parser) def test_query_builtin(self): @@ -629,7 +628,7 @@ def test_nested_raises_on_local_self_reference(self): df = DataFrame(np.random.randn(5, 3)) # can't reference ourself b/c we're a local so @ is necessary - with tm.assertRaises(UndefinedVariableError): + with pytest.raises(UndefinedVariableError): df.query('df > 0', engine=self.engine, parser=self.parser) def test_local_syntax(self): @@ -799,7 +798,7 @@ def test_date_index_query_with_NaT_duplicates(self): df['dates3'] = date_range('1/1/2014', periods=n) df.loc[np.random.rand(n) > 0.5, 'dates1'] = pd.NaT df.set_index('dates1', inplace=True, drop=True) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): df.query('index < 20130101 < dates3', engine=engine, parser=parser) def test_nested_scope(self): @@ -815,10 +814,10 @@ def test_nested_scope(self): df2 = DataFrame(np.random.randn(5, 3)) # don't have the pandas parser - with tm.assertRaises(SyntaxError): + with pytest.raises(SyntaxError): df.query('(@df>0) & (@df2>0)', engine=engine, parser=parser) - with tm.assertRaises(UndefinedVariableError): + with pytest.raises(UndefinedVariableError): df.query('(df>0) & (df2>0)', engine=engine, parser=parser) expected = df[(df > 0) & (df2 > 0)] @@ -893,8 +892,9 @@ def check_str_query_method(self, parser, engine): for lhs, op, rhs in zip(lhs, ops, rhs): ex = '{lhs} {op} {rhs}'.format(lhs=lhs, op=op, rhs=rhs) - assertRaises(NotImplementedError, df.query, ex, engine=engine, - parser=parser, local_dict={'strings': df.strings}) + pytest.raises(NotImplementedError, df.query, ex, + engine=engine, parser=parser, + local_dict={'strings': df.strings}) else: res = df.query('"a" == strings', engine=engine, parser=parser) assert_frame_equal(res, expect) @@ -937,7 +937,7 @@ def check_str_list_query_method(self, parser, engine): for lhs, op, rhs in zip(lhs, ops, rhs): ex = '{lhs} {op} {rhs}'.format(lhs=lhs, op=op, rhs=rhs) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): df.query(ex, engine=engine, parser=parser) else: res = df.query('strings == ["a", "b"]', engine=engine, @@ -973,10 +973,10 @@ def check_query_with_string_columns(self, parser, engine): expec = df[df.a.isin(df.b) & (df.c < df.d)] assert_frame_equal(res, expec) else: - with assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): df.query('a in b', parser=parser, engine=engine) - with assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): df.query('a in b and c < d', parser=parser, engine=engine) def test_query_with_string_columns(self): diff --git a/pandas/tests/frame/test_replace.py b/pandas/tests/frame/test_replace.py index f8e411c30fe38..bb2baaf0e02e2 100644 --- a/pandas/tests/frame/test_replace.py +++ b/pandas/tests/frame/test_replace.py @@ -2,6 +2,8 @@ from __future__ import print_function +import pytest + from datetime import datetime import re @@ -31,8 +33,8 @@ def test_replace_inplace(self): tsframe.replace(nan, 0, inplace=True) assert_frame_equal(tsframe, self.tsframe.fillna(0)) - self.assertRaises(TypeError, self.tsframe.replace, nan, inplace=True) - self.assertRaises(TypeError, self.tsframe.replace, nan) + pytest.raises(TypeError, self.tsframe.replace, nan, inplace=True) + pytest.raises(TypeError, self.tsframe.replace, nan) # mixed type mf = self.mixed_frame @@ -718,7 +720,7 @@ def test_replace_simple_nested_dict_with_nonexistent_value(self): assert_frame_equal(expected, result) def test_replace_value_is_none(self): - self.assertRaises(TypeError, self.tsframe.replace, nan) + pytest.raises(TypeError, self.tsframe.replace, nan) orig_value = self.tsframe.iloc[0, 0] orig2 = self.tsframe.iloc[1, 0] @@ -831,7 +833,7 @@ def test_replace_input_formats_listlike(self): expected.replace(to_rep[i], values[i], inplace=True) assert_frame_equal(result, expected) - self.assertRaises(ValueError, df.replace, to_rep, values[1:]) + pytest.raises(ValueError, df.replace, to_rep, values[1:]) def test_replace_input_formats_scalar(self): df = DataFrame({'A': [np.nan, 0, np.inf], 'B': [0, 2, 5], @@ -845,7 +847,7 @@ def test_replace_input_formats_scalar(self): expected[k] = v.replace(to_rep[k], 0) assert_frame_equal(filled, DataFrame(expected)) - self.assertRaises(TypeError, df.replace, to_rep, [np.nan, 0, '']) + pytest.raises(TypeError, df.replace, to_rep, [np.nan, 0, '']) # list to scalar to_rep = [np.nan, 0, ''] diff --git a/pandas/tests/frame/test_reshape.py b/pandas/tests/frame/test_reshape.py index 067c6539121c0..60f19b7e6c87b 100644 --- a/pandas/tests/frame/test_reshape.py +++ b/pandas/tests/frame/test_reshape.py @@ -4,7 +4,9 @@ from warnings import catch_warnings from datetime import datetime + import itertools +import pytest from numpy.random import randn from numpy import nan @@ -364,7 +366,7 @@ def test_stack_mixed_levels(self): # When mixed types are passed and the ints are not level # names, raise - self.assertRaises(ValueError, df2.stack, level=['animal', 0]) + pytest.raises(ValueError, df2.stack, level=['animal', 0]) # GH #8584: Having 0 in the level names could raise a # strange error about lexsort depth @@ -523,10 +525,10 @@ def test_unstack_non_unique_index_names(self): idx = MultiIndex.from_tuples([('a', 'b'), ('c', 'd')], names=['c1', 'c1']) df = DataFrame([1, 2], index=idx) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.unstack('c1') - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.T.stack('c1') def test_unstack_nan_index(self): # GH7466 diff --git a/pandas/tests/frame/test_sorting.py b/pandas/tests/frame/test_sorting.py index 97171123c4a36..f1bca0d6a99b8 100644 --- a/pandas/tests/frame/test_sorting.py +++ b/pandas/tests/frame/test_sorting.py @@ -1,6 +1,8 @@ # -*- coding: utf-8 -*- from __future__ import print_function + +import pytest import random import numpy as np @@ -61,7 +63,7 @@ def test_sort_values(self): sorted_df = frame.sort_values(by=['B', 'A'], ascending=[True, False]) assert_frame_equal(sorted_df, expected) - self.assertRaises(ValueError, lambda: frame.sort_values( + pytest.raises(ValueError, lambda: frame.sort_values( by=['A', 'B'], axis=2, inplace=True)) # by row (axis=1): GH 10806 diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py index c521ba9ec215a..cf42f751f390a 100644 --- a/pandas/tests/frame/test_timeseries.py +++ b/pandas/tests/frame/test_timeseries.py @@ -4,6 +4,8 @@ from datetime import datetime, time +import pytest + from numpy import nan from numpy.random import randn import numpy as np @@ -299,7 +301,7 @@ def test_tshift(self): assert_frame_equal(unshifted, inferred_ts) no_freq = self.tsframe.iloc[[0, 5, 7], :] - self.assertRaises(ValueError, no_freq.tshift) + pytest.raises(ValueError, no_freq.tshift) def test_truncate(self): ts = self.tsframe[::3] @@ -340,9 +342,9 @@ def test_truncate(self): truncated = ts.truncate(after=end_missing) assert_frame_equal(truncated, expected) - self.assertRaises(ValueError, ts.truncate, - before=ts.index[-1] - 1, - after=ts.index[0] + 1) + pytest.raises(ValueError, ts.truncate, + before=ts.index[-1] - 1, + after=ts.index[0] + 1) def test_truncate_copy(self): index = self.tsframe.index @@ -571,4 +573,4 @@ def test_frame_to_period(self): pts = df.to_period('M', axis=1) tm.assert_index_equal(pts.columns, exp.columns.asfreq('M')) - self.assertRaises(ValueError, df.to_period, axis=2) + pytest.raises(ValueError, df.to_period, axis=2) diff --git a/pandas/tests/frame/test_to_csv.py b/pandas/tests/frame/test_to_csv.py index f7da45e14cbde..2df2e23c3f877 100644 --- a/pandas/tests/frame/test_to_csv.py +++ b/pandas/tests/frame/test_to_csv.py @@ -3,6 +3,7 @@ from __future__ import print_function import csv +import pytest from numpy import nan import numpy as np @@ -94,8 +95,8 @@ def test_to_csv_from_csv2(self): assert_frame_equal(xp, rs) - self.assertRaises(ValueError, self.frame2.to_csv, path, - header=['AA', 'X']) + pytest.raises(ValueError, self.frame2.to_csv, path, + header=['AA', 'X']) def test_to_csv_from_csv3(self): @@ -965,8 +966,8 @@ def test_to_csv_compression_value_error(self): with ensure_clean() as filename: # zip compression is not supported and should raise ValueError import zipfile - self.assertRaises(zipfile.BadZipfile, df.to_csv, - filename, compression="zip") + pytest.raises(zipfile.BadZipfile, df.to_csv, + filename, compression="zip") def test_to_csv_date_format(self): with ensure_clean('__tmp_to_csv_date_format__') as path: diff --git a/pandas/tests/frame/test_validate.py b/pandas/tests/frame/test_validate.py index e1ef87bb3271a..4c4abb7e58e75 100644 --- a/pandas/tests/frame/test_validate.py +++ b/pandas/tests/frame/test_validate.py @@ -1,6 +1,8 @@ from unittest import TestCase from pandas.core.frame import DataFrame +import pytest + class TestDataFrameValidate(TestCase): """Tests for error handling related to data types of method arguments.""" @@ -11,23 +13,23 @@ def test_validate_bool_args(self): invalid_values = [1, "True", [1, 2, 3], 5.0] for value in invalid_values: - with self.assertRaises(ValueError): + with pytest.raises(ValueError): self.df.query('a > b', inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): self.df.eval('a + b', inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): self.df.set_index(keys=['a'], inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): self.df.reset_index(inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): self.df.dropna(inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): self.df.drop_duplicates(inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): self.df.sort_values(by=['a'], inplace=value) diff --git a/pandas/tests/groupby/test_aggregate.py b/pandas/tests/groupby/test_aggregate.py index d91340312d7c2..e32dbb7846061 100644 --- a/pandas/tests/groupby/test_aggregate.py +++ b/pandas/tests/groupby/test_aggregate.py @@ -6,6 +6,9 @@ """ from __future__ import print_function + +import pytest + from datetime import datetime, timedelta from functools import partial @@ -179,8 +182,8 @@ def test_agg_cast_results_dtypes(self): def test_agg_must_agg(self): grouped = self.df.groupby('A')['C'] - self.assertRaises(Exception, grouped.agg, lambda x: x.describe()) - self.assertRaises(Exception, grouped.agg, lambda x: x.index[:2]) + pytest.raises(Exception, grouped.agg, lambda x: x.describe()) + pytest.raises(Exception, grouped.agg, lambda x: x.index[:2]) def test_agg_ser_multi_key(self): # TODO(wesm): unused @@ -374,7 +377,7 @@ def f(): g.aggregate({'r1': {'C': ['mean', 'sum']}, 'r2': {'D': ['mean', 'sum']}}) - self.assertRaises(SpecificationError, f) + pytest.raises(SpecificationError, f) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): @@ -477,7 +480,7 @@ def raiseException(df): pprint_thing(df.to_string()) raise TypeError - self.assertRaises(TypeError, df.groupby(0).agg, raiseException) + pytest.raises(TypeError, df.groupby(0).agg, raiseException) def test_series_agg_multikey(self): ts = tm.makeTimeSeries() @@ -563,11 +566,11 @@ def test_cython_agg_boolean(self): def test_cython_agg_nothing_to_agg(self): frame = DataFrame({'a': np.random.randint(0, 5, 50), 'b': ['foo', 'bar'] * 25}) - self.assertRaises(DataError, frame.groupby('a')['b'].mean) + pytest.raises(DataError, frame.groupby('a')['b'].mean) frame = DataFrame({'a': np.random.randint(0, 5, 50), 'b': ['foo', 'bar'] * 25}) - self.assertRaises(DataError, frame[['b']].groupby(frame['a']).mean) + pytest.raises(DataError, frame[['b']].groupby(frame['a']).mean) def test_cython_agg_nothing_to_agg_with_dates(self): frame = DataFrame({'a': np.random.randint(0, 5, 50), @@ -659,7 +662,7 @@ def test_agg_multiple_functions_too_many_lambdas(self): grouped = self.df.groupby('A') funcs = ['mean', lambda x: x.mean(), lambda x: x.std()] - self.assertRaises(SpecificationError, grouped.agg, funcs) + pytest.raises(SpecificationError, grouped.agg, funcs) def test_more_flexible_frame_multi_function(self): diff --git a/pandas/tests/groupby/test_bin_groupby.py b/pandas/tests/groupby/test_bin_groupby.py index 289723ed5667a..320acacff483c 100644 --- a/pandas/tests/groupby/test_bin_groupby.py +++ b/pandas/tests/groupby/test_bin_groupby.py @@ -1,5 +1,7 @@ # -*- coding: utf-8 -*- +import pytest + from numpy import nan import numpy as np @@ -70,15 +72,15 @@ def test_generate_bins(self): bins = func(values, binner, closed='right') assert ((bins == np.array([3, 6])).all()) - self.assertRaises(ValueError, generate_bins_generic, values, [], - 'right') - self.assertRaises(ValueError, generate_bins_generic, values[:0], - binner, 'right') + pytest.raises(ValueError, generate_bins_generic, values, [], + 'right') + pytest.raises(ValueError, generate_bins_generic, values[:0], + binner, 'right') - self.assertRaises(ValueError, generate_bins_generic, values, [4], - 'right') - self.assertRaises(ValueError, generate_bins_generic, values, [-3, -1], - 'right') + pytest.raises(ValueError, generate_bins_generic, values, [4], + 'right') + pytest.raises(ValueError, generate_bins_generic, values, [-3, -1], + 'right') def test_group_ohlc(): diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 83471c7e98299..b9a731f2204da 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -2,6 +2,8 @@ from __future__ import print_function from datetime import datetime +import pytest + import numpy as np from numpy import nan @@ -227,7 +229,7 @@ def test_groupby_bins_unequal_len(self): # len(bins) != len(series) here def f(): series.groupby(bins).mean() - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def test_groupby_multi_categorical_as_index(self): # GH13204 diff --git a/pandas/tests/groupby/test_filters.py b/pandas/tests/groupby/test_filters.py index de6757786a363..5f39f320b1ea1 100644 --- a/pandas/tests/groupby/test_filters.py +++ b/pandas/tests/groupby/test_filters.py @@ -2,6 +2,7 @@ from __future__ import print_function from numpy import nan +import pytest from pandas import Timestamp from pandas.core.index import MultiIndex @@ -164,8 +165,8 @@ def raise_if_sum_is_zero(x): s = pd.Series([-1, 0, 1, 2]) grouper = s.apply(lambda x: x % 2) grouped = s.groupby(grouper) - self.assertRaises(TypeError, - lambda: grouped.filter(raise_if_sum_is_zero)) + pytest.raises(TypeError, + lambda: grouped.filter(raise_if_sum_is_zero)) def test_filter_with_axis_in_groupby(self): # issue 11041 @@ -186,16 +187,16 @@ def test_filter_bad_shapes(self): g_s = s.groupby(s) f = lambda x: x - self.assertRaises(TypeError, lambda: g_df.filter(f)) - self.assertRaises(TypeError, lambda: g_s.filter(f)) + pytest.raises(TypeError, lambda: g_df.filter(f)) + pytest.raises(TypeError, lambda: g_s.filter(f)) f = lambda x: x == 1 - self.assertRaises(TypeError, lambda: g_df.filter(f)) - self.assertRaises(TypeError, lambda: g_s.filter(f)) + pytest.raises(TypeError, lambda: g_df.filter(f)) + pytest.raises(TypeError, lambda: g_s.filter(f)) f = lambda x: np.outer(x, x) - self.assertRaises(TypeError, lambda: g_df.filter(f)) - self.assertRaises(TypeError, lambda: g_s.filter(f)) + pytest.raises(TypeError, lambda: g_df.filter(f)) + pytest.raises(TypeError, lambda: g_s.filter(f)) def test_filter_nan_is_false(self): df = DataFrame({'A': np.arange(8), diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index ea76fa24cc37c..25ebfef327476 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -1,6 +1,8 @@ # -*- coding: utf-8 -*- from __future__ import print_function +import pytest + from warnings import catch_warnings from string import ascii_lowercase from datetime import datetime @@ -69,7 +71,7 @@ def checkit(dtype): self.assertEqual(agged[1], 21) # corner cases - self.assertRaises(Exception, grouped.aggregate, lambda x: x * 2) + pytest.raises(Exception, grouped.aggregate, lambda x: x * 2) for dtype in ['int64', 'int32', 'float64', 'float32']: checkit(dtype) @@ -77,9 +79,9 @@ def checkit(dtype): def test_select_bad_cols(self): df = DataFrame([[1, 2]], columns=['A', 'B']) g = df.groupby('A') - self.assertRaises(KeyError, g.__getitem__, ['C']) # g[['C']] + pytest.raises(KeyError, g.__getitem__, ['C']) # g[['C']] - self.assertRaises(KeyError, g.__getitem__, ['A', 'C']) # g[['A', 'C']] + pytest.raises(KeyError, g.__getitem__, ['A', 'C']) # g[['A', 'C']] with assertRaisesRegexp(KeyError, '^[^A]+$'): # A should not be referenced as a bad column... # will have to rethink regex if you change message! @@ -648,7 +650,7 @@ def test_grouper_iter(self): def test_empty_groups(self): # GH # 1048 - self.assertRaises(ValueError, self.df.groupby, []) + pytest.raises(ValueError, self.df.groupby, []) def test_groupby_grouper(self): grouped = self.df.groupby('A') @@ -662,8 +664,8 @@ def test_groupby_duplicated_column_errormsg(self): df = DataFrame(columns=['A', 'B', 'A', 'C'], data=[range(4), range(2, 6), range(0, 8, 2)]) - self.assertRaises(ValueError, df.groupby, 'A') - self.assertRaises(ValueError, df.groupby, ['A', 'B']) + pytest.raises(ValueError, df.groupby, 'A') + pytest.raises(ValueError, df.groupby, ['A', 'B']) grouped = df.groupby('B') c = grouped.count() @@ -702,7 +704,7 @@ def test_groupby_grouper_f_sanity_checked(self): # when the elements are Timestamp. # the result is Index[0:6], very confusing. - self.assertRaises(AssertionError, ts.groupby, lambda key: key[0:6]) + pytest.raises(AssertionError, ts.groupby, lambda key: key[0:6]) def test_groupby_nonobject_dtype(self): key = self.mframe.index.labels[0] @@ -853,10 +855,10 @@ def test_get_group(self): assert_frame_equal(result1, result3) # must pass a same-length tuple with multiple keys - self.assertRaises(ValueError, lambda: g.get_group('foo')) - self.assertRaises(ValueError, lambda: g.get_group(('foo'))) - self.assertRaises(ValueError, - lambda: g.get_group(('foo', 'bar', 'baz'))) + pytest.raises(ValueError, lambda: g.get_group('foo')) + pytest.raises(ValueError, lambda: g.get_group(('foo'))) + pytest.raises(ValueError, + lambda: g.get_group(('foo', 'bar', 'baz'))) def test_get_group_empty_bins(self): @@ -870,7 +872,7 @@ def test_get_group_empty_bins(self): expected = DataFrame([3, 1], index=[0, 1]) assert_frame_equal(result, expected) - self.assertRaises(KeyError, lambda: g.get_group(pd.Interval(10, 15))) + pytest.raises(KeyError, lambda: g.get_group(pd.Interval(10, 15))) def test_get_group_grouped_by_tuple(self): # GH 8121 @@ -890,8 +892,8 @@ def test_get_group_grouped_by_tuple(self): def test_grouping_error_on_multidim_input(self): from pandas.core.groupby import Grouping - self.assertRaises(ValueError, - Grouping, self.df.index, self.df[['A', 'A']]) + pytest.raises(ValueError, + Grouping, self.df.index, self.df[['A', 'A']]) def test_apply_describe_bug(self): grouped = self.mframe.groupby(level='first') @@ -1073,12 +1075,12 @@ def f3(x): assert_frame_equal(result1, result2) # should fail (not the same number of levels) - self.assertRaises(AssertionError, df.groupby('a').apply, f2) - self.assertRaises(AssertionError, df2.groupby('a').apply, f2) + pytest.raises(AssertionError, df.groupby('a').apply, f2) + pytest.raises(AssertionError, df2.groupby('a').apply, f2) # should fail (incorrect shape) - self.assertRaises(AssertionError, df.groupby('a').apply, f3) - self.assertRaises(AssertionError, df2.groupby('a').apply, f3) + pytest.raises(AssertionError, df.groupby('a').apply, f3) + pytest.raises(AssertionError, df2.groupby('a').apply, f3) def test_attr_wrapper(self): grouped = self.ts.groupby(lambda x: x.weekday()) @@ -1100,7 +1102,7 @@ def test_attr_wrapper(self): expected = grouped.agg(lambda x: x.dtype) # make sure raises error - self.assertRaises(AttributeError, getattr, grouped, 'foo') + pytest.raises(AttributeError, getattr, grouped, 'foo') def test_series_describe_multikey(self): ts = tm.makeTimeSeries() @@ -1155,8 +1157,8 @@ def test_frame_describe_tupleindex(self): 'z': [100, 200, 300, 400, 500] * 3}) df1['k'] = [(0, 0, 1), (0, 1, 0), (1, 0, 0)] * 5 df2 = df1.rename(columns={'k': 'key'}) - tm.assertRaises(ValueError, lambda: df1.groupby('k').describe()) - tm.assertRaises(ValueError, lambda: df2.groupby('key').describe()) + pytest.raises(ValueError, lambda: df1.groupby('k').describe()) + pytest.raises(ValueError, lambda: df2.groupby('key').describe()) def test_frame_describe_unstacked_format(self): # GH 4792 @@ -1585,7 +1587,7 @@ def test_as_index_series_return_frame(self): assert_frame_equal(result2, expected2) # corner case - self.assertRaises(Exception, grouped['C'].__getitem__, 'D') + pytest.raises(Exception, grouped['C'].__getitem__, 'D') def test_groupby_as_index_cython(self): data = self.df @@ -1619,11 +1621,11 @@ def test_groupby_as_index_series_scalar(self): assert_frame_equal(result, expected) def test_groupby_as_index_corner(self): - self.assertRaises(TypeError, self.ts.groupby, lambda x: x.weekday(), - as_index=False) + pytest.raises(TypeError, self.ts.groupby, lambda x: x.weekday(), + as_index=False) - self.assertRaises(ValueError, self.df.groupby, lambda x: x.lower(), - as_index=False, axis=1) + pytest.raises(ValueError, self.df.groupby, lambda x: x.lower(), + as_index=False, axis=1) def test_groupby_as_index_apply(self): # GH #4648 and #3417 @@ -1756,8 +1758,8 @@ def test_omit_nuisance(self): # won't work with axis = 1 grouped = df.groupby({'A': 0, 'C': 0, 'D': 1, 'E': 1}, axis=1) - result = self.assertRaises(TypeError, grouped.agg, - lambda x: x.sum(0, numeric_only=False)) + result = pytest.raises(TypeError, grouped.agg, + lambda x: x.sum(0, numeric_only=False)) def test_omit_nuisance_python_multiple(self): grouped = self.three_group.groupby(['A', 'B']) @@ -1821,7 +1823,7 @@ def desc3(group): def test_nonsense_func(self): df = DataFrame([0]) - self.assertRaises(Exception, df.groupby, lambda x: x + 'foo') + pytest.raises(Exception, df.groupby, lambda x: x + 'foo') def test_builtins_apply(self): # GH8155 df = pd.DataFrame(np.random.randint(1, 50, (1000, 2)), @@ -2046,14 +2048,14 @@ def test_groupby_level(self): assert_frame_equal(result1, expected1.T) # raise exception for non-MultiIndex - self.assertRaises(ValueError, self.df.groupby, level=1) + pytest.raises(ValueError, self.df.groupby, level=1) def test_groupby_level_index_names(self): # GH4014 this used to raise ValueError since 'exp'>1 (in py2) df = DataFrame({'exp': ['A'] * 3 + ['B'] * 3, 'var1': lrange(6), }).set_index('exp') df.groupby(level='exp') - self.assertRaises(ValueError, df.groupby, level='foo') + pytest.raises(ValueError, df.groupby, level='foo') def test_groupby_level_with_nas(self): index = MultiIndex(levels=[[1, 0], [0, 1, 2, 3]], @@ -2140,12 +2142,12 @@ def test_groupby_level_nonmulti(self): result = s.groupby(level=[-1]).sum() tm.assert_series_equal(result, expected) - tm.assertRaises(ValueError, s.groupby, level=1) - tm.assertRaises(ValueError, s.groupby, level=-2) - tm.assertRaises(ValueError, s.groupby, level=[]) - tm.assertRaises(ValueError, s.groupby, level=[0, 0]) - tm.assertRaises(ValueError, s.groupby, level=[0, 1]) - tm.assertRaises(ValueError, s.groupby, level=[1]) + pytest.raises(ValueError, s.groupby, level=1) + pytest.raises(ValueError, s.groupby, level=-2) + pytest.raises(ValueError, s.groupby, level=[]) + pytest.raises(ValueError, s.groupby, level=[0, 0]) + pytest.raises(ValueError, s.groupby, level=[0, 1]) + pytest.raises(ValueError, s.groupby, level=[1]) def test_groupby_complex(self): # GH 12902 @@ -2905,7 +2907,7 @@ def test_groupby_list_infer_array_like(self): expected = self.df.groupby(self.df['A']).mean() assert_frame_equal(result, expected, check_names=False) - self.assertRaises(Exception, self.df.groupby, list(self.df['A'][:-1])) + pytest.raises(Exception, self.df.groupby, list(self.df['A'][:-1])) # pathological case of ambiguity df = DataFrame({'foo': [0, 1], @@ -2931,9 +2933,9 @@ def test_groupby_keys_same_size_as_index(self): def test_groupby_one_row(self): # GH 11741 df1 = pd.DataFrame(np.random.randn(1, 4), columns=list('ABCD')) - self.assertRaises(KeyError, df1.groupby, 'Z') + pytest.raises(KeyError, df1.groupby, 'Z') df2 = pd.DataFrame(np.random.randn(2, 4), columns=list('ABCD')) - self.assertRaises(KeyError, df2.groupby, 'Z') + pytest.raises(KeyError, df2.groupby, 'Z') def test_groupby_nat_exclude(self): # GH 6992 @@ -2970,7 +2972,7 @@ def test_groupby_nat_exclude(self): tm.assert_frame_equal( grouped.get_group(Timestamp('2013-02-01')), df.iloc[[3, 5]]) - self.assertRaises(KeyError, grouped.get_group, pd.NaT) + pytest.raises(KeyError, grouped.get_group, pd.NaT) nan_df = DataFrame({'nan': [np.nan, np.nan, np.nan], 'nat': [pd.NaT, pd.NaT, pd.NaT]}) @@ -2982,8 +2984,8 @@ def test_groupby_nat_exclude(self): self.assertEqual(grouped.groups, {}) self.assertEqual(grouped.ngroups, 0) self.assertEqual(grouped.indices, {}) - self.assertRaises(KeyError, grouped.get_group, np.nan) - self.assertRaises(KeyError, grouped.get_group, pd.NaT) + pytest.raises(KeyError, grouped.get_group, np.nan) + pytest.raises(KeyError, grouped.get_group, pd.NaT) def test_dictify(self): dict(iter(self.df.groupby('A'))) @@ -4019,7 +4021,7 @@ def test_pivot_table_values_key_error(self): df['year'] = df.set_index('eventDate').index.year df['month'] = df.set_index('eventDate').index.month - with self.assertRaises(KeyError): + with pytest.raises(KeyError): df.reset_index().pivot_table(index='year', columns='month', values='badname', aggfunc='count') diff --git a/pandas/tests/groupby/test_timegrouper.py b/pandas/tests/groupby/test_timegrouper.py index dfc23d3db21bc..ae0413615f738 100644 --- a/pandas/tests/groupby/test_timegrouper.py +++ b/pandas/tests/groupby/test_timegrouper.py @@ -1,5 +1,7 @@ """ test with the TimeGrouper / grouping with datetimes """ +import pytest + from datetime import datetime import numpy as np from numpy import nan @@ -186,7 +188,7 @@ def test_timegrouper_with_reg_groups(self): ]).sum() assert_frame_equal(result, expected) - with self.assertRaises(KeyError): + with pytest.raises(KeyError): df.groupby([pd.Grouper(freq='1M', key='foo'), 'Buyer']).sum() # passing the level @@ -198,7 +200,7 @@ def test_timegrouper_with_reg_groups(self): ) assert_frame_equal(result, expected) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): df.groupby([pd.Grouper(freq='1M', level='foo'), 'Buyer']).sum() @@ -219,7 +221,7 @@ def test_timegrouper_with_reg_groups(self): assert_frame_equal(result, expected) # error as we have both a level and a name! - with self.assertRaises(ValueError): + with pytest.raises(ValueError): df.groupby([pd.Grouper(freq='1M', key='Date', level='Date'), 'Buyer']).sum() diff --git a/pandas/tests/groupby/test_transform.py b/pandas/tests/groupby/test_transform.py index 3ed2023136b3a..57ea8eb067a2b 100644 --- a/pandas/tests/groupby/test_transform.py +++ b/pandas/tests/groupby/test_transform.py @@ -1,5 +1,7 @@ """ test with the .transform """ +import pytest + import numpy as np import pandas as pd from pandas.util import testing as tm @@ -534,8 +536,8 @@ def test_cython_transform(self): for c in df: if c not in ['float', 'int', 'float_missing' ] and op != 'shift': - self.assertRaises(DataError, gb[c].transform, op) - self.assertRaises(DataError, getattr(gb[c], op)) + pytest.raises(DataError, gb[c].transform, op) + pytest.raises(DataError, getattr(gb[c], op)) else: expected = gb[c].apply(targop) expected.name = c diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index 91c08764985a9..ff90c924933f3 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -40,7 +40,7 @@ def test_pickle_compat_construction(self): return # need an object to create with - self.assertRaises(TypeError, self._holder) + pytest.raises(TypeError, self._holder) def test_to_series(self): # assert that we are creating a copy of the index @@ -55,8 +55,8 @@ def test_shift(self): # GH8083 test the base class for shift idx = self.create_index() - self.assertRaises(NotImplementedError, idx.shift, 1) - self.assertRaises(NotImplementedError, idx.shift, 1, 2) + pytest.raises(NotImplementedError, idx.shift, 1) + pytest.raises(NotImplementedError, idx.shift, 1, 2) def test_create_index_existing_name(self): @@ -363,13 +363,13 @@ def test_get_unique_index(self): def test_sort(self): for ind in self.indices.values(): - self.assertRaises(TypeError, ind.sort) + pytest.raises(TypeError, ind.sort) def test_mutability(self): for ind in self.indices.values(): if not len(ind): continue - self.assertRaises(TypeError, ind.__setitem__, 0, ind[0]) + pytest.raises(TypeError, ind.__setitem__, 0, ind[0]) def test_view(self): for ind in self.indices.values(): @@ -459,7 +459,7 @@ def test_take(self): if not isinstance(ind, (DatetimeIndex, PeriodIndex, TimedeltaIndex)): # GH 10791 - with tm.assertRaises(AttributeError): + with pytest.raises(AttributeError): ind.freq def test_take_invalid_kwargs(self): @@ -694,7 +694,7 @@ def test_delete_base(self): self.assertTrue(result.equals(expected)) self.assertEqual(result.name, expected.name) - with tm.assertRaises((IndexError, ValueError)): + with pytest.raises((IndexError, ValueError)): # either depending on numpy version result = idx.delete(len(idx)) diff --git a/pandas/tests/indexes/datetimes/test_astype.py b/pandas/tests/indexes/datetimes/test_astype.py index 3d7814b7340bc..755944d342ed4 100644 --- a/pandas/tests/indexes/datetimes/test_astype.py +++ b/pandas/tests/indexes/datetimes/test_astype.py @@ -1,3 +1,5 @@ +import pytest + import numpy as np from datetime import datetime @@ -115,11 +117,11 @@ def test_astype_raises(self): # GH 13149, GH 13209 idx = DatetimeIndex(['2016-05-16', 'NaT', NaT, np.NaN]) - self.assertRaises(ValueError, idx.astype, float) - self.assertRaises(ValueError, idx.astype, 'timedelta64') - self.assertRaises(ValueError, idx.astype, 'timedelta64[ns]') - self.assertRaises(ValueError, idx.astype, 'datetime64') - self.assertRaises(ValueError, idx.astype, 'datetime64[D]') + pytest.raises(ValueError, idx.astype, float) + pytest.raises(ValueError, idx.astype, 'timedelta64') + pytest.raises(ValueError, idx.astype, 'timedelta64[ns]') + pytest.raises(ValueError, idx.astype, 'datetime64') + pytest.raises(ValueError, idx.astype, 'datetime64[D]') def test_index_convert_to_datetime_array(self): tm._skip_if_no_pytz() diff --git a/pandas/tests/indexes/datetimes/test_construction.py b/pandas/tests/indexes/datetimes/test_construction.py index 50d389e263305..ca673e3059ea2 100644 --- a/pandas/tests/indexes/datetimes/test_construction.py +++ b/pandas/tests/indexes/datetimes/test_construction.py @@ -1,3 +1,5 @@ +import pytest + import numpy as np from datetime import timedelta @@ -49,7 +51,7 @@ def test_construction_with_alt(self): tm.assert_index_equal(i2, expected) # incompat tz/dtype - self.assertRaises(ValueError, lambda: DatetimeIndex( + pytest.raises(ValueError, lambda: DatetimeIndex( i.tz_localize(None).asi8, dtype=i.dtype, tz='US/Pacific')) def test_construction_index_with_mixed_timezones(self): @@ -239,7 +241,7 @@ def test_construction_dti_with_mixed_timezones(self): # tz mismatch affecting to tz-aware raises TypeError/ValueError - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): DatetimeIndex([Timestamp('2011-01-01 10:00', tz='Asia/Tokyo'), Timestamp('2011-01-02 10:00', tz='US/Eastern')], name='idx') @@ -249,7 +251,7 @@ def test_construction_dti_with_mixed_timezones(self): Timestamp('2011-01-02 10:00', tz='US/Eastern')], tz='Asia/Tokyo', name='idx') - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): DatetimeIndex([Timestamp('2011-01-01 10:00', tz='Asia/Tokyo'), Timestamp('2011-01-02 10:00', tz='US/Eastern')], tz='US/Eastern', name='idx') @@ -280,7 +282,7 @@ def test_construction_outofbounds(self): # coerces to object tm.assert_index_equal(Index(dates), exp) - with tm.assertRaises(OutOfBoundsDatetime): + with pytest.raises(OutOfBoundsDatetime): # can't create DatetimeIndex DatetimeIndex(dates) @@ -302,13 +304,13 @@ def test_constructor_coverage(self): exp = date_range('1/1/2000', periods=10) tm.assert_index_equal(rng, exp) - self.assertRaises(ValueError, DatetimeIndex, start='1/1/2000', - periods='foo', freq='D') + pytest.raises(ValueError, DatetimeIndex, start='1/1/2000', + periods='foo', freq='D') - self.assertRaises(ValueError, DatetimeIndex, start='1/1/2000', - end='1/10/2000') + pytest.raises(ValueError, DatetimeIndex, start='1/1/2000', + end='1/10/2000') - self.assertRaises(ValueError, DatetimeIndex, '1/1/2000') + pytest.raises(ValueError, DatetimeIndex, '1/1/2000') # generator expression gen = (datetime(2000, 1, 1) + timedelta(i) for i in range(10)) @@ -336,14 +338,14 @@ def test_constructor_coverage(self): tm.assert_index_equal(from_ints, expected) # non-conforming - self.assertRaises(ValueError, DatetimeIndex, - ['2000-01-01', '2000-01-02', '2000-01-04'], freq='D') + pytest.raises(ValueError, DatetimeIndex, + ['2000-01-01', '2000-01-02', '2000-01-04'], freq='D') - self.assertRaises(ValueError, DatetimeIndex, start='2011-01-01', - freq='b') - self.assertRaises(ValueError, DatetimeIndex, end='2011-01-01', - freq='B') - self.assertRaises(ValueError, DatetimeIndex, periods=10, freq='D') + pytest.raises(ValueError, DatetimeIndex, start='2011-01-01', + freq='b') + pytest.raises(ValueError, DatetimeIndex, end='2011-01-01', + freq='B') + pytest.raises(ValueError, DatetimeIndex, periods=10, freq='D') def test_constructor_datetime64_tzformat(self): # GH 6572 @@ -414,18 +416,18 @@ def test_constructor_dtype(self): idx = DatetimeIndex(['2013-01-01', '2013-01-02'], dtype='datetime64[ns, US/Eastern]') - self.assertRaises(ValueError, - lambda: DatetimeIndex(idx, - dtype='datetime64[ns]')) + pytest.raises(ValueError, + lambda: DatetimeIndex(idx, + dtype='datetime64[ns]')) # this is effectively trying to convert tz's - self.assertRaises(TypeError, - lambda: DatetimeIndex(idx, - dtype='datetime64[ns, CET]')) - self.assertRaises(ValueError, - lambda: DatetimeIndex( - idx, tz='CET', - dtype='datetime64[ns, US/Eastern]')) + pytest.raises(TypeError, + lambda: DatetimeIndex(idx, + dtype='datetime64[ns, CET]')) + pytest.raises(ValueError, + lambda: DatetimeIndex( + idx, tz='CET', + dtype='datetime64[ns, US/Eastern]')) result = DatetimeIndex(idx, dtype='datetime64[ns, US/Eastern]') tm.assert_index_equal(idx, result) @@ -527,7 +529,7 @@ def test_from_freq_recreate_from_data(self): def test_datetimeindex_constructor_misc(self): arr = ['1/1/2005', '1/2/2005', 'Jn 3, 2005', '2005-01-04'] - self.assertRaises(Exception, DatetimeIndex, arr) + pytest.raises(Exception, DatetimeIndex, arr) arr = ['1/1/2005', '1/2/2005', '1/3/2005', '2005-01-04'] idx1 = DatetimeIndex(arr) diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 3c00fb32649bb..665dcc45050f3 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -3,6 +3,8 @@ construction from the convenience range functions """ +import pytest + import numpy as np from datetime import datetime, timedelta, time @@ -79,8 +81,8 @@ def test_date_range_ambiguous_arguments(self): start = datetime(2011, 1, 1, 5, 3, 40) end = datetime(2011, 1, 1, 8, 9, 40) - self.assertRaises(ValueError, date_range, start, end, freq='s', - periods=10) + pytest.raises(ValueError, date_range, start, end, freq='s', + periods=10) def test_date_range_businesshour(self): idx = DatetimeIndex(['2014-07-04 09:00', '2014-07-04 10:00', @@ -119,13 +121,13 @@ def test_date_range_businesshour(self): def test_range_misspecified(self): # GH #1095 - self.assertRaises(ValueError, date_range, '1/1/2000') - self.assertRaises(ValueError, date_range, end='1/1/2000') - self.assertRaises(ValueError, date_range, periods=10) + pytest.raises(ValueError, date_range, '1/1/2000') + pytest.raises(ValueError, date_range, end='1/1/2000') + pytest.raises(ValueError, date_range, periods=10) - self.assertRaises(ValueError, date_range, '1/1/2000', freq='H') - self.assertRaises(ValueError, date_range, end='1/1/2000', freq='H') - self.assertRaises(ValueError, date_range, periods=10, freq='H') + pytest.raises(ValueError, date_range, '1/1/2000', freq='H') + pytest.raises(ValueError, date_range, end='1/1/2000', freq='H') + pytest.raises(ValueError, date_range, periods=10, freq='H') def test_compat_replace(self): # https://github.com/statsmodels/statsmodels/issues/3349 @@ -141,8 +143,8 @@ def test_compat_replace(self): def test_catch_infinite_loop(self): offset = offsets.DateOffset(minute=5) # blow up, don't loop forever - self.assertRaises(Exception, date_range, datetime(2011, 11, 11), - datetime(2011, 11, 12), freq=offset) + pytest.raises(Exception, date_range, datetime(2011, 11, 11), + datetime(2011, 11, 12), freq=offset) class TestGenRangeGeneration(tm.TestCase): @@ -203,8 +205,8 @@ def test_constructor(self): bdate_range(START, END, freq=BDay()) bdate_range(START, periods=20, freq=BDay()) bdate_range(end=START, periods=20, freq=BDay()) - self.assertRaises(ValueError, date_range, '2011-1-1', '2012-1-1', 'B') - self.assertRaises(ValueError, bdate_range, '2011-1-1', '2012-1-1', 'B') + pytest.raises(ValueError, date_range, '2011-1-1', '2012-1-1', 'B') + pytest.raises(ValueError, bdate_range, '2011-1-1', '2012-1-1', 'B') def test_naive_aware_conflicts(self): naive = bdate_range(START, END, freq=BDay(), tz=None) @@ -250,8 +252,8 @@ def test_timezone_comparaison_bug(self): def test_timezone_comparaison_assert(self): start = Timestamp('20130220 10:00', tz='US/Eastern') - self.assertRaises(AssertionError, date_range, start, periods=2, - tz='Europe/Berlin') + pytest.raises(AssertionError, date_range, start, periods=2, + tz='Europe/Berlin') def test_misc(self): end = datetime(2009, 5, 13) @@ -265,14 +267,14 @@ def test_misc(self): def test_date_parse_failure(self): badly_formed_date = '2007/100/1' - self.assertRaises(ValueError, Timestamp, badly_formed_date) + pytest.raises(ValueError, Timestamp, badly_formed_date) - self.assertRaises(ValueError, bdate_range, start=badly_formed_date, - periods=10) - self.assertRaises(ValueError, bdate_range, end=badly_formed_date, - periods=10) - self.assertRaises(ValueError, bdate_range, badly_formed_date, - badly_formed_date) + pytest.raises(ValueError, bdate_range, start=badly_formed_date, + periods=10) + pytest.raises(ValueError, bdate_range, end=badly_formed_date, + periods=10) + pytest.raises(ValueError, bdate_range, badly_formed_date, + badly_formed_date) def test_daterange_bug_456(self): # GH #456 @@ -284,8 +286,8 @@ def test_daterange_bug_456(self): assert isinstance(result, DatetimeIndex) def test_error_with_zero_monthends(self): - self.assertRaises(ValueError, date_range, '1/1/2000', '1/1/2001', - freq=MonthEnd(0)) + pytest.raises(ValueError, date_range, '1/1/2000', '1/1/2001', + freq=MonthEnd(0)) def test_range_bug(self): # GH #770 @@ -488,8 +490,8 @@ def test_constructor(self): cdate_range(START, END, freq=CDay()) cdate_range(START, periods=20, freq=CDay()) cdate_range(end=START, periods=20, freq=CDay()) - self.assertRaises(ValueError, date_range, '2011-1-1', '2012-1-1', 'C') - self.assertRaises(ValueError, cdate_range, '2011-1-1', '2012-1-1', 'C') + pytest.raises(ValueError, date_range, '2011-1-1', '2012-1-1', 'C') + pytest.raises(ValueError, cdate_range, '2011-1-1', '2012-1-1', 'C') def test_cached_range(self): DatetimeIndex._cached_range(START, END, offset=CDay()) @@ -498,16 +500,16 @@ def test_cached_range(self): DatetimeIndex._cached_range(end=START, periods=20, offset=CDay()) - self.assertRaises(Exception, DatetimeIndex._cached_range, START, END) + pytest.raises(Exception, DatetimeIndex._cached_range, START, END) - self.assertRaises(Exception, DatetimeIndex._cached_range, START, - freq=CDay()) + pytest.raises(Exception, DatetimeIndex._cached_range, START, + freq=CDay()) - self.assertRaises(Exception, DatetimeIndex._cached_range, end=END, - freq=CDay()) + pytest.raises(Exception, DatetimeIndex._cached_range, end=END, + freq=CDay()) - self.assertRaises(Exception, DatetimeIndex._cached_range, periods=20, - freq=CDay()) + pytest.raises(Exception, DatetimeIndex._cached_range, periods=20, + freq=CDay()) def test_misc(self): end = datetime(2009, 5, 13) @@ -521,14 +523,14 @@ def test_misc(self): def test_date_parse_failure(self): badly_formed_date = '2007/100/1' - self.assertRaises(ValueError, Timestamp, badly_formed_date) + pytest.raises(ValueError, Timestamp, badly_formed_date) - self.assertRaises(ValueError, cdate_range, start=badly_formed_date, - periods=10) - self.assertRaises(ValueError, cdate_range, end=badly_formed_date, - periods=10) - self.assertRaises(ValueError, cdate_range, badly_formed_date, - badly_formed_date) + pytest.raises(ValueError, cdate_range, start=badly_formed_date, + periods=10) + pytest.raises(ValueError, cdate_range, end=badly_formed_date, + periods=10) + pytest.raises(ValueError, cdate_range, badly_formed_date, + badly_formed_date) def test_daterange_bug_456(self): # GH #456 diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index cd7e8cb782f12..7cef5eeb94915 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -1,3 +1,5 @@ +import pytest + import numpy as np from datetime import date, timedelta, time @@ -40,7 +42,7 @@ def test_get_loc(self): tolerance=timedelta(1)), 1) with tm.assertRaisesRegexp(ValueError, 'must be convertible'): idx.get_loc('2000-01-01T12', method='nearest', tolerance='foo') - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): idx.get_loc('2000-01-01T03', method='nearest', tolerance='2 hours') self.assertEqual(idx.get_loc('2000', method='nearest'), slice(0, 3)) @@ -49,14 +51,14 @@ def test_get_loc(self): self.assertEqual(idx.get_loc('1999', method='nearest'), 0) self.assertEqual(idx.get_loc('2001', method='nearest'), 2) - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): idx.get_loc('1999', method='pad') - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): idx.get_loc('2001', method='backfill') - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): idx.get_loc('foobar') - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): idx.get_loc(slice(2)) idx = pd.to_datetime(['2000-01-01', '2000-01-04']) @@ -70,7 +72,7 @@ def test_get_loc(self): np.array([12]), check_dtype=False) tm.assert_numpy_array_equal(idx.get_loc(time(12, 30)), np.array([]), check_dtype=False) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): idx.get_loc(time(12, 30), method='pad') def test_get_indexer(self): @@ -90,7 +92,7 @@ def test_get_indexer(self): idx.get_indexer(target, 'nearest', tolerance=pd.Timedelta('1 hour')), np.array([0, -1, 1], dtype=np.intp)) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): idx.get_indexer(idx[[0]], method='nearest', tolerance='foo') def test_reasonable_keyerror(self): @@ -234,7 +236,7 @@ def test_append_join_nondatetimeindex(self): def test_to_period_nofreq(self): idx = DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-04']) - self.assertRaises(ValueError, idx.to_period) + pytest.raises(ValueError, idx.to_period) idx = DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03'], freq='infer') @@ -252,7 +254,7 @@ def test_comparisons_coverage(self): rng = date_range('1/1/2000', periods=10) # raise TypeError for now - self.assertRaises(TypeError, rng.__lt__, rng[3].value) + pytest.raises(TypeError, rng.__lt__, rng[3].value) result = rng == list(rng) exp = rng == rng @@ -422,15 +424,15 @@ def test_overflow_offset(self): def f(): t + offset - self.assertRaises(OverflowError, f) + pytest.raises(OverflowError, f) def f(): offset + t - self.assertRaises(OverflowError, f) + pytest.raises(OverflowError, f) def f(): t - offset - self.assertRaises(OverflowError, f) + pytest.raises(OverflowError, f) def test_get_duplicates(self): idx = DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-02', @@ -511,7 +513,7 @@ def test_take_fill_value(self): with tm.assertRaisesRegexp(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): idx.take(np.array([1, -5])) def test_take_fill_value_with_timezone(self): @@ -542,7 +544,7 @@ def test_take_fill_value_with_timezone(self): with tm.assertRaisesRegexp(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): idx.take(np.array([1, -5])) def test_map_bug_1677(self): diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index 3cb96eb4e4051..568e045d9f5e7 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -167,7 +167,7 @@ def test_delete(self): self.assertEqual(result.name, expected.name) self.assertEqual(result.freq, expected.freq) - with tm.assertRaises((IndexError, ValueError)): + with pytest.raises((IndexError, ValueError)): # either depeidnig on numpy version result = idx.delete(5) diff --git a/pandas/tests/indexes/datetimes/test_misc.py b/pandas/tests/indexes/datetimes/test_misc.py index d7507360506ca..4c7235fea63e8 100644 --- a/pandas/tests/indexes/datetimes/test_misc.py +++ b/pandas/tests/indexes/datetimes/test_misc.py @@ -1,5 +1,6 @@ -import numpy as np +import pytest +import numpy as np import pandas as pd import pandas.util.testing as tm from pandas import (Index, DatetimeIndex, datetime, offsets, @@ -291,7 +292,7 @@ def test_datetimeindex_accessors(self): # CBD requires np >= 1.7 bday_egypt = offsets.CustomBusinessDay(weekmask='Sun Mon Tue Wed Thu') dti = date_range(datetime(2013, 4, 30), periods=5, freq=bday_egypt) - self.assertRaises(ValueError, lambda: dti.is_month_start) + pytest.raises(ValueError, lambda: dti.is_month_start) dti = DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03']) diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py index f04207caef6ab..2eff8a12dee77 100644 --- a/pandas/tests/indexes/datetimes/test_ops.py +++ b/pandas/tests/indexes/datetimes/test_ops.py @@ -41,14 +41,14 @@ def test_ops_properties_basic(self): # sanity check that the behavior didn't change # GH7206 for op in ['year', 'day', 'second', 'weekday']: - self.assertRaises(TypeError, lambda x: getattr(self.dt_series, op)) + pytest.raises(TypeError, lambda x: getattr(self.dt_series, op)) # attribute access should still work! s = Series(dict(year=2000, month=1, day=10)) self.assertEqual(s.year, 2000) self.assertEqual(s.month, 1) self.assertEqual(s.day, 10) - self.assertRaises(AttributeError, lambda: s.weekday) + pytest.raises(AttributeError, lambda: s.weekday) def test_asobject_tolist(self): idx = pd.date_range(start='2013-01-01', periods=4, freq='M', @@ -446,16 +446,16 @@ def test_add_dti_dti(self): dti = date_range('20130101', periods=3) dti_tz = date_range('20130101', periods=3).tz_localize('US/Eastern') - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): dti + dti - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): dti_tz + dti_tz - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): dti_tz + dti - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): dti + dti_tz def test_difference(self): @@ -521,13 +521,13 @@ def test_sub_dti_dti(self): result = dti_tz - dti_tz tm.assert_index_equal(result, expected) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): dti_tz - dti - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): dti - dti_tz - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): dti_tz - dti_tz2 # isub @@ -537,7 +537,7 @@ def test_sub_dti_dti(self): # different length raises ValueError dti1 = date_range('20130101', periods=3) dti2 = date_range('20130101', periods=4) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): dti1 - dti2 # NaN propagation @@ -555,10 +555,10 @@ def test_sub_period(self): for freq in [None, 'D']: idx = pd.DatetimeIndex(['2011-01-01', '2011-01-02'], freq=freq) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): idx - p - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): p - idx def test_comp_nat(self): diff --git a/pandas/tests/indexes/datetimes/test_partial_slicing.py b/pandas/tests/indexes/datetimes/test_partial_slicing.py index ee704d0b29ddd..9c41e2d823238 100644 --- a/pandas/tests/indexes/datetimes/test_partial_slicing.py +++ b/pandas/tests/indexes/datetimes/test_partial_slicing.py @@ -1,4 +1,7 @@ """ test partial slicing on Series/Frame """ + +import pytest + from datetime import datetime import numpy as np import pandas as pd @@ -67,7 +70,7 @@ def test_partial_slice(self): result = s['2005-1-1'] self.assertEqual(result, s.iloc[0]) - self.assertRaises(Exception, s.__getitem__, '2004-12-31') + pytest.raises(Exception, s.__getitem__, '2004-12-31') def test_partial_slice_daily(self): rng = DatetimeIndex(freq='H', start=datetime(2005, 1, 31), periods=500) @@ -76,7 +79,7 @@ def test_partial_slice_daily(self): result = s['2005-1-31'] tm.assert_series_equal(result, s.iloc[:24]) - self.assertRaises(Exception, s.__getitem__, '2004-12-31 00') + pytest.raises(Exception, s.__getitem__, '2004-12-31 00') def test_partial_slice_hourly(self): rng = DatetimeIndex(freq='T', start=datetime(2005, 1, 1, 20, 0, 0), @@ -90,7 +93,7 @@ def test_partial_slice_hourly(self): tm.assert_series_equal(result, s.iloc[:60]) self.assertEqual(s['2005-1-1 20:00'], s.iloc[0]) - self.assertRaises(Exception, s.__getitem__, '2004-12-31 00:15') + pytest.raises(Exception, s.__getitem__, '2004-12-31 00:15') def test_partial_slice_minutely(self): rng = DatetimeIndex(freq='S', start=datetime(2005, 1, 1, 23, 59, 0), @@ -104,7 +107,7 @@ def test_partial_slice_minutely(self): tm.assert_series_equal(result, s.iloc[:60]) self.assertEqual(s[Timestamp('2005-1-1 23:59:00')], s.iloc[0]) - self.assertRaises(Exception, s.__getitem__, '2004-12-31 00:00:00') + pytest.raises(Exception, s.__getitem__, '2004-12-31 00:00:00') def test_partial_slice_second_precision(self): rng = DatetimeIndex(start=datetime(2005, 1, 1, 0, 0, 59, @@ -152,7 +155,7 @@ def test_partial_slicing_dataframe(self): result = df['a'][ts_string] assert isinstance(result, np.int64) self.assertEqual(result, expected) - self.assertRaises(KeyError, df.__getitem__, ts_string) + pytest.raises(KeyError, df.__getitem__, ts_string) # Timestamp with resolution less precise than index for fmt in formats[:rnum]: @@ -179,15 +182,15 @@ def test_partial_slicing_dataframe(self): result = df['a'][ts_string] assert isinstance(result, np.int64) self.assertEqual(result, 2) - self.assertRaises(KeyError, df.__getitem__, ts_string) + pytest.raises(KeyError, df.__getitem__, ts_string) # Not compatible with existing key # Should raise KeyError for fmt, res in list(zip(formats, resolutions))[rnum + 1:]: ts = index[1] + Timedelta("1 " + res) ts_string = ts.strftime(fmt) - self.assertRaises(KeyError, df['a'].__getitem__, ts_string) - self.assertRaises(KeyError, df.__getitem__, ts_string) + pytest.raises(KeyError, df['a'].__getitem__, ts_string) + pytest.raises(KeyError, df.__getitem__, ts_string) def test_partial_slicing_with_multiindex(self): @@ -216,7 +219,7 @@ def test_partial_slicing_with_multiindex(self): def f(): df_multi.loc[('2013-06-19', 'ACCT1', 'ABC')] - self.assertRaises(KeyError, f) + pytest.raises(KeyError, f) # GH 4294 # partial slice on a series mi diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index faebd4b2761f1..b7427f1935a8c 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -184,8 +184,8 @@ def test_to_datetime_dt64s(self): oob_dts = [np.datetime64('1000-01-01'), np.datetime64('5000-01-02'), ] for dt in oob_dts: - self.assertRaises(ValueError, pd.to_datetime, dt, errors='raise') - self.assertRaises(ValueError, Timestamp, dt) + pytest.raises(ValueError, pd.to_datetime, dt, errors='raise') + pytest.raises(ValueError, Timestamp, dt) self.assertIs(pd.to_datetime(dt, errors='coerce'), NaT) def test_to_datetime_array_of_dt64s(self): @@ -201,8 +201,8 @@ def test_to_datetime_array_of_dt64s(self): # A list of datetimes where the last one is out of bounds dts_with_oob = dts + [np.datetime64('9999-01-01')] - self.assertRaises(ValueError, pd.to_datetime, dts_with_oob, - errors='raise') + pytest.raises(ValueError, pd.to_datetime, dts_with_oob, + errors='raise') tm.assert_numpy_array_equal( pd.to_datetime(dts_with_oob, box=False, errors='coerce'), @@ -241,7 +241,7 @@ def test_to_datetime_tz(self): # mixed tzs will raise arr = [pd.Timestamp('2013-01-01 13:00:00', tz='US/Pacific'), pd.Timestamp('2013-01-02 14:00:00', tz='US/Eastern')] - self.assertRaises(ValueError, lambda: pd.to_datetime(arr)) + pytest.raises(ValueError, lambda: pd.to_datetime(arr)) def test_to_datetime_tz_pytz(self): @@ -309,17 +309,17 @@ def test_to_datetime_tz_psycopg2(self): def test_datetime_bool(self): # GH13176 - with self.assertRaises(TypeError): + with pytest.raises(TypeError): to_datetime(False) self.assertTrue(to_datetime(False, errors="coerce") is NaT) self.assertEqual(to_datetime(False, errors="ignore"), False) - with self.assertRaises(TypeError): + with pytest.raises(TypeError): to_datetime(True) self.assertTrue(to_datetime(True, errors="coerce") is NaT) self.assertEqual(to_datetime(True, errors="ignore"), True) - with self.assertRaises(TypeError): + with pytest.raises(TypeError): to_datetime([False, datetime.today()]) - with self.assertRaises(TypeError): + with pytest.raises(TypeError): to_datetime(['20130101', True]) tm.assert_index_equal(to_datetime([0, False, NaT, 0.0], errors="coerce"), @@ -329,9 +329,9 @@ def test_datetime_bool(self): def test_datetime_invalid_datatype(self): # GH13176 - with self.assertRaises(TypeError): + with pytest.raises(TypeError): pd.to_datetime(bool) - with self.assertRaises(TypeError): + with pytest.raises(TypeError): pd.to_datetime(pd.to_datetime) @@ -341,7 +341,7 @@ def test_unit(self): # GH 11758 # test proper behavior with erros - with self.assertRaises(ValueError): + with pytest.raises(ValueError): to_datetime([1], unit='D', format='%Y%m%d') values = [11111111, 1, 1.0, tslib.iNaT, NaT, np.nan, @@ -358,7 +358,7 @@ def test_unit(self): 'NaT', 'NaT', 'NaT', 'NaT', 'NaT']) tm.assert_index_equal(result, expected) - with self.assertRaises(tslib.OutOfBoundsDatetime): + with pytest.raises(tslib.OutOfBoundsDatetime): to_datetime(values, unit='D', errors='raise') values = [1420043460000, tslib.iNaT, NaT, np.nan, 'NaT'] @@ -372,7 +372,7 @@ def test_unit(self): expected = DatetimeIndex(['NaT', 'NaT', 'NaT', 'NaT', 'NaT']) tm.assert_index_equal(result, expected) - with self.assertRaises(tslib.OutOfBoundsDatetime): + with pytest.raises(tslib.OutOfBoundsDatetime): to_datetime(values, errors='raise', unit='s') # if we have a string, then we raise a ValueError @@ -441,7 +441,7 @@ def test_unit_mixed(self): result = pd.to_datetime(arr, errors='coerce') tm.assert_index_equal(result, expected) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): pd.to_datetime(arr, errors='raise') expected = DatetimeIndex(['NaT', @@ -451,7 +451,7 @@ def test_unit_mixed(self): result = pd.to_datetime(arr, errors='coerce') tm.assert_index_equal(result, expected) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): pd.to_datetime(arr, errors='raise') def test_dataframe(self): @@ -529,7 +529,7 @@ def test_dataframe(self): df2 = DataFrame({'year': [2015, 2016], 'month': [2, 20], 'day': [4, 5]}) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): to_datetime(df2) result = to_datetime(df2, errors='coerce') expected = Series([Timestamp('20150204 00:00:00'), @@ -537,7 +537,7 @@ def test_dataframe(self): assert_series_equal(result, expected) # extra columns - with self.assertRaises(ValueError): + with pytest.raises(ValueError): df2 = df.copy() df2['foo'] = 1 to_datetime(df2) @@ -548,7 +548,7 @@ def test_dataframe(self): ['year', 'month', 'second'], ['month', 'day'], ['year', 'day', 'second']]: - with self.assertRaises(ValueError): + with pytest.raises(ValueError): to_datetime(df[c]) # duplicates @@ -556,7 +556,7 @@ def test_dataframe(self): 'month': [2, 20], 'day': [4, 5]}) df2.columns = ['year', 'year', 'day'] - with self.assertRaises(ValueError): + with pytest.raises(ValueError): to_datetime(df2) df2 = DataFrame({'year': [2015, 2016], @@ -564,7 +564,7 @@ def test_dataframe(self): 'day': [4, 5], 'hour': [4, 5]}) df2.columns = ['year', 'month', 'day', 'day'] - with self.assertRaises(ValueError): + with pytest.raises(ValueError): to_datetime(df2) def test_dataframe_dtypes(self): @@ -591,7 +591,7 @@ def test_dataframe_dtypes(self): df = DataFrame({'year': [2000, 2001], 'month': [1.5, 1], 'day': [1, 1]}) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): to_datetime(df) @@ -631,7 +631,7 @@ def test_to_datetime_default(self): # dayfirst is essentially broken # to_datetime('01-13-2012', dayfirst=True) - # self.assertRaises(ValueError, to_datetime('01-13-2012', + # pytest.raises(ValueError, to_datetime('01-13-2012', # dayfirst=True)) def test_to_datetime_on_datetime64_series(self): @@ -644,7 +644,7 @@ def test_to_datetime_on_datetime64_series(self): def test_to_datetime_with_space_in_series(self): # GH 6428 s = Series(['10/18/2006', '10/18/2008', ' ']) - tm.assertRaises(ValueError, lambda: to_datetime(s, errors='raise')) + pytest.raises(ValueError, lambda: to_datetime(s, errors='raise')) result_coerce = to_datetime(s, errors='coerce') expected_coerce = Series([datetime(2006, 10, 18), datetime(2008, 10, 18), @@ -665,12 +665,12 @@ def test_to_datetime_with_apply(self): assert_series_equal(result, expected) td = pd.Series(['May 04', 'Jun 02', ''], index=[1, 2, 3]) - self.assertRaises(ValueError, - lambda: pd.to_datetime(td, format='%b %y', - errors='raise')) - self.assertRaises(ValueError, - lambda: td.apply(pd.to_datetime, format='%b %y', - errors='raise')) + pytest.raises(ValueError, + lambda: pd.to_datetime(td, format='%b %y', + errors='raise')) + pytest.raises(ValueError, + lambda: td.apply(pd.to_datetime, format='%b %y', + errors='raise')) expected = pd.to_datetime(td, format='%b %y', errors='coerce') result = td.apply( @@ -713,7 +713,7 @@ def test_to_datetime_unprocessable_input(self): to_datetime([1, '1'], errors='ignore'), np.array([1, '1'], dtype='O') ) - self.assertRaises(TypeError, to_datetime, [1, '1'], errors='raise') + pytest.raises(TypeError, to_datetime, [1, '1'], errors='raise') def test_to_datetime_other_datetime64_units(self): # 5/25/2012 @@ -767,13 +767,13 @@ def test_string_na_nat_conversion(self): malformed = np.array(['1/100/2000', np.nan], dtype=object) # GH 10636, default is now 'raise' - self.assertRaises(ValueError, - lambda: to_datetime(malformed, errors='raise')) + pytest.raises(ValueError, + lambda: to_datetime(malformed, errors='raise')) result = to_datetime(malformed, errors='ignore') tm.assert_numpy_array_equal(result, malformed) - self.assertRaises(ValueError, to_datetime, malformed, errors='raise') + pytest.raises(ValueError, to_datetime, malformed, errors='raise') idx = ['a', 'b', 'c', 'd', 'e'] series = Series(['1/1/2000', np.nan, '1/3/2000', np.nan, @@ -1002,14 +1002,14 @@ def test_day_not_in_month_coerce(self): errors='coerce'))) def test_day_not_in_month_raise(self): - self.assertRaises(ValueError, to_datetime, '2015-02-29', - errors='raise') - self.assertRaises(ValueError, to_datetime, '2015-02-29', - errors='raise', format="%Y-%m-%d") - self.assertRaises(ValueError, to_datetime, '2015-02-32', - errors='raise', format="%Y-%m-%d") - self.assertRaises(ValueError, to_datetime, '2015-04-31', - errors='raise', format="%Y-%m-%d") + pytest.raises(ValueError, to_datetime, '2015-02-29', + errors='raise') + pytest.raises(ValueError, to_datetime, '2015-02-29', + errors='raise', format="%Y-%m-%d") + pytest.raises(ValueError, to_datetime, '2015-02-32', + errors='raise', format="%Y-%m-%d") + pytest.raises(ValueError, to_datetime, '2015-04-31', + errors='raise', format="%Y-%m-%d") def test_day_not_in_month_ignore(self): self.assertEqual(to_datetime( @@ -1139,7 +1139,7 @@ def test_parsers_quarter_invalid(self): cases = ['2Q 2005', '2Q-200A', '2Q-200', '22Q2005', '6Q-20', '2Q200.'] for case in cases: - self.assertRaises(ValueError, tools.parse_time_string, case) + pytest.raises(ValueError, tools.parse_time_string, case) def test_parsers_dayfirst_yearfirst(self): tm._skip_if_no_dateutil() @@ -1272,7 +1272,7 @@ def test_parsers_time(self): self.assertEqual(tools.to_time(time_string), expected) new_string = "14.15" - self.assertRaises(ValueError, tools.to_time, new_string) + pytest.raises(ValueError, tools.to_time, new_string) self.assertEqual(tools.to_time(new_string, format="%H.%M"), expected) arg = ["14:15", "20:20"] @@ -1287,7 +1287,7 @@ def test_parsers_time(self): res = tools.to_time(arg, format="%I:%M%p", errors="ignore") tm.assert_numpy_array_equal(res, np.array(arg, dtype=np.object_)) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): tools.to_time(arg, format="%I:%M%p", errors="raise") tm.assert_series_equal(tools.to_time(Series(arg, name="test")), @@ -1375,7 +1375,7 @@ def test_parsers_iso8601(self): # wrong separator for HHMMSS '2001-01-01 12-34-56'] for date_str in invalid_cases: - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): tslib._test_parse_iso8601(date_str) # If no ValueError raised, let me know which case failed. raise Exception(date_str) @@ -1459,11 +1459,10 @@ def test_coercing_dates_outside_of_datetime64_ns_bounds(self): ] for invalid_date in invalid_dates: - self.assertRaises(ValueError, - tslib.array_to_datetime, - np.array( - [invalid_date], dtype='object'), - errors='raise', ) + pytest.raises(ValueError, + tslib.array_to_datetime, + np.array([invalid_date], dtype='object'), + errors='raise', ) tm.assert_numpy_array_equal( tslib.array_to_datetime( np.array([invalid_date], dtype='object'), diff --git a/pandas/tests/indexes/period/test_asfreq.py b/pandas/tests/indexes/period/test_asfreq.py index adf68605b65db..4d1fe9c46f126 100644 --- a/pandas/tests/indexes/period/test_asfreq.py +++ b/pandas/tests/indexes/period/test_asfreq.py @@ -1,5 +1,6 @@ -import numpy as np +import pytest +import numpy as np import pandas as pd from pandas.util import testing as tm from pandas import PeriodIndex, Series, DataFrame @@ -69,7 +70,7 @@ def test_asfreq(self): self.assertEqual(pi7.asfreq('H', 'S'), pi5) self.assertEqual(pi7.asfreq('Min', 'S'), pi6) - self.assertRaises(ValueError, pi7.asfreq, 'T', 'foo') + pytest.raises(ValueError, pi7.asfreq, 'T', 'foo') result1 = pi1.asfreq('3M') result2 = pi1.asfreq('M') expected = PeriodIndex(freq='M', start='2001-12', end='2001-12') diff --git a/pandas/tests/indexes/period/test_construction.py b/pandas/tests/indexes/period/test_construction.py index 4e53ac56ec187..8f2b03829b128 100644 --- a/pandas/tests/indexes/period/test_construction.py +++ b/pandas/tests/indexes/period/test_construction.py @@ -1,5 +1,6 @@ -import numpy as np +import pytest +import numpy as np import pandas as pd import pandas.util.testing as tm import pandas.core.indexes.period as period @@ -58,12 +59,12 @@ def test_constructor_field_arrays(self): years = [2007, 2007, 2007] months = [1, 2] - self.assertRaises(ValueError, PeriodIndex, year=years, month=months, - freq='M') - self.assertRaises(ValueError, PeriodIndex, year=years, month=months, - freq='2M') - self.assertRaises(ValueError, PeriodIndex, year=years, month=months, - freq='M', start=Period('2007-01', freq='M')) + pytest.raises(ValueError, PeriodIndex, year=years, month=months, + freq='M') + pytest.raises(ValueError, PeriodIndex, year=years, month=months, + freq='2M') + pytest.raises(ValueError, PeriodIndex, year=years, month=months, + freq='M', start=Period('2007-01', freq='M')) years = [2007, 2007, 2007] months = [1, 2, 3] @@ -73,8 +74,8 @@ def test_constructor_field_arrays(self): def test_constructor_U(self): # U was used as undefined period - self.assertRaises(ValueError, period_range, '2007-1-1', periods=500, - freq='X') + pytest.raises(ValueError, period_range, '2007-1-1', periods=500, + freq='X') def test_constructor_nano(self): idx = period_range(start=Period(ordinal=1, freq='N'), @@ -95,17 +96,17 @@ def test_constructor_arrays_negative_year(self): tm.assert_index_equal(pindex.quarter, pd.Index(quarters)) def test_constructor_invalid_quarters(self): - self.assertRaises(ValueError, PeriodIndex, year=lrange(2000, 2004), - quarter=lrange(4), freq='Q-DEC') + pytest.raises(ValueError, PeriodIndex, year=lrange(2000, 2004), + quarter=lrange(4), freq='Q-DEC') def test_constructor_corner(self): - self.assertRaises(ValueError, PeriodIndex, periods=10, freq='A') + pytest.raises(ValueError, PeriodIndex, periods=10, freq='A') start = Period('2007', freq='A-JUN') end = Period('2010', freq='A-DEC') - self.assertRaises(ValueError, PeriodIndex, start=start, end=end) - self.assertRaises(ValueError, PeriodIndex, start=start) - self.assertRaises(ValueError, PeriodIndex, end=end) + pytest.raises(ValueError, PeriodIndex, start=start, end=end) + pytest.raises(ValueError, PeriodIndex, start=start) + pytest.raises(ValueError, PeriodIndex, end=end) result = period_range('2007-01', periods=10.5, freq='M') exp = period_range('2007-01', periods=10, freq='M') @@ -118,10 +119,10 @@ def test_constructor_fromarraylike(self): tm.assert_index_equal(PeriodIndex(idx.values), idx) tm.assert_index_equal(PeriodIndex(list(idx.values)), idx) - self.assertRaises(ValueError, PeriodIndex, idx._values) - self.assertRaises(ValueError, PeriodIndex, list(idx._values)) - self.assertRaises(TypeError, PeriodIndex, - data=Period('2007', freq='A')) + pytest.raises(ValueError, PeriodIndex, idx._values) + pytest.raises(ValueError, PeriodIndex, list(idx._values)) + pytest.raises(TypeError, PeriodIndex, + data=Period('2007', freq='A')) result = PeriodIndex(iter(idx)) tm.assert_index_equal(result, idx) @@ -152,7 +153,7 @@ def test_constructor_datetime64arr(self): vals = np.arange(100000, 100000 + 10000, 100, dtype=np.int64) vals = vals.view(np.dtype('M8[us]')) - self.assertRaises(ValueError, PeriodIndex, vals, freq='D') + pytest.raises(ValueError, PeriodIndex, vals, freq='D') def test_constructor_dtype(self): # passing a dtype with a tz should localize @@ -288,17 +289,17 @@ def test_constructor_simple_new_empty(self): def test_constructor_floats(self): # GH13079 for floats in [[1.1, 2.1], np.array([1.1, 2.1])]: - with self.assertRaises(TypeError): + with pytest.raises(TypeError): pd.PeriodIndex._simple_new(floats, freq='M') - with self.assertRaises(TypeError): + with pytest.raises(TypeError): pd.PeriodIndex(floats, freq='M') def test_constructor_nat(self): - self.assertRaises(ValueError, period_range, start='NaT', - end='2011-01-01', freq='M') - self.assertRaises(ValueError, period_range, start='2011-01-01', - end='NaT', freq='M') + pytest.raises(ValueError, period_range, start='NaT', + end='2011-01-01', freq='M') + pytest.raises(ValueError, period_range, start='2011-01-01', + end='NaT', freq='M') def test_constructor_year_and_quarter(self): year = pd.Series([2001, 2002, 2003]) @@ -427,9 +428,9 @@ def test_constructor(self): # Mixed freq should fail vals = [end_intv, Period('2006-12-31', 'w')] - self.assertRaises(ValueError, PeriodIndex, vals) + pytest.raises(ValueError, PeriodIndex, vals) vals = np.array(vals) - self.assertRaises(ValueError, PeriodIndex, vals) + pytest.raises(ValueError, PeriodIndex, vals) def test_constructor_error(self): start = Period('02-Apr-2005', 'B') @@ -478,7 +479,7 @@ def setUp(self): self.series = Series(period_range('2000-01-01', periods=10, freq='D')) def test_constructor_cant_cast_period(self): - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): Series(period_range('2000-01-01', periods=10, freq='D'), dtype=float) diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py index 419a917415f98..982ac7d96a9cc 100644 --- a/pandas/tests/indexes/period/test_indexing.py +++ b/pandas/tests/indexes/period/test_indexing.py @@ -1,5 +1,7 @@ from datetime import datetime +import pytest + import numpy as np import pandas as pd from pandas.util import testing as tm @@ -76,7 +78,7 @@ def test_getitem_partial(self): rng = period_range('2007-01', periods=50, freq='M') ts = Series(np.random.randn(len(rng)), rng) - self.assertRaises(KeyError, ts.__getitem__, '2006') + pytest.raises(KeyError, ts.__getitem__, '2006') result = ts['2008'] self.assertTrue((result.index.year == 2008).all()) @@ -148,13 +150,13 @@ def test_getitem_seconds(self): '2013/02/01 09:00'] for v in values: if _np_version_under1p9: - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): idx[v] else: # GH7116 # these show deprecations as we are trying # to slice with non-integer indexers - # with tm.assertRaises(IndexError): + # with pytest.raises(IndexError): # idx[v] continue @@ -177,13 +179,13 @@ def test_getitem_day(self): for v in values: if _np_version_under1p9: - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): idx[v] else: # GH7116 # these show deprecations as we are trying # to slice with non-integer indexers - # with tm.assertRaises(IndexError): + # with pytest.raises(IndexError): # idx[v] continue @@ -194,7 +196,7 @@ def test_getitem_day(self): invalid = ['2013/02/01 9H', '2013/02/01 09:00'] for v in invalid: - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): s[v] @@ -203,7 +205,7 @@ class TestIndexing(tm.TestCase): def test_get_loc_msg(self): idx = period_range('2000-1-1', freq='A', periods=10) bad_period = Period('2012', 'A') - self.assertRaises(KeyError, idx.get_loc, bad_period) + pytest.raises(KeyError, idx.get_loc, bad_period) try: idx.get_loc(bad_period) @@ -314,5 +316,5 @@ def test_take_fill_value(self): with tm.assertRaisesRegexp(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): idx.take(np.array([1, -5])) diff --git a/pandas/tests/indexes/period/test_ops.py b/pandas/tests/indexes/period/test_ops.py index dd91e19c5a9c5..70a27eada7774 100644 --- a/pandas/tests/indexes/period/test_ops.py +++ b/pandas/tests/indexes/period/test_ops.py @@ -1,3 +1,5 @@ +import pytest + import numpy as np from datetime import timedelta @@ -287,10 +289,10 @@ def test_add_iadd(self): other = pd.period_range('1/6/2000', freq='D', periods=5) # previously performed setop union, now raises TypeError (GH14164) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): rng + other - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): rng += other # offset @@ -392,10 +394,10 @@ def test_sub_isub(self): rng = pd.period_range('1/1/2000', freq='D', periods=5) other = pd.period_range('1/6/2000', freq='D', periods=5) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): rng - other - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): rng -= other # offset @@ -747,7 +749,7 @@ def test_shift(self): # GH 9903 idx = pd.PeriodIndex([], name='xxx', freq='H') - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): # period shift doesn't accept freq idx.shift(1, freq='H') @@ -885,29 +887,29 @@ def test_pi_ops_errors(self): with tm.assertRaisesRegexp(TypeError, msg): obj + ng - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): # error message differs between PY2 and 3 ng + obj with tm.assertRaisesRegexp(TypeError, msg): obj - ng - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): np.add(obj, ng) if _np_version_under1p10: self.assertIs(np.add(ng, obj), NotImplemented) else: - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): np.add(ng, obj) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): np.subtract(obj, ng) if _np_version_under1p10: self.assertIs(np.subtract(ng, obj), NotImplemented) else: - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): np.subtract(ng, obj) def test_pi_ops_nat(self): diff --git a/pandas/tests/indexes/period/test_partial_slicing.py b/pandas/tests/indexes/period/test_partial_slicing.py index b051c4a0dcab1..a8ac6a3e55fe5 100644 --- a/pandas/tests/indexes/period/test_partial_slicing.py +++ b/pandas/tests/indexes/period/test_partial_slicing.py @@ -1,3 +1,5 @@ +import pytest + import numpy as np import pandas as pd @@ -75,7 +77,7 @@ def test_range_slice_day(self): values = ['2014', '2013/02', '2013/01/02', '2013/02/01 9H', '2013/02/01 09:00'] for v in values: - with tm.assertRaises(exc): + with pytest.raises(exc): idx[v:] s = Series(np.random.rand(len(idx)), index=idx) @@ -87,7 +89,7 @@ def test_range_slice_day(self): invalid = ['2013/02/01 9H', '2013/02/01 09:00'] for v in invalid: - with tm.assertRaises(exc): + with pytest.raises(exc): idx[v:] def test_range_slice_seconds(self): @@ -105,7 +107,7 @@ def test_range_slice_seconds(self): values = ['2014', '2013/02', '2013/01/02', '2013/02/01 9H', '2013/02/01 09:00'] for v in values: - with tm.assertRaises(exc): + with pytest.raises(exc): idx[v:] s = Series(np.random.rand(len(idx)), index=idx) diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index bb87e780012ce..9f72c10316c90 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -47,10 +47,10 @@ def test_astype_raises(self): # GH 13149, GH 13209 idx = PeriodIndex(['2016-05-16', 'NaT', NaT, np.NaN], freq='D') - self.assertRaises(ValueError, idx.astype, str) - self.assertRaises(ValueError, idx.astype, float) - self.assertRaises(ValueError, idx.astype, 'timedelta64') - self.assertRaises(ValueError, idx.astype, 'timedelta64[ns]') + pytest.raises(ValueError, idx.astype, str) + pytest.raises(ValueError, idx.astype, float) + pytest.raises(ValueError, idx.astype, 'timedelta64') + pytest.raises(ValueError, idx.astype, 'timedelta64[ns]') def test_pickle_compat_construction(self): pass @@ -88,7 +88,7 @@ def test_get_loc(self): msg = 'Input has different freq from PeriodIndex\\(freq=D\\)' with tm.assertRaisesRegexp(ValueError, msg): idx.get_loc('2000-01-10', method='nearest', tolerance='1 hour') - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): idx.get_loc('2000-01-10', method='nearest', tolerance='1 day') def test_where(self): @@ -197,10 +197,10 @@ def test_fillna_period(self): pd.Period('2011-01-01', freq='D')), exp) def test_no_millisecond_field(self): - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): DatetimeIndex.millisecond - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): DatetimeIndex([]).millisecond def test_difference_freq(self): @@ -355,9 +355,9 @@ def test_period_index_length(self): # Mixed freq should fail vals = [end_intv, Period('2006-12-31', 'w')] - self.assertRaises(ValueError, PeriodIndex, vals) + pytest.raises(ValueError, PeriodIndex, vals) vals = np.array(vals) - self.assertRaises(ValueError, PeriodIndex, vals) + pytest.raises(ValueError, PeriodIndex, vals) def test_fields(self): # year, month, day, hour, minute @@ -530,7 +530,7 @@ def test_contains_nat(self): self.assertTrue(np.nan in idx) def test_periods_number_check(self): - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): period_range('2011-1-1', '2012-1-1', 'B') def test_start_time(self): @@ -720,7 +720,7 @@ def test_is_full(self): self.assertTrue(index.is_full) index = PeriodIndex([2006, 2005, 2005], freq='A') - self.assertRaises(ValueError, getattr, index, 'is_full') + pytest.raises(ValueError, getattr, index, 'is_full') self.assertTrue(index[:0].is_full) diff --git a/pandas/tests/indexes/period/test_setops.py b/pandas/tests/indexes/period/test_setops.py index e142b5179ad55..54dafd832fd23 100644 --- a/pandas/tests/indexes/period/test_setops.py +++ b/pandas/tests/indexes/period/test_setops.py @@ -1,3 +1,5 @@ +import pytest + import numpy as np import pandas as pd @@ -106,7 +108,7 @@ def test_union_misc(self): # raise if different frequencies index = period_range('1/1/2000', '1/20/2000', freq='D') index2 = period_range('1/1/2000', '1/20/2000', freq='W-WED') - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): index.union(index2) msg = 'can only call with other PeriodIndex-ed objects' @@ -114,7 +116,7 @@ def test_union_misc(self): index.join(index.to_timestamp()) index3 = period_range('1/1/2000', '1/20/2000', freq='2D') - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): index.join(index3) def test_union_dataframe_index(self): @@ -143,11 +145,11 @@ def test_intersection(self): # raise if different frequencies index = period_range('1/1/2000', '1/20/2000', freq='D') index2 = period_range('1/1/2000', '1/20/2000', freq='W-WED') - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): index.intersection(index2) index3 = period_range('1/1/2000', '1/20/2000', freq='2D') - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): index.intersection(index3) def test_intersection_cases(self): diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 221bd8d50cee6..695d3aa7ebe3a 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1,5 +1,7 @@ # -*- coding: utf-8 -*- +import pytest + from datetime import datetime, timedelta import pandas.util.testing as tm @@ -83,11 +85,11 @@ def test_constructor(self): # what to do here? # arr = np.array(5.) - # self.assertRaises(Exception, arr.view, Index) + # pytest.raises(Exception, arr.view, Index) def test_constructor_corner(self): # corner case - self.assertRaises(TypeError, Index, 0) + pytest.raises(TypeError, Index, 0) def test_construction_list_mixed_tuples(self): # see gh-10697: if we are constructing from a mixed list of tuples, @@ -387,7 +389,7 @@ def test_view_with_args(self): ind = self.indices[i] # with arguments - self.assertRaises(TypeError, lambda: ind.view('i8')) + pytest.raises(TypeError, lambda: ind.view('i8')) # these are ok for i in list(set(self.indices.keys()) - set(restricted)): @@ -454,7 +456,7 @@ def test_delete(self): tm.assert_index_equal(result, expected) self.assertEqual(result.name, expected.name) - with tm.assertRaises((IndexError, ValueError)): + with pytest.raises((IndexError, ValueError)): # either depending on numpy version result = idx.delete(5) @@ -589,7 +591,7 @@ def test_empty_fancy(self): # np.ndarray only accepts ndarray of int & bool dtypes, so should # Index. - self.assertRaises(IndexError, idx.__getitem__, empty_farr) + pytest.raises(IndexError, idx.__getitem__, empty_farr) def test_getitem(self): arr = np.array(self.dateIndex) @@ -773,10 +775,10 @@ def test_add(self): def test_sub(self): idx = self.strIndex - self.assertRaises(TypeError, lambda: idx - 'a') - self.assertRaises(TypeError, lambda: idx - idx) - self.assertRaises(TypeError, lambda: idx - idx.tolist()) - self.assertRaises(TypeError, lambda: idx.tolist() - idx) + pytest.raises(TypeError, lambda: idx - 'a') + pytest.raises(TypeError, lambda: idx - idx) + pytest.raises(TypeError, lambda: idx - idx.tolist()) + pytest.raises(TypeError, lambda: idx.tolist() - idx) def test_map_identity_mapping(self): # GH 12766 @@ -1126,10 +1128,10 @@ def test_get_indexer_strings(self): expected = np.array([0, 0, 1, -1], dtype=np.intp) tm.assert_numpy_array_equal(actual, expected) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): idx.get_indexer(['a', 'b', 'c', 'd'], method='nearest') - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): idx.get_indexer(['a', 'b', 'c', 'd'], method='pad', tolerance=2) def test_get_loc(self): @@ -1139,7 +1141,7 @@ def test_get_loc(self): self.assertEqual(idx.get_loc(1, method=method), 1) if method is not None: self.assertEqual(idx.get_loc(1, method=method, tolerance=0), 1) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): idx.get_loc([1, 2], method=method) for method, loc in [('pad', 1), ('backfill', 2), ('nearest', 1)]: @@ -1149,7 +1151,7 @@ def test_get_loc(self): self.assertEqual(idx.get_loc(1.1, method, tolerance=1), loc) for method in ['pad', 'backfill', 'nearest']: - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): idx.get_loc(1.1, method, tolerance=0.05) with tm.assertRaisesRegexp(ValueError, 'must be numeric'): @@ -1158,9 +1160,9 @@ def test_get_loc(self): idx.get_loc(1.1, tolerance=1) idx = pd.Index(['a', 'c']) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): idx.get_loc('a', method='nearest') - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): idx.get_loc('a', method='pad', tolerance='invalid') def test_slice_locs(self): @@ -1192,15 +1194,15 @@ def test_slice_locs(self): # int slicing with floats # GH 4892, these are all TypeErrors idx = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=int)) - self.assertRaises(TypeError, - lambda: idx.slice_locs(5.0, 10.0), (3, n)) - self.assertRaises(TypeError, - lambda: idx.slice_locs(4.5, 10.5), (3, 8)) + pytest.raises(TypeError, + lambda: idx.slice_locs(5.0, 10.0), (3, n)) + pytest.raises(TypeError, + lambda: idx.slice_locs(4.5, 10.5), (3, 8)) idx2 = idx[::-1] - self.assertRaises(TypeError, - lambda: idx2.slice_locs(8.5, 1.5), (2, 6)) - self.assertRaises(TypeError, - lambda: idx2.slice_locs(10.5, -1), (0, n)) + pytest.raises(TypeError, + lambda: idx2.slice_locs(8.5, 1.5), (2, 6)) + pytest.raises(TypeError, + lambda: idx2.slice_locs(10.5, -1), (0, n)) def test_slice_locs_dup(self): idx = Index(['a', 'a', 'b', 'c', 'd', 'd']) @@ -1226,8 +1228,8 @@ def test_slice_locs_dup(self): def test_slice_locs_na(self): idx = Index([np.nan, 1, 2]) - self.assertRaises(KeyError, idx.slice_locs, start=1.5) - self.assertRaises(KeyError, idx.slice_locs, end=1.5) + pytest.raises(KeyError, idx.slice_locs, start=1.5) + pytest.raises(KeyError, idx.slice_locs, end=1.5) self.assertEqual(idx.slice_locs(1), (1, 3)) self.assertEqual(idx.slice_locs(np.nan), (0, 3)) @@ -1268,8 +1270,8 @@ def test_drop(self): expected = self.strIndex[lrange(5) + lrange(10, n)] tm.assert_index_equal(dropped, expected) - self.assertRaises(ValueError, self.strIndex.drop, ['foo', 'bar']) - self.assertRaises(ValueError, self.strIndex.drop, ['1', 'bar']) + pytest.raises(ValueError, self.strIndex.drop, ['foo', 'bar']) + pytest.raises(ValueError, self.strIndex.drop, ['1', 'bar']) # errors='ignore' mixed = drop.tolist() + ['foo'] @@ -1291,7 +1293,7 @@ def test_drop(self): tm.assert_index_equal(dropped, expected) # errors='ignore' - self.assertRaises(ValueError, ser.drop, [3, 4]) + pytest.raises(ValueError, ser.drop, [3, 4]) dropped = ser.drop(4, errors='ignore') expected = Index([1, 2, 3]) @@ -1388,19 +1390,19 @@ def check_idx(idx): tm.assert_numpy_array_equal(expected, idx.isin(values, level=0)) tm.assert_numpy_array_equal(expected, idx.isin(values, level=-1)) - self.assertRaises(IndexError, idx.isin, values, level=1) - self.assertRaises(IndexError, idx.isin, values, level=10) - self.assertRaises(IndexError, idx.isin, values, level=-2) + pytest.raises(IndexError, idx.isin, values, level=1) + pytest.raises(IndexError, idx.isin, values, level=10) + pytest.raises(IndexError, idx.isin, values, level=-2) - self.assertRaises(KeyError, idx.isin, values, level=1.0) - self.assertRaises(KeyError, idx.isin, values, level='foobar') + pytest.raises(KeyError, idx.isin, values, level=1.0) + pytest.raises(KeyError, idx.isin, values, level='foobar') idx.name = 'foobar' tm.assert_numpy_array_equal(expected, idx.isin(values, level='foobar')) - self.assertRaises(KeyError, idx.isin, values, level='xyzzy') - self.assertRaises(KeyError, idx.isin, values, level=np.nan) + pytest.raises(KeyError, idx.isin, values, level='xyzzy') + pytest.raises(KeyError, idx.isin, values, level=np.nan) check_idx(Index(['qux', 'baz', 'foo', 'bar'])) # Float64Index overrides isin, so must be checked separately @@ -1529,7 +1531,7 @@ def test_take_fill_value(self): with tm.assertRaisesRegexp(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): idx.take(np.array([1, -5])) def test_reshape_raise(self): diff --git a/pandas/tests/indexes/test_category.py b/pandas/tests/indexes/test_category.py index 18842f7886cad..057ea1a416275 100644 --- a/pandas/tests/indexes/test_category.py +++ b/pandas/tests/indexes/test_category.py @@ -131,12 +131,12 @@ def test_disallow_set_ops(self): # set ops (+/-) raise TypeError idx = pd.Index(pd.Categorical(['a', 'b'])) - self.assertRaises(TypeError, lambda: idx - idx) - self.assertRaises(TypeError, lambda: idx + idx) - self.assertRaises(TypeError, lambda: idx - ['a', 'b']) - self.assertRaises(TypeError, lambda: idx + ['a', 'b']) - self.assertRaises(TypeError, lambda: ['a', 'b'] - idx) - self.assertRaises(TypeError, lambda: ['a', 'b'] + idx) + pytest.raises(TypeError, lambda: idx - idx) + pytest.raises(TypeError, lambda: idx + idx) + pytest.raises(TypeError, lambda: idx - ['a', 'b']) + pytest.raises(TypeError, lambda: idx + ['a', 'b']) + pytest.raises(TypeError, lambda: ['a', 'b'] - idx) + pytest.raises(TypeError, lambda: ['a', 'b'] + idx) def test_method_delegation(self): @@ -170,7 +170,7 @@ def test_method_delegation(self): list('aabbca'), categories=list('cabdef'), ordered=True)) # invalid - self.assertRaises(ValueError, lambda: ci.set_categories( + pytest.raises(ValueError, lambda: ci.set_categories( list('cab'), inplace=True)) def test_contains(self): @@ -193,8 +193,8 @@ def test_contains(self): def test_min_max(self): ci = self.create_index(ordered=False) - self.assertRaises(TypeError, lambda: ci.min()) - self.assertRaises(TypeError, lambda: ci.max()) + pytest.raises(TypeError, lambda: ci.min()) + pytest.raises(TypeError, lambda: ci.max()) ci = self.create_index(ordered=True) @@ -275,10 +275,10 @@ def test_append(self): tm.assert_index_equal(result, ci, exact=True) # appending with different categories or reoreded is not ok - self.assertRaises( + pytest.raises( TypeError, lambda: ci.append(ci.values.set_categories(list('abcd')))) - self.assertRaises( + pytest.raises( TypeError, lambda: ci.append(ci.values.reorder_categories(list('abc')))) @@ -288,7 +288,7 @@ def test_append(self): tm.assert_index_equal(result, expected, exact=True) # invalid objects - self.assertRaises(TypeError, lambda: ci.append(Index(['a', 'd']))) + pytest.raises(TypeError, lambda: ci.append(Index(['a', 'd']))) # GH14298 - if base object is not categorical -> coerce to object result = Index(['c', 'a']).append(ci) @@ -316,7 +316,7 @@ def test_insert(self): tm.assert_index_equal(result, expected, exact=True) # invalid - self.assertRaises(TypeError, lambda: ci.insert(0, 'd')) + pytest.raises(TypeError, lambda: ci.insert(0, 'd')) def test_delete(self): @@ -439,12 +439,12 @@ def test_get_indexer(self): r1 = idx1.get_indexer(idx2) assert_almost_equal(r1, np.array([0, 1, 2, -1], dtype=np.intp)) - self.assertRaises(NotImplementedError, - lambda: idx2.get_indexer(idx1, method='pad')) - self.assertRaises(NotImplementedError, - lambda: idx2.get_indexer(idx1, method='backfill')) - self.assertRaises(NotImplementedError, - lambda: idx2.get_indexer(idx1, method='nearest')) + pytest.raises(NotImplementedError, + lambda: idx2.get_indexer(idx1, method='pad')) + pytest.raises(NotImplementedError, + lambda: idx2.get_indexer(idx1, method='backfill')) + pytest.raises(NotImplementedError, + lambda: idx2.get_indexer(idx1, method='nearest')) def test_get_loc(self): # GH 12531 @@ -454,7 +454,7 @@ def test_get_loc(self): self.assertEqual(cidx1.get_loc('e'), idx1.get_loc('e')) for i in [cidx1, idx1]: - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): i.get_loc('NOT-EXIST') # non-unique @@ -472,7 +472,7 @@ def test_get_loc(self): self.assertEqual(res, 4) for i in [cidx2, idx2]: - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): i.get_loc('NOT-EXIST') # non-unique, slicable @@ -489,7 +489,7 @@ def test_get_loc(self): self.assertEqual(res, slice(2, 5, None)) for i in [cidx3, idx3]: - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): i.get_loc('c') def test_repr_roundtrip(self): @@ -581,10 +581,10 @@ def test_equals_categorical(self): # invalid comparisons with tm.assertRaisesRegexp(ValueError, "Lengths must match"): ci1 == Index(['a', 'b', 'c']) - self.assertRaises(TypeError, lambda: ci1 == ci2) - self.assertRaises( + pytest.raises(TypeError, lambda: ci1 == ci2) + pytest.raises( TypeError, lambda: ci1 == Categorical(ci1.values, ordered=False)) - self.assertRaises( + pytest.raises( TypeError, lambda: ci1 == Categorical(ci1.values, categories=list('abc'))) @@ -866,7 +866,7 @@ def test_take_fill_value(self): with tm.assertRaisesRegexp(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): idx.take(np.array([1, -5])) def test_take_fill_value_datetime(self): @@ -904,7 +904,7 @@ def test_take_fill_value_datetime(self): with tm.assertRaisesRegexp(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): idx.take(np.array([1, -5])) def test_take_invalid_kwargs(self): diff --git a/pandas/tests/indexes/test_interval.py b/pandas/tests/indexes/test_interval.py index f9ddf936007b2..53b5c01c40899 100644 --- a/pandas/tests/indexes/test_interval.py +++ b/pandas/tests/indexes/test_interval.py @@ -114,7 +114,7 @@ def test_constructors_error(self): # non-intervals def f(): IntervalIndex.from_intervals([0.997, 4.0]) - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def test_properties(self): index = self.index @@ -212,7 +212,7 @@ def test_astype(self): for dtype in [np.int64, np.float64, 'datetime64[ns]', 'datetime64[ns, US/Eastern]', 'timedelta64', 'period[M]']: - self.assertRaises(ValueError, idx.astype, dtype) + pytest.raises(ValueError, idx.astype, dtype) result = idx.astype(object) tm.assert_index_equal(result, Index(idx.values, dtype='object')) @@ -251,9 +251,9 @@ def test_insert(self): actual = self.index.insert(2, Interval(2, 3)) self.assertTrue(expected.equals(actual)) - self.assertRaises(ValueError, self.index.insert, 0, 1) - self.assertRaises(ValueError, self.index.insert, 0, - Interval(2, 3, closed='left')) + pytest.raises(ValueError, self.index.insert, 0, 1) + pytest.raises(ValueError, self.index.insert, 0, + Interval(2, 3, closed='left')) def test_take(self): actual = self.index.take([0, 1]) @@ -328,13 +328,13 @@ def test_get_item(self): tm.assert_index_equal(result, expected) def test_get_loc_value(self): - self.assertRaises(KeyError, self.index.get_loc, 0) + pytest.raises(KeyError, self.index.get_loc, 0) self.assertEqual(self.index.get_loc(0.5), 0) self.assertEqual(self.index.get_loc(1), 0) self.assertEqual(self.index.get_loc(1.5), 1) self.assertEqual(self.index.get_loc(2), 1) - self.assertRaises(KeyError, self.index.get_loc, -1) - self.assertRaises(KeyError, self.index.get_loc, 3) + pytest.raises(KeyError, self.index.get_loc, -1) + pytest.raises(KeyError, self.index.get_loc, 3) idx = IntervalIndex.from_tuples([(0, 2), (1, 3)]) self.assertEqual(idx.get_loc(0.5), 0) @@ -344,10 +344,10 @@ def test_get_loc_value(self): tm.assert_numpy_array_equal(np.sort(idx.get_loc(2)), np.array([0, 1], dtype='int64')) self.assertEqual(idx.get_loc(3), 1) - self.assertRaises(KeyError, idx.get_loc, 3.5) + pytest.raises(KeyError, idx.get_loc, 3.5) idx = IntervalIndex.from_arrays([0, 2], [1, 3]) - self.assertRaises(KeyError, idx.get_loc, 1.5) + pytest.raises(KeyError, idx.get_loc, 1.5) def slice_locs_cases(self, breaks): # TODO: same tests for more index types @@ -401,16 +401,16 @@ def test_slice_locs_decreasing_float64(self): def test_slice_locs_fails(self): index = IntervalIndex.from_tuples([(1, 2), (0, 1), (2, 3)]) - with self.assertRaises(KeyError): + with pytest.raises(KeyError): index.slice_locs(1, 2) def test_get_loc_interval(self): self.assertEqual(self.index.get_loc(Interval(0, 1)), 0) self.assertEqual(self.index.get_loc(Interval(0, 0.5)), 0) self.assertEqual(self.index.get_loc(Interval(0, 1, 'left')), 0) - self.assertRaises(KeyError, self.index.get_loc, Interval(2, 3)) - self.assertRaises(KeyError, self.index.get_loc, - Interval(-1, 0, 'left')) + pytest.raises(KeyError, self.index.get_loc, Interval(2, 3)) + pytest.raises(KeyError, self.index.get_loc, + Interval(-1, 0, 'left')) def test_get_indexer(self): actual = self.index.get_indexer([-1, 0, 0.5, 1, 1.5, 2, 3]) @@ -543,10 +543,10 @@ def test_symmetric_difference(self): tm.assert_index_equal(result, expected) def test_set_operation_errors(self): - self.assertRaises(ValueError, self.index.union, self.index.left) + pytest.raises(ValueError, self.index.union, self.index.left) other = IntervalIndex.from_breaks([0, 1, 2], closed='neither') - self.assertRaises(ValueError, self.index.union, other) + pytest.raises(ValueError, self.index.union, other) def test_isin(self): actual = self.index.isin(self.index) @@ -606,9 +606,9 @@ def test_comparison(self): self.index > 0 with self.assertRaisesRegexp(TypeError, 'unorderable types'): self.index <= 0 - with self.assertRaises(TypeError): + with pytest.raises(TypeError): self.index > np.arange(2) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): self.index > np.arange(3) def test_missing_values(self): @@ -677,7 +677,7 @@ def f(): index1.append(IntervalIndex.from_arrays([0, 1], [1, 2], closed='both')) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) class TestIntervalRange(tm.TestCase): @@ -694,28 +694,28 @@ def test_errors(self): def f(): interval_range(0) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def f(): interval_range(periods=2) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def f(): interval_range() - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # mixed units def f(): interval_range(0, Timestamp('20130101'), freq=2) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def f(): interval_range(0, 10, freq=Timedelta('1day')) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) class TestIntervalTree(tm.TestCase): @@ -740,7 +740,7 @@ def test_get_indexer(self): tm.assert_numpy_array_equal( tree.get_indexer(np.array([1.0, 5.5, 6.5])), np.array([0, 4, -1], dtype='int64')) - with self.assertRaises(KeyError): + with pytest.raises(KeyError): tree.get_indexer(np.array([3.0])) def test_get_indexer_non_unique(self): diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index d10cf4e71c916..c671a33e2f171 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -22,7 +22,7 @@ import pandas.util.testing as tm -from pandas.util.testing import (assertRaises, assertRaisesRegexp, +from pandas.util.testing import (assertRaisesRegexp, assert_almost_equal, assert_copy) @@ -87,7 +87,7 @@ def test_where(self): def f(): i.where(True) - self.assertRaises(NotImplementedError, f) + pytest.raises(NotImplementedError, f) def test_where_array_like(self): i = MultiIndex.from_tuples([('A', 1), ('A', 2)]) @@ -96,7 +96,7 @@ def test_where_array_like(self): for klass in klasses: f = lambda: i.where(klass(cond)) - self.assertRaises(NotImplementedError, f) + pytest.raises(NotImplementedError, f) def test_repeat(self): reps = 2 @@ -657,7 +657,7 @@ def test_get_level_number_integer(self): self.index.names = [1, 0] self.assertEqual(self.index._get_level_number(1), 0) self.assertEqual(self.index._get_level_number(0), 1) - self.assertRaises(IndexError, self.index._get_level_number, 2) + pytest.raises(IndexError, self.index._get_level_number, 2) assertRaisesRegexp(KeyError, 'Level fourth not found', self.index._get_level_number, 'fourth') @@ -784,7 +784,7 @@ def test_from_arrays_invalid_input(self): invalid_inputs = [1, [1], [1, 2], [[1], 2], 'a', ['a'], ['a', 'b'], [['a'], 'b']] for i in invalid_inputs: - tm.assertRaises(TypeError, MultiIndex.from_arrays, arrays=i) + pytest.raises(TypeError, MultiIndex.from_arrays, arrays=i) def test_from_arrays_different_lengths(self): # GH13599 @@ -853,7 +853,7 @@ def test_from_product_invalid_input(self): invalid_inputs = [1, [1], [1, 2], [[1], 2], 'a', ['a'], ['a', 'b'], [['a'], 'b']] for i in invalid_inputs: - tm.assertRaises(TypeError, MultiIndex.from_product, iterables=i) + pytest.raises(TypeError, MultiIndex.from_product, iterables=i) def test_from_product_datetimeindex(self): dt_index = date_range('2000-01-01', periods=2) @@ -1108,17 +1108,17 @@ def test_getitem_group_select(self): def test_get_loc(self): self.assertEqual(self.index.get_loc(('foo', 'two')), 1) self.assertEqual(self.index.get_loc(('baz', 'two')), 3) - self.assertRaises(KeyError, self.index.get_loc, ('bar', 'two')) - self.assertRaises(KeyError, self.index.get_loc, 'quux') + pytest.raises(KeyError, self.index.get_loc, ('bar', 'two')) + pytest.raises(KeyError, self.index.get_loc, 'quux') - self.assertRaises(NotImplementedError, self.index.get_loc, 'foo', - method='nearest') + pytest.raises(NotImplementedError, self.index.get_loc, 'foo', + method='nearest') # 3 levels index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index( lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array( [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])]) - self.assertRaises(KeyError, index.get_loc, (1, 1)) + pytest.raises(KeyError, index.get_loc, (1, 1)) self.assertEqual(index.get_loc((2, 0)), slice(3, 5)) def test_get_loc_duplicates(self): @@ -1126,7 +1126,7 @@ def test_get_loc_duplicates(self): result = index.get_loc(2) expected = slice(0, 4) self.assertEqual(result, expected) - # self.assertRaises(Exception, index.get_loc, 2) + # pytest.raises(Exception, index.get_loc, 2) index = Index(['c', 'a', 'a', 'b', 'b']) rs = index.get_loc('c') @@ -1160,7 +1160,7 @@ def test_get_loc_level(self): self.assertEqual(loc, expected) self.assertIsNone(new_index) - self.assertRaises(KeyError, index.get_loc_level, (2, 2)) + pytest.raises(KeyError, index.get_loc_level, (2, 2)) index = MultiIndex(levels=[[2000], lrange(4)], labels=[np.array( [0, 0, 0, 0]), np.array([0, 1, 2, 3])]) @@ -1298,7 +1298,7 @@ def test_truncate(self): self.assertEqual(len(result.levels[0]), 2) # after < before - self.assertRaises(ValueError, index.truncate, 3, 1) + pytest.raises(ValueError, index.truncate, 3, 1) def test_get_indexer(self): major_axis = Index(lrange(4)) @@ -1353,9 +1353,9 @@ def test_get_indexer(self): def test_get_indexer_nearest(self): midx = MultiIndex.from_tuples([('a', 1), ('b', 2)]) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): midx.get_indexer(['a'], method='nearest') - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): midx.get_indexer(['a'], method='pad', tolerance=2) def test_hash_collisions(self): @@ -1631,13 +1631,13 @@ def test_sub(self): first = self.index # - now raises (previously was set op difference) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): first - self.index[-3:] - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): self.index[-3:] - first - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): self.index[-3:] - first.tolist() - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): first.tolist() - self.index[-3:] def test_difference(self): @@ -1781,13 +1781,13 @@ def test_drop(self): tm.assert_index_equal(dropped, expected) index = MultiIndex.from_tuples([('bar', 'two')]) - self.assertRaises(KeyError, self.index.drop, [('bar', 'two')]) - self.assertRaises(KeyError, self.index.drop, index) - self.assertRaises(KeyError, self.index.drop, ['foo', 'two']) + pytest.raises(KeyError, self.index.drop, [('bar', 'two')]) + pytest.raises(KeyError, self.index.drop, index) + pytest.raises(KeyError, self.index.drop, ['foo', 'two']) # partially correct argument mixed_index = MultiIndex.from_tuples([('qux', 'one'), ('bar', 'two')]) - self.assertRaises(KeyError, self.index.drop, mixed_index) + pytest.raises(KeyError, self.index.drop, mixed_index) # error='ignore' dropped = self.index.drop(index, errors='ignore') @@ -1809,7 +1809,7 @@ def test_drop(self): # mixed partial / full drop / error='ignore' mixed_index = ['foo', ('qux', 'one'), 'two'] - self.assertRaises(KeyError, self.index.drop, mixed_index) + pytest.raises(KeyError, self.index.drop, mixed_index) dropped = self.index.drop(mixed_index, errors='ignore') expected = self.index[[2, 3, 5]] tm.assert_index_equal(dropped, expected) @@ -1969,7 +1969,7 @@ def test_take_fill_value(self): with tm.assertRaisesRegexp(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): idx.take(np.array([1, -5])) def take_invalid_kwargs(self): @@ -2355,7 +2355,7 @@ def test_isnull_behavior(self): # should not segfault GH5123 # NOTE: if MI representation changes, may make sense to allow # isnull(MI) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): pd.isnull(self.index) def test_level_setting_resets_attributes(self): @@ -2527,18 +2527,18 @@ def test_isin_level_kwarg(self): tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level=1)) tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level=-1)) - self.assertRaises(IndexError, idx.isin, vals_0, level=5) - self.assertRaises(IndexError, idx.isin, vals_0, level=-5) + pytest.raises(IndexError, idx.isin, vals_0, level=5) + pytest.raises(IndexError, idx.isin, vals_0, level=-5) - self.assertRaises(KeyError, idx.isin, vals_0, level=1.0) - self.assertRaises(KeyError, idx.isin, vals_1, level=-1.0) - self.assertRaises(KeyError, idx.isin, vals_1, level='A') + pytest.raises(KeyError, idx.isin, vals_0, level=1.0) + pytest.raises(KeyError, idx.isin, vals_1, level=-1.0) + pytest.raises(KeyError, idx.isin, vals_1, level='A') idx.names = ['A', 'B'] tm.assert_numpy_array_equal(expected, idx.isin(vals_0, level='A')) tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level='B')) - self.assertRaises(KeyError, idx.isin, vals_1, level='C') + pytest.raises(KeyError, idx.isin, vals_1, level='C') def test_reindex_preserves_names_when_target_is_list_or_ndarray(self): # GH6552 @@ -2616,16 +2616,16 @@ def test_large_multiindex_error(self): df_below_1000000 = pd.DataFrame( 1, index=pd.MultiIndex.from_product([[1, 2], range(499999)]), columns=['dest']) - with assertRaises(KeyError): + with pytest.raises(KeyError): df_below_1000000.loc[(-1, 0), 'dest'] - with assertRaises(KeyError): + with pytest.raises(KeyError): df_below_1000000.loc[(3, 0), 'dest'] df_above_1000000 = pd.DataFrame( 1, index=pd.MultiIndex.from_product([[1, 2], range(500001)]), columns=['dest']) - with assertRaises(KeyError): + with pytest.raises(KeyError): df_above_1000000.loc[(-1, 0), 'dest'] - with assertRaises(KeyError): + with pytest.raises(KeyError): df_above_1000000.loc[(3, 0), 'dest'] def test_partial_string_timestamp_multiindex(self): @@ -2678,7 +2678,7 @@ def test_partial_string_timestamp_multiindex(self): # ambiguous and we don't want to extend this behavior forward to work # in multi-indexes. This would amount to selecting a scalar from a # column. - with assertRaises(KeyError): + with pytest.raises(KeyError): df['2016-01-01'] # partial string match on year only @@ -2707,7 +2707,7 @@ def test_partial_string_timestamp_multiindex(self): tm.assert_frame_equal(result, expected) # Slicing date on first level should break (of course) - with assertRaises(KeyError): + with pytest.raises(KeyError): df_swap.loc['2016-01-01'] # GH12685 (partial string with daily resolution or below) @@ -2771,12 +2771,12 @@ def test_unsortedindex(self): df = pd.DataFrame([[i, 10 * i] for i in lrange(6)], index=mi, columns=['one', 'two']) - with assertRaises(UnsortedIndexError): + with pytest.raises(UnsortedIndexError): df.loc(axis=0)['z', :] df.sort_index(inplace=True) self.assertEqual(len(df.loc(axis=0)['z', :]), 2) - with assertRaises(KeyError): + with pytest.raises(KeyError): df.loc(axis=0)['q', :] def test_unsortedindex_doc_examples(self): @@ -2807,7 +2807,7 @@ def test_tuples_with_name_string(self): # GH 15110 and GH 14848 li = [(0, 0, 1), (0, 1, 0), (1, 0, 0)] - with assertRaises(ValueError): + with pytest.raises(ValueError): pd.Index(li, name='abc') - with assertRaises(ValueError): + with pytest.raises(ValueError): pd.Index(li, name='a') diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py index b14175843ae20..62aabaaef100c 100644 --- a/pandas/tests/indexes/test_numeric.py +++ b/pandas/tests/indexes/test_numeric.py @@ -1,5 +1,7 @@ # -*- coding: utf-8 -*- +import pytest + from datetime import datetime from pandas.compat import range, PY3 @@ -74,10 +76,10 @@ def test_numeric_compat(self): tm.assert_index_equal(result, expected) # invalid - self.assertRaises(TypeError, - lambda: idx * date_range('20130101', periods=5)) - self.assertRaises(ValueError, lambda: idx * idx[0:3]) - self.assertRaises(ValueError, lambda: idx * np.array([1, 2])) + pytest.raises(TypeError, + lambda: idx * date_range('20130101', periods=5)) + pytest.raises(ValueError, lambda: idx * idx[0:3]) + pytest.raises(ValueError, lambda: idx * np.array([1, 2])) result = divmod(idx, 2) with np.errstate(all='ignore'): @@ -235,9 +237,9 @@ def test_constructor(self): def test_constructor_invalid(self): # invalid - self.assertRaises(TypeError, Float64Index, 0.) - self.assertRaises(TypeError, Float64Index, ['a', 'b', 0.]) - self.assertRaises(TypeError, Float64Index, [Timestamp('20130101')]) + pytest.raises(TypeError, Float64Index, 0.) + pytest.raises(TypeError, Float64Index, ['a', 'b', 0.]) + pytest.raises(TypeError, Float64Index, [Timestamp('20130101')]) def test_constructor_coerce(self): @@ -295,12 +297,12 @@ def test_astype(self): # invalid for dtype in ['M8[ns]', 'm8[ns]']: - self.assertRaises(TypeError, lambda: i.astype(dtype)) + pytest.raises(TypeError, lambda: i.astype(dtype)) # GH 13149 for dtype in ['int16', 'int32', 'int64']: i = Float64Index([0, 1.1, np.NAN]) - self.assertRaises(ValueError, lambda: i.astype(dtype)) + pytest.raises(ValueError, lambda: i.astype(dtype)) def test_equals_numeric(self): @@ -342,10 +344,10 @@ def test_get_loc(self): self.assertEqual(idx.get_loc(1.1, method), loc) self.assertEqual(idx.get_loc(1.1, method, tolerance=0.9), loc) - self.assertRaises(KeyError, idx.get_loc, 'foo') - self.assertRaises(KeyError, idx.get_loc, 1.5) - self.assertRaises(KeyError, idx.get_loc, 1.5, method='pad', - tolerance=0.1) + pytest.raises(KeyError, idx.get_loc, 'foo') + pytest.raises(KeyError, idx.get_loc, 1.5) + pytest.raises(KeyError, idx.get_loc, 1.5, method='pad', + tolerance=0.1) with tm.assertRaisesRegexp(ValueError, 'must be numeric'): idx.get_loc(1.4, method='nearest', tolerance='foo') @@ -359,7 +361,7 @@ def test_get_loc_na(self): self.assertEqual(idx.get_loc(1), 1) # representable by slice [0:2:2] - # self.assertRaises(KeyError, idx.slice_locs, np.nan) + # pytest.raises(KeyError, idx.slice_locs, np.nan) sliced = idx.slice_locs(np.nan) self.assertTrue(isinstance(sliced, tuple)) self.assertEqual(sliced, (0, 3)) @@ -367,7 +369,7 @@ def test_get_loc_na(self): # not representable by slice idx = Float64Index([np.nan, 1, np.nan, np.nan]) self.assertEqual(idx.get_loc(1), 1) - self.assertRaises(KeyError, idx.slice_locs, np.nan) + pytest.raises(KeyError, idx.slice_locs, np.nan) def test_contains_nans(self): i = Float64Index([1.0, 2.0, np.nan]) @@ -441,7 +443,7 @@ def test_take_fill_value(self): with tm.assertRaisesRegexp(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): idx.take(np.array([1, -5])) @@ -534,11 +536,11 @@ def test_union_noncomparable(self): def test_cant_or_shouldnt_cast(self): # can't data = ['foo', 'bar', 'baz'] - self.assertRaises(TypeError, self._holder, data) + pytest.raises(TypeError, self._holder, data) # shouldn't data = ['0', '1', '2'] - self.assertRaises(TypeError, self._holder, data) + pytest.raises(TypeError, self._holder, data) def test_view_index(self): self.index.view(Index) @@ -578,7 +580,7 @@ def test_take_fill_value(self): with tm.assertRaisesRegexp(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): idx.take(np.array([1, -5])) def test_slice_keep_name(self): @@ -642,7 +644,7 @@ def test_constructor(self): tm.assert_index_equal(index, expected) # scalar raise Exception - self.assertRaises(TypeError, Int64Index, 5) + pytest.raises(TypeError, Int64Index, 5) # copy arr = self.index.values diff --git a/pandas/tests/indexes/test_range.py b/pandas/tests/indexes/test_range.py index 6168deba7e72c..0b27eb0c34111 100644 --- a/pandas/tests/indexes/test_range.py +++ b/pandas/tests/indexes/test_range.py @@ -1,5 +1,7 @@ # -*- coding: utf-8 -*- +import pytest + from datetime import datetime from itertools import combinations import operator @@ -111,13 +113,13 @@ def test_constructor(self): self.assertEqual(index.name, 'Foo') # we don't allow on a bare Index - self.assertRaises(TypeError, lambda: Index(0, 1000)) + pytest.raises(TypeError, lambda: Index(0, 1000)) # invalid args for i in [Index(['a', 'b']), Series(['a', 'b']), np.array(['a', 'b']), [], 'foo', datetime(2000, 1, 1, 0, 0), np.arange(0, 10), np.array([1]), [1]]: - self.assertRaises(TypeError, lambda: RangeIndex(i)) + pytest.raises(TypeError, lambda: RangeIndex(i)) def test_constructor_same(self): @@ -132,12 +134,12 @@ def test_constructor_same(self): result = RangeIndex(index) tm.assert_index_equal(result, index, exact=True) - self.assertRaises(TypeError, - lambda: RangeIndex(index, dtype='float64')) + pytest.raises(TypeError, + lambda: RangeIndex(index, dtype='float64')) def test_constructor_range(self): - self.assertRaises(TypeError, lambda: RangeIndex(range(1, 5, 2))) + pytest.raises(TypeError, lambda: RangeIndex(range(1, 5, 2))) result = RangeIndex.from_range(range(1, 5, 2)) expected = RangeIndex(1, 5, 2) @@ -160,8 +162,8 @@ def test_constructor_range(self): expected = RangeIndex(1, 5, 2) tm.assert_index_equal(result, expected, exact=True) - self.assertRaises(TypeError, - lambda: Index(range(1, 5, 2), dtype='float64')) + pytest.raises(TypeError, + lambda: Index(range(1, 5, 2), dtype='float64')) def test_constructor_name(self): # GH12288 @@ -249,11 +251,11 @@ def test_constructor_corner(self): tm.assert_index_equal(index, Index(arr)) # non-int raise Exception - self.assertRaises(TypeError, RangeIndex, '1', '10', '1') - self.assertRaises(TypeError, RangeIndex, 1.1, 10.2, 1.3) + pytest.raises(TypeError, RangeIndex, '1', '10', '1') + pytest.raises(TypeError, RangeIndex, 1.1, 10.2, 1.3) # invalid passed type - self.assertRaises(TypeError, lambda: RangeIndex(1, 5, dtype='float64')) + pytest.raises(TypeError, lambda: RangeIndex(1, 5, dtype='float64')) def test_copy(self): i = RangeIndex(5, name='Foo') @@ -306,7 +308,7 @@ def test_delete(self): tm.assert_index_equal(result, expected) self.assertEqual(result.name, expected.name) - with tm.assertRaises((IndexError, ValueError)): + with pytest.raises((IndexError, ValueError)): # either depending on numpy version result = idx.delete(len(idx)) @@ -696,10 +698,10 @@ def test_nbytes(self): def test_cant_or_shouldnt_cast(self): # can't - self.assertRaises(TypeError, RangeIndex, 'foo', 'bar', 'baz') + pytest.raises(TypeError, RangeIndex, 'foo', 'bar', 'baz') # shouldn't - self.assertRaises(TypeError, RangeIndex, '0', '1', '2') + pytest.raises(TypeError, RangeIndex, '0', '1', '2') def test_view_Index(self): self.index.view(Index) @@ -737,7 +739,7 @@ def test_take_fill_value(self): with tm.assertRaisesRegexp(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): idx.take(np.array([1, -5])) def test_print_unicode_columns(self): diff --git a/pandas/tests/indexes/timedeltas/test_astype.py b/pandas/tests/indexes/timedeltas/test_astype.py index c2afaf209dbc0..d269cddcbb5c8 100644 --- a/pandas/tests/indexes/timedeltas/test_astype.py +++ b/pandas/tests/indexes/timedeltas/test_astype.py @@ -1,3 +1,5 @@ +import pytest + import numpy as np import pandas as pd @@ -59,10 +61,10 @@ def test_astype_raises(self): # GH 13149, GH 13209 idx = TimedeltaIndex([1e14, 'NaT', pd.NaT, np.NaN]) - self.assertRaises(ValueError, idx.astype, float) - self.assertRaises(ValueError, idx.astype, str) - self.assertRaises(ValueError, idx.astype, 'datetime64') - self.assertRaises(ValueError, idx.astype, 'datetime64[ns]') + pytest.raises(ValueError, idx.astype, float) + pytest.raises(ValueError, idx.astype, str) + pytest.raises(ValueError, idx.astype, 'datetime64') + pytest.raises(ValueError, idx.astype, 'datetime64[ns]') def test_pickle_compat_construction(self): pass @@ -116,6 +118,6 @@ def test_numeric_compat(self): 5, dtype='float64') * (np.arange(5, dtype='float64') + 0.1))) # invalid - self.assertRaises(TypeError, lambda: idx * idx) - self.assertRaises(ValueError, lambda: idx * self._holder(np.arange(3))) - self.assertRaises(ValueError, lambda: idx * np.array([1, 2])) + pytest.raises(TypeError, lambda: idx * idx) + pytest.raises(ValueError, lambda: idx * self._holder(np.arange(3))) + pytest.raises(ValueError, lambda: idx * np.array([1, 2])) diff --git a/pandas/tests/indexes/timedeltas/test_construction.py b/pandas/tests/indexes/timedeltas/test_construction.py index e903615a09f5c..6681a03a3b271 100644 --- a/pandas/tests/indexes/timedeltas/test_construction.py +++ b/pandas/tests/indexes/timedeltas/test_construction.py @@ -1,3 +1,5 @@ +import pytest + import numpy as np from datetime import timedelta @@ -48,13 +50,13 @@ def test_constructor_coverage(self): exp = timedelta_range('1 days', periods=10) tm.assert_index_equal(rng, exp) - self.assertRaises(ValueError, TimedeltaIndex, start='1 days', - periods='foo', freq='D') + pytest.raises(ValueError, TimedeltaIndex, start='1 days', + periods='foo', freq='D') - self.assertRaises(ValueError, TimedeltaIndex, start='1 days', - end='10 days') + pytest.raises(ValueError, TimedeltaIndex, start='1 days', + end='10 days') - self.assertRaises(ValueError, TimedeltaIndex, '1 days') + pytest.raises(ValueError, TimedeltaIndex, '1 days') # generator expression gen = (timedelta(i) for i in range(10)) @@ -72,10 +74,10 @@ def test_constructor_coverage(self): tm.assert_index_equal(from_ints, expected) # non-conforming freq - self.assertRaises(ValueError, TimedeltaIndex, - ['1 days', '2 days', '4 days'], freq='D') + pytest.raises(ValueError, TimedeltaIndex, + ['1 days', '2 days', '4 days'], freq='D') - self.assertRaises(ValueError, TimedeltaIndex, periods=10, freq='D') + pytest.raises(ValueError, TimedeltaIndex, periods=10, freq='D') def test_constructor_name(self): idx = TimedeltaIndex(start='1 days', periods=1, freq='D', name='TEST') diff --git a/pandas/tests/indexes/timedeltas/test_indexing.py b/pandas/tests/indexes/timedeltas/test_indexing.py index b98b5f097ce24..58b83dde5f402 100644 --- a/pandas/tests/indexes/timedeltas/test_indexing.py +++ b/pandas/tests/indexes/timedeltas/test_indexing.py @@ -1,3 +1,5 @@ +import pytest + from datetime import timedelta import pandas.util.testing as tm @@ -77,7 +79,7 @@ def test_delete(self): self.assertEqual(result.name, expected.name) self.assertEqual(result.freq, expected.freq) - with tm.assertRaises((IndexError, ValueError)): + with pytest.raises((IndexError, ValueError)): # either depeidnig on numpy version result = idx.delete(5) diff --git a/pandas/tests/indexes/timedeltas/test_ops.py b/pandas/tests/indexes/timedeltas/test_ops.py index 6d8d5f19b98e2..97c4a1df95963 100644 --- a/pandas/tests/indexes/timedeltas/test_ops.py +++ b/pandas/tests/indexes/timedeltas/test_ops.py @@ -1,3 +1,5 @@ +import pytest + import numpy as np from datetime import timedelta from distutils.version import LooseVersion @@ -276,7 +278,7 @@ def test_ops_compat(self): # multiply for offset in offsets: - self.assertRaises(TypeError, lambda: rng * offset) + pytest.raises(TypeError, lambda: rng * offset) # divide expected = Int64Index((np.arange(10) + 1) * 12, name='foo') @@ -298,7 +300,7 @@ def test_ops_compat(self): tm.assert_index_equal(result, expected) # don't allow division by NaT (make could in the future) - self.assertRaises(TypeError, lambda: rng / pd.NaT) + pytest.raises(TypeError, lambda: rng / pd.NaT) def test_subtraction_ops(self): @@ -308,10 +310,10 @@ def test_subtraction_ops(self): td = Timedelta('1 days') dt = Timestamp('20130101') - self.assertRaises(TypeError, lambda: tdi - dt) - self.assertRaises(TypeError, lambda: tdi - dti) - self.assertRaises(TypeError, lambda: td - dt) - self.assertRaises(TypeError, lambda: td - dti) + pytest.raises(TypeError, lambda: tdi - dt) + pytest.raises(TypeError, lambda: tdi - dti) + pytest.raises(TypeError, lambda: td - dt) + pytest.raises(TypeError, lambda: td - dti) result = dt - dti expected = TimedeltaIndex(['0 days', '-1 days', '-2 days'], name='bar') @@ -368,19 +370,19 @@ def _check(result, expected): _check(result, expected) # tz mismatches - self.assertRaises(TypeError, lambda: dt_tz - ts) - self.assertRaises(TypeError, lambda: dt_tz - dt) - self.assertRaises(TypeError, lambda: dt_tz - ts_tz2) - self.assertRaises(TypeError, lambda: dt - dt_tz) - self.assertRaises(TypeError, lambda: ts - dt_tz) - self.assertRaises(TypeError, lambda: ts_tz2 - ts) - self.assertRaises(TypeError, lambda: ts_tz2 - dt) - self.assertRaises(TypeError, lambda: ts_tz - ts_tz2) + pytest.raises(TypeError, lambda: dt_tz - ts) + pytest.raises(TypeError, lambda: dt_tz - dt) + pytest.raises(TypeError, lambda: dt_tz - ts_tz2) + pytest.raises(TypeError, lambda: dt - dt_tz) + pytest.raises(TypeError, lambda: ts - dt_tz) + pytest.raises(TypeError, lambda: ts_tz2 - ts) + pytest.raises(TypeError, lambda: ts_tz2 - dt) + pytest.raises(TypeError, lambda: ts_tz - ts_tz2) # with dti - self.assertRaises(TypeError, lambda: dti - ts_tz) - self.assertRaises(TypeError, lambda: dti_tz - ts) - self.assertRaises(TypeError, lambda: dti_tz - ts_tz2) + pytest.raises(TypeError, lambda: dti - ts_tz) + pytest.raises(TypeError, lambda: dti_tz - ts) + pytest.raises(TypeError, lambda: dti_tz - ts_tz2) result = dti_tz - dt_tz expected = TimedeltaIndex(['0 days', '1 days', '2 days']) @@ -437,10 +439,10 @@ def test_sub_period(self): for freq in [None, 'H']: idx = pd.TimedeltaIndex(['1 hours', '2 hours'], freq=freq) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): idx - p - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): p - idx def test_addition_ops(self): @@ -468,14 +470,14 @@ def test_addition_ops(self): tm.assert_index_equal(result, expected) # unequal length - self.assertRaises(ValueError, lambda: tdi + dti[0:1]) - self.assertRaises(ValueError, lambda: tdi[0:1] + dti) + pytest.raises(ValueError, lambda: tdi + dti[0:1]) + pytest.raises(ValueError, lambda: tdi[0:1] + dti) # random indexes - self.assertRaises(TypeError, lambda: tdi + Int64Index([1, 2, 3])) + pytest.raises(TypeError, lambda: tdi + Int64Index([1, 2, 3])) # this is a union! - # self.assertRaises(TypeError, lambda : Int64Index([1,2,3]) + tdi) + # pytest.raises(TypeError, lambda : Int64Index([1,2,3]) + tdi) result = tdi + dti # name will be reset expected = DatetimeIndex(['20130102', pd.NaT, '20130105']) @@ -566,7 +568,7 @@ def test_unknown_attribute(self): tdi = pd.timedelta_range(start=0, periods=10, freq='1s') ts = pd.Series(np.random.normal(size=10), index=tdi) self.assertNotIn('foo', ts.__dict__.keys()) - self.assertRaises(AttributeError, lambda: ts.foo) + pytest.raises(AttributeError, lambda: ts.foo) def test_order(self): # GH 10295 @@ -886,11 +888,11 @@ def test_ops(self): self.assertEqual(abs(-td), Timedelta('10d')) # invalid multiply with another timedelta - self.assertRaises(TypeError, lambda: td * td) + pytest.raises(TypeError, lambda: td * td) # can't operate with integers - self.assertRaises(TypeError, lambda: td + 2) - self.assertRaises(TypeError, lambda: td - 2) + pytest.raises(TypeError, lambda: td + 2) + pytest.raises(TypeError, lambda: td - 2) def test_ops_offsets(self): td = Timedelta(10, unit='d') @@ -910,21 +912,21 @@ def test_ops_ndarray(self): tm.assert_numpy_array_equal(td + other, expected) if LooseVersion(np.__version__) >= '1.8': tm.assert_numpy_array_equal(other + td, expected) - self.assertRaises(TypeError, lambda: td + np.array([1])) - self.assertRaises(TypeError, lambda: np.array([1]) + td) + pytest.raises(TypeError, lambda: td + np.array([1])) + pytest.raises(TypeError, lambda: np.array([1]) + td) expected = pd.to_timedelta(['0 days']).values tm.assert_numpy_array_equal(td - other, expected) if LooseVersion(np.__version__) >= '1.8': tm.assert_numpy_array_equal(-other + td, expected) - self.assertRaises(TypeError, lambda: td - np.array([1])) - self.assertRaises(TypeError, lambda: np.array([1]) - td) + pytest.raises(TypeError, lambda: td - np.array([1])) + pytest.raises(TypeError, lambda: np.array([1]) - td) expected = pd.to_timedelta(['2 days']).values tm.assert_numpy_array_equal(td * np.array([2]), expected) tm.assert_numpy_array_equal(np.array([2]) * td, expected) - self.assertRaises(TypeError, lambda: td * other) - self.assertRaises(TypeError, lambda: other * td) + pytest.raises(TypeError, lambda: td * other) + pytest.raises(TypeError, lambda: other * td) tm.assert_numpy_array_equal(td / other, np.array([1], dtype=np.float64)) @@ -1002,16 +1004,16 @@ def test_ops_error_str(self): tdi = TimedeltaIndex(['1 day', '2 days']) for l, r in [(tdi, 'a'), ('a', tdi)]: - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): l + r - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): l > r - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): l == r - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): l != r def test_timedelta_ops(self): @@ -1058,7 +1060,7 @@ def test_timedelta_ops(self): # invalid ops for op in ['skew', 'kurt', 'sem', 'prod']: - self.assertRaises(TypeError, getattr(td, op)) + pytest.raises(TypeError, getattr(td, op)) # GH 10040 # make sure NaT is properly handled by median() diff --git a/pandas/tests/indexes/timedeltas/test_partial_slicing.py b/pandas/tests/indexes/timedeltas/test_partial_slicing.py index 0d46ee4172211..f7560c37e814b 100644 --- a/pandas/tests/indexes/timedeltas/test_partial_slicing.py +++ b/pandas/tests/indexes/timedeltas/test_partial_slicing.py @@ -1,3 +1,5 @@ +import pytest + import numpy as np import pandas.util.testing as tm @@ -27,7 +29,7 @@ def test_partial_slice(self): result = s['6 days, 23:11:12'] self.assertEqual(result, s.iloc[133]) - self.assertRaises(KeyError, s.__getitem__, '50 days') + pytest.raises(KeyError, s.__getitem__, '50 days') def test_partial_slice_high_reso(self): diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py index 12c9e626ca9e1..9ca207876520f 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -1,3 +1,5 @@ +import pytest + import numpy as np from datetime import timedelta @@ -119,9 +121,9 @@ def test_numeric_compat(self): 5, dtype='float64') * (np.arange(5, dtype='float64') + 0.1))) # invalid - self.assertRaises(TypeError, lambda: idx * idx) - self.assertRaises(ValueError, lambda: idx * self._holder(np.arange(3))) - self.assertRaises(ValueError, lambda: idx * np.array([1, 2])) + pytest.raises(TypeError, lambda: idx * idx) + pytest.raises(ValueError, lambda: idx * self._holder(np.arange(3))) + pytest.raises(ValueError, lambda: idx * np.array([1, 2])) def test_pickle_compat_construction(self): pass @@ -238,7 +240,7 @@ def test_take_fill_value(self): with tm.assertRaisesRegexp(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): idx.take(np.array([1, -5])) def test_isin(self): @@ -411,7 +413,7 @@ def test_comparisons_coverage(self): tm.assert_numpy_array_equal(result, exp) # raise TypeError for now - self.assertRaises(TypeError, rng.__lt__, rng[3].value) + pytest.raises(TypeError, rng.__lt__, rng[3].value) result = rng == list(rng) exp = rng == rng @@ -497,9 +499,9 @@ def test_fields(self): tm.assert_index_equal(rng.nanoseconds, Index([456, 456], dtype='int64')) - self.assertRaises(AttributeError, lambda: rng.hours) - self.assertRaises(AttributeError, lambda: rng.minutes) - self.assertRaises(AttributeError, lambda: rng.milliseconds) + pytest.raises(AttributeError, lambda: rng.hours) + pytest.raises(AttributeError, lambda: rng.minutes) + pytest.raises(AttributeError, lambda: rng.milliseconds) # with nat s = Series(rng) diff --git a/pandas/tests/indexes/timedeltas/test_tools.py b/pandas/tests/indexes/timedeltas/test_tools.py index ade9366c7e994..b4f6f33a6e06a 100644 --- a/pandas/tests/indexes/timedeltas/test_tools.py +++ b/pandas/tests/indexes/timedeltas/test_tools.py @@ -1,3 +1,5 @@ +import pytest + from datetime import time, timedelta import numpy as np @@ -115,15 +117,15 @@ def test_to_timedelta_invalid(self): ['foo'], errors='never') # these will error - self.assertRaises(ValueError, lambda: to_timedelta([1, 2], unit='foo')) - self.assertRaises(ValueError, lambda: to_timedelta(1, unit='foo')) + pytest.raises(ValueError, lambda: to_timedelta([1, 2], unit='foo')) + pytest.raises(ValueError, lambda: to_timedelta(1, unit='foo')) # time not supported ATM - self.assertRaises(ValueError, lambda: to_timedelta(time(second=1))) + pytest.raises(ValueError, lambda: to_timedelta(time(second=1))) self.assertTrue(to_timedelta( time(second=1), errors='coerce') is pd.NaT) - self.assertRaises(ValueError, lambda: to_timedelta(['foo', 'bar'])) + pytest.raises(ValueError, lambda: to_timedelta(['foo', 'bar'])) tm.assert_index_equal(TimedeltaIndex([pd.NaT, pd.NaT]), to_timedelta(['foo', 'bar'], errors='coerce')) @@ -199,4 +201,4 @@ def test_to_timedelta_on_nanoseconds(self): expected = Timedelta('990ns') self.assertEqual(result, expected) - self.assertRaises(TypeError, lambda: Timedelta(nanoseconds='abc')) + pytest.raises(TypeError, lambda: Timedelta(nanoseconds='abc')) diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py index b8a24cb2dcb03..fd5557dfcb99c 100644 --- a/pandas/tests/indexing/test_categorical.py +++ b/pandas/tests/indexing/test_categorical.py @@ -1,5 +1,7 @@ # -*- coding: utf-8 -*- +import pytest + import pandas as pd import numpy as np from pandas import Series, DataFrame @@ -47,22 +49,22 @@ def test_loc_scalar(self): assert_frame_equal(df, expected) # value not in the categories - self.assertRaises(KeyError, lambda: df.loc['d']) + pytest.raises(KeyError, lambda: df.loc['d']) def f(): df.loc['d'] = 10 - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def f(): df.loc['d', 'A'] = 10 - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def f(): df.loc['d', 'C'] = 10 - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def test_loc_listlike(self): @@ -78,7 +80,7 @@ def test_loc_listlike(self): assert_frame_equal(result, expected, check_index_type=True) # element in the categories but not in the values - self.assertRaises(KeyError, lambda: self.df2.loc['e']) + pytest.raises(KeyError, lambda: self.df2.loc['e']) # assign is ok df = self.df2.copy() @@ -97,7 +99,7 @@ def test_loc_listlike(self): assert_frame_equal(result, expected, check_index_type=True) # not all labels in the categories - self.assertRaises(KeyError, lambda: self.df2.loc[['a', 'd']]) + pytest.raises(KeyError, lambda: self.df2.loc[['a', 'd']]) def test_loc_listlike_dtypes(self): # GH 11586 @@ -324,22 +326,22 @@ def test_reindexing(self): assert_frame_equal(result, expected, check_index_type=True) # passed duplicate indexers are not allowed - self.assertRaises(ValueError, lambda: self.df2.reindex(['a', 'a'])) + pytest.raises(ValueError, lambda: self.df2.reindex(['a', 'a'])) # args NotImplemented ATM - self.assertRaises(NotImplementedError, - lambda: self.df2.reindex(['a'], method='ffill')) - self.assertRaises(NotImplementedError, - lambda: self.df2.reindex(['a'], level=1)) - self.assertRaises(NotImplementedError, - lambda: self.df2.reindex(['a'], limit=2)) + pytest.raises(NotImplementedError, + lambda: self.df2.reindex(['a'], method='ffill')) + pytest.raises(NotImplementedError, + lambda: self.df2.reindex(['a'], level=1)) + pytest.raises(NotImplementedError, + lambda: self.df2.reindex(['a'], limit=2)) def test_loc_slice(self): # slicing # not implemented ATM # GH9748 - self.assertRaises(TypeError, lambda: self.df.loc[1:5]) + pytest.raises(TypeError, lambda: self.df.loc[1:5]) # result = df.loc[1:5] # expected = df.iloc[[1,2,3,4]] @@ -387,8 +389,8 @@ def test_boolean_selection(self): # categories=[3, 2, 1], # ordered=False, # name=u'B') - self.assertRaises(TypeError, lambda: df4[df4.index < 2]) - self.assertRaises(TypeError, lambda: df4[df4.index > 1]) + pytest.raises(TypeError, lambda: df4[df4.index < 2]) + pytest.raises(TypeError, lambda: df4[df4.index > 1]) def test_indexing_with_category(self): diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index f2c3a49bc377c..c0d83c580d1d1 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -326,7 +326,7 @@ def test_setting_with_copy_bug(self): def f(): df[['c']][mask] = df[['b']][mask] - self.assertRaises(com.SettingWithCopyError, f) + pytest.raises(com.SettingWithCopyError, f) # invalid warning as we are returning a new object # GH 8730 diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index 7216c05657102..15a56d97eeaec 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -268,7 +268,7 @@ def test_setitem_index_object(self): # object + int -> IndexError, regarded as location temp = obj.copy() - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): temp[5] = 5 # object + float -> object @@ -300,7 +300,7 @@ def test_setitem_index_float64(self): # float + int -> int temp = obj.copy() # TODO_GH12747 The result must be float - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): temp[5] = 5 # float + float -> float @@ -803,7 +803,7 @@ def test_where_index_datetime64(self): # datetime64 + datetime64 -> datetime64 # must support scalar msg = "cannot coerce a Timestamp with a tz on a naive Block" - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): obj.where(cond, pd.Timestamp('2012-01-01')) values = pd.Index([pd.Timestamp('2012-01-01'), diff --git a/pandas/tests/indexing/test_datetime.py b/pandas/tests/indexing/test_datetime.py index eeef41ad6dbb2..9b224ba796268 100644 --- a/pandas/tests/indexing/test_datetime.py +++ b/pandas/tests/indexing/test_datetime.py @@ -1,3 +1,5 @@ +import pytest + import numpy as np import pandas as pd from pandas import date_range, Index, DataFrame, Series, Timestamp @@ -57,7 +59,7 @@ def test_indexing_with_datetime_tz(self): def f(): df.loc[df.new_col == 'new', 'time'] = v - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) v = df.loc[df.new_col == 'new', 'time'] + pd.Timedelta('1s') df.loc[df.new_col == 'new', 'time'] = v diff --git a/pandas/tests/indexing/test_floats.py b/pandas/tests/indexing/test_floats.py index 4c177cade88bf..ef64c6e0475e9 100644 --- a/pandas/tests/indexing/test_floats.py +++ b/pandas/tests/indexing/test_floats.py @@ -1,5 +1,7 @@ # -*- coding: utf-8 -*- +import pytest + from warnings import catch_warnings import numpy as np from pandas import Series, DataFrame, Index, Float64Index @@ -52,7 +54,7 @@ def f(): def f(): s.iloc[3.0] = 0 - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def test_scalar_non_numeric(self): @@ -87,7 +89,7 @@ def f(): error = KeyError else: error = TypeError - self.assertRaises(error, f) + pytest.raises(error, f) # label based can be a TypeError or KeyError def f(): @@ -97,7 +99,7 @@ def f(): error = KeyError else: error = TypeError - self.assertRaises(error, f) + pytest.raises(error, f) # contains self.assertFalse(3.0 in s) @@ -105,7 +107,7 @@ def f(): # setting with a float fails with iloc def f(): s.iloc[3.0] = 0 - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) # setting with an indexer if s.index.inferred_type in ['categorical']: @@ -121,7 +123,7 @@ def f(): # s2 = s.copy() # def f(): # idxr(s2)[3.0] = 0 - # self.assertRaises(TypeError, f) + # pytest.raises(TypeError, f) pass else: @@ -140,7 +142,7 @@ def f(): # fallsback to position selection, series only s = Series(np.arange(len(i)), index=i) s[3] - self.assertRaises(TypeError, lambda: s[3.0]) + pytest.raises(TypeError, lambda: s[3.0]) def test_scalar_with_mixed(self): @@ -157,9 +159,9 @@ def f(): with catch_warnings(record=True): idxr(s2)[1.0] - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) - self.assertRaises(KeyError, lambda: s2.loc[1.0]) + pytest.raises(KeyError, lambda: s2.loc[1.0]) result = s2.loc['b'] expected = 2 @@ -174,14 +176,14 @@ def f(): with catch_warnings(record=True): idxr(s3)[1.0] - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) result = idxr(s3)[1] expected = 2 self.assertEqual(result, expected) - self.assertRaises(TypeError, lambda: s3.iloc[1.0]) - self.assertRaises(KeyError, lambda: s3.loc[1.0]) + pytest.raises(TypeError, lambda: s3.iloc[1.0]) + pytest.raises(KeyError, lambda: s3.loc[1.0]) result = s3.loc[1.5] expected = 3 @@ -270,7 +272,7 @@ def f(): # random integer is a KeyError with catch_warnings(record=True): - self.assertRaises(KeyError, lambda: idxr(s)[3.5]) + pytest.raises(KeyError, lambda: idxr(s)[3.5]) # contains self.assertTrue(3.0 in s) @@ -284,11 +286,11 @@ def f(): self.check(result, s, 3, False) # iloc raises with a float - self.assertRaises(TypeError, lambda: s.iloc[3.0]) + pytest.raises(TypeError, lambda: s.iloc[3.0]) def g(): s2.iloc[3.0] = 0 - self.assertRaises(TypeError, g) + pytest.raises(TypeError, g) def test_slice_non_numeric(self): @@ -311,7 +313,7 @@ def test_slice_non_numeric(self): def f(): s.iloc[l] - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) for idxr in [lambda x: x.ix, lambda x: x.loc, @@ -321,7 +323,7 @@ def f(): def f(): with catch_warnings(record=True): idxr(s)[l] - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) # setitem for l in [slice(3.0, 4), @@ -330,7 +332,7 @@ def f(): def f(): s.iloc[l] = 0 - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) for idxr in [lambda x: x.ix, lambda x: x.loc, @@ -339,7 +341,7 @@ def f(): def f(): with catch_warnings(record=True): idxr(s)[l] = 0 - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def test_slice_integer(self): @@ -378,7 +380,7 @@ def test_slice_integer(self): def f(): s[l] - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) # getitem out-of-bounds for l in [slice(-6, 6), @@ -402,7 +404,7 @@ def f(): def f(): s[slice(-6.0, 6.0)] - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) # getitem odd floats for l, res1 in [(slice(2.5, 4), slice(3, 5)), @@ -425,7 +427,7 @@ def f(): def f(): s[l] - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) # setitem for l in [slice(3.0, 4), @@ -444,7 +446,7 @@ def f(): def f(): s[l] = 0 - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def test_integer_positional_indexing(self): """ make sure that we are raising on positional indexing @@ -466,7 +468,7 @@ def test_integer_positional_indexing(self): def f(): idxr(s)[l] - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def test_slice_integer_frame_getitem(self): @@ -493,7 +495,7 @@ def test_slice_integer_frame_getitem(self): def f(): s[l] - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) # getitem out-of-bounds for l in [slice(-10, 10), @@ -506,7 +508,7 @@ def f(): def f(): s[slice(-10.0, 10.0)] - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) # getitem odd floats for l, res in [(slice(0.5, 1), slice(1, 2)), @@ -521,7 +523,7 @@ def f(): def f(): s[l] - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) # setitem for l in [slice(3.0, 4), @@ -538,7 +540,7 @@ def f(): def f(): s[l] = 0 - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def test_slice_float(self): @@ -610,9 +612,9 @@ def test_floating_misc(self): # value not found (and no fallbacking at all) # scalar integers - self.assertRaises(KeyError, lambda: s.loc[4]) - self.assertRaises(KeyError, lambda: s.loc[4]) - self.assertRaises(KeyError, lambda: s[4]) + pytest.raises(KeyError, lambda: s.loc[4]) + pytest.raises(KeyError, lambda: s.loc[4]) + pytest.raises(KeyError, lambda: s[4]) # fancy floats/integers create the correct entry (as nan) # fancy tests diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index 517194835ca73..174026a00fcdd 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -1,5 +1,7 @@ """ test positional based indexing with iloc """ +import pytest + from warnings import catch_warnings import numpy as np @@ -23,26 +25,26 @@ def test_iloc_exceeds_bounds(self): with tm.assertRaisesRegexp(IndexError, 'positional indexers are out-of-bounds'): df.iloc[:, [0, 1, 2, 3, 4, 5]] - self.assertRaises(IndexError, lambda: df.iloc[[1, 30]]) - self.assertRaises(IndexError, lambda: df.iloc[[1, -30]]) - self.assertRaises(IndexError, lambda: df.iloc[[100]]) + pytest.raises(IndexError, lambda: df.iloc[[1, 30]]) + pytest.raises(IndexError, lambda: df.iloc[[1, -30]]) + pytest.raises(IndexError, lambda: df.iloc[[100]]) s = df['A'] - self.assertRaises(IndexError, lambda: s.iloc[[100]]) - self.assertRaises(IndexError, lambda: s.iloc[[-100]]) + pytest.raises(IndexError, lambda: s.iloc[[100]]) + pytest.raises(IndexError, lambda: s.iloc[[-100]]) # still raise on a single indexer msg = 'single positional indexer is out-of-bounds' with tm.assertRaisesRegexp(IndexError, msg): df.iloc[30] - self.assertRaises(IndexError, lambda: df.iloc[-30]) + pytest.raises(IndexError, lambda: df.iloc[-30]) # GH10779 # single positive/negative indexer exceeding Series bounds should raise # an IndexError with tm.assertRaisesRegexp(IndexError, msg): s.iloc[30] - self.assertRaises(IndexError, lambda: s.iloc[-30]) + pytest.raises(IndexError, lambda: s.iloc[-30]) # slices are ok result = df.iloc[:, 4:10] # 0 < start < len < stop @@ -101,8 +103,8 @@ def check(result, expected): check(dfl.iloc[:, 1:3], dfl.iloc[:, [1]]) check(dfl.iloc[4:6], dfl.iloc[[4]]) - self.assertRaises(IndexError, lambda: dfl.iloc[[4, 5, 6]]) - self.assertRaises(IndexError, lambda: dfl.iloc[:, 4]) + pytest.raises(IndexError, lambda: dfl.iloc[[4, 5, 6]]) + pytest.raises(IndexError, lambda: dfl.iloc[:, 4]) def test_iloc_getitem_int(self): @@ -385,10 +387,10 @@ def test_iloc_getitem_labelled_frame(self): self.assertEqual(result, exp) # out-of-bounds exception - self.assertRaises(IndexError, df.iloc.__getitem__, tuple([10, 5])) + pytest.raises(IndexError, df.iloc.__getitem__, tuple([10, 5])) # trying to use a label - self.assertRaises(ValueError, df.iloc.__getitem__, tuple(['j', 'D'])) + pytest.raises(ValueError, df.iloc.__getitem__, tuple(['j', 'D'])) def test_iloc_getitem_doc_issue(self): @@ -488,10 +490,10 @@ def test_iloc_mask(self): # GH 3631, iloc with a mask (of a series) should raise df = DataFrame(lrange(5), list('ABCDE'), columns=['a']) mask = (df.a % 2 == 0) - self.assertRaises(ValueError, df.iloc.__getitem__, tuple([mask])) + pytest.raises(ValueError, df.iloc.__getitem__, tuple([mask])) mask.index = lrange(len(mask)) - self.assertRaises(NotImplementedError, df.iloc.__getitem__, - tuple([mask])) + pytest.raises(NotImplementedError, df.iloc.__getitem__, + tuple([mask])) # ndarray ok result = df.iloc[np.array([True] * len(mask), dtype=bool)] diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index ff3b1cc3dbc89..fe934e7b2a7e0 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -3,6 +3,8 @@ """ test fancy indexing & misc """ +import pytest + from warnings import catch_warnings from datetime import datetime @@ -40,7 +42,7 @@ def f(): df.loc[df.index[2:5], 'bar'] = np.array([2.33j, 1.23 + 0.1j, 2.2, 1.0]) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # valid df.loc[df.index[2:6], 'bar'] = np.array([2.33j, 1.23 + 0.1j, @@ -59,7 +61,7 @@ def f(): def f(): df[2:5] = np.arange(1, 4) * 1j - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def test_setitem_dtype_upcast(self): @@ -240,7 +242,7 @@ def test_multitype_list_index_access(self): df = pd.DataFrame(np.random.random((10, 5)), columns=["a"] + [20, 21, 22, 23]) - with self.assertRaises(KeyError): + with pytest.raises(KeyError): df[[22, 26, -8]] self.assertEqual(df[21].shape[0], df.shape[0]) @@ -429,18 +431,18 @@ def test_string_slice(self): df = pd.DataFrame([1], pd.Index([pd.Timestamp('2011-01-01')], dtype=object)) self.assertTrue(df.index.is_all_dates) - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): df['2011'] - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): df.loc['2011', 0] df = pd.DataFrame() self.assertFalse(df.index.is_all_dates) - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): df['2011'] - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): df.loc['2011', 0] def test_mi_access(self): diff --git a/pandas/tests/indexing/test_ix.py b/pandas/tests/indexing/test_ix.py index d8b43abd1b537..c3ce21343b8d1 100644 --- a/pandas/tests/indexing/test_ix.py +++ b/pandas/tests/indexing/test_ix.py @@ -1,5 +1,7 @@ """ test indexing with ix """ +import pytest + from warnings import catch_warnings import numpy as np @@ -96,7 +98,7 @@ def compare(result, expected): with catch_warnings(record=True): df.ix[key] - self.assertRaises(TypeError, lambda: df.loc[key]) + pytest.raises(TypeError, lambda: df.loc[key]) df = pd.DataFrame(np.random.randn(5, 4), columns=list('ABCD'), index=pd.date_range('2012-01-01', periods=5)) @@ -116,7 +118,7 @@ def compare(result, expected): with catch_warnings(record=True): expected = df.ix[key] except KeyError: - self.assertRaises(KeyError, lambda: df.loc[key]) + pytest.raises(KeyError, lambda: df.loc[key]) continue result = df.loc[key] @@ -298,14 +300,14 @@ def test_ix_setitem_out_of_bounds_axis_0(self): np.random.randn(2, 5), index=["row%s" % i for i in range(2)], columns=["col%s" % i for i in range(5)]) with catch_warnings(record=True): - self.assertRaises(ValueError, df.ix.__setitem__, (2, 0), 100) + pytest.raises(ValueError, df.ix.__setitem__, (2, 0), 100) def test_ix_setitem_out_of_bounds_axis_1(self): df = pd.DataFrame( np.random.randn(5, 2), index=["row%s" % i for i in range(5)], columns=["col%s" % i for i in range(2)]) with catch_warnings(record=True): - self.assertRaises(ValueError, df.ix.__setitem__, (0, 2), 100) + pytest.raises(ValueError, df.ix.__setitem__, (0, 2), 100) def test_ix_empty_list_indexer_is_ok(self): with catch_warnings(record=True): diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index af9d3ffdf6671..b2a5e6147cd28 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -1,6 +1,8 @@ """ test label based indexing with loc """ import itertools +import pytest + from warnings import catch_warnings import numpy as np @@ -231,8 +233,8 @@ def test_loc_to_fail(self): columns=['e', 'f', 'g']) # raise a KeyError? - self.assertRaises(KeyError, df.loc.__getitem__, - tuple([[1, 2], [1, 2]])) + pytest.raises(KeyError, df.loc.__getitem__, + tuple([[1, 2], [1, 2]])) # GH 7496 # loc should not fallback @@ -241,10 +243,10 @@ def test_loc_to_fail(self): s.loc[1] = 1 s.loc['a'] = 2 - self.assertRaises(KeyError, lambda: s.loc[-1]) - self.assertRaises(KeyError, lambda: s.loc[[-1, -2]]) + pytest.raises(KeyError, lambda: s.loc[-1]) + pytest.raises(KeyError, lambda: s.loc[[-1, -2]]) - self.assertRaises(KeyError, lambda: s.loc[['4']]) + pytest.raises(KeyError, lambda: s.loc[['4']]) s.loc[-1] = 3 result = s.loc[[-1, -2]] @@ -252,14 +254,14 @@ def test_loc_to_fail(self): tm.assert_series_equal(result, expected) s['a'] = 2 - self.assertRaises(KeyError, lambda: s.loc[[-2]]) + pytest.raises(KeyError, lambda: s.loc[[-2]]) del s['a'] def f(): s.loc[[-2]] = 0 - self.assertRaises(KeyError, f) + pytest.raises(KeyError, f) # inconsistency between .loc[values] and .loc[values,:] # GH 7999 @@ -268,12 +270,12 @@ def f(): def f(): df.loc[[3], :] - self.assertRaises(KeyError, f) + pytest.raises(KeyError, f) def f(): df.loc[[3]] - self.assertRaises(KeyError, f) + pytest.raises(KeyError, f) def test_loc_getitem_label_slice(self): @@ -540,11 +542,11 @@ def test_loc_non_unique(self): # these are going to raise becuase the we are non monotonic df = DataFrame({'A': [1, 2, 3, 4, 5, 6], 'B': [3, 4, 5, 6, 7, 8]}, index=[0, 1, 0, 1, 2, 3]) - self.assertRaises(KeyError, df.loc.__getitem__, - tuple([slice(1, None)])) - self.assertRaises(KeyError, df.loc.__getitem__, - tuple([slice(0, None)])) - self.assertRaises(KeyError, df.loc.__getitem__, tuple([slice(1, 2)])) + pytest.raises(KeyError, df.loc.__getitem__, + tuple([slice(1, None)])) + pytest.raises(KeyError, df.loc.__getitem__, + tuple([slice(0, None)])) + pytest.raises(KeyError, df.loc.__getitem__, tuple([slice(1, 2)])) # monotonic are ok df = DataFrame({'A': [1, 2, 3, 4, 5, 6], diff --git a/pandas/tests/indexing/test_multiindex.py b/pandas/tests/indexing/test_multiindex.py index c39e25a1f1d74..18cb9a3a063b9 100644 --- a/pandas/tests/indexing/test_multiindex.py +++ b/pandas/tests/indexing/test_multiindex.py @@ -446,7 +446,7 @@ def test_multiindex_setitem(self): def f(): df.loc['bar'] *= 2 - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) # from SO # http://stackoverflow.com/questions/24572040/pandas-access-the-level-of-multiindex-for-inplace-operation @@ -492,12 +492,12 @@ def test_getitem_duplicates_multiindex(self): def f(): df.val['A'] - self.assertRaises(KeyError, f) + pytest.raises(KeyError, f) def f(): df.val['X'] - self.assertRaises(KeyError, f) + pytest.raises(KeyError, f) # A is treated as a special Timestamp index = MultiIndex(levels=[['A', 'B', 'C'], @@ -514,7 +514,7 @@ def f(): def f(): df.val['X'] - self.assertRaises(KeyError, f) + pytest.raises(KeyError, f) # GH 7866 # multi-index slicing with missing indexers @@ -534,7 +534,7 @@ def f(): tm.assert_series_equal(result, expected) # not any values found - self.assertRaises(KeyError, lambda: s.loc[['D']]) + pytest.raises(KeyError, lambda: s.loc[['D']]) # empty ok result = s.loc[[]] @@ -611,13 +611,13 @@ def f(): with catch_warnings(record=True): df.ix[4, 'c'] = [0, 1, 2, 3] - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def f(): with catch_warnings(record=True): df.ix[4, 'c'] = [0] - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # groupby example NUM_ROWS = 100 @@ -786,12 +786,12 @@ def test_per_axis_per_level_getitem(self): def f(): df.loc[(slice(None), np.array([True, False])), :] - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # ambiguous cases # these can be multiply interpreted (e.g. in this case # as df.loc[slice(None),[1]] as well - self.assertRaises(KeyError, lambda: df.loc[slice(None), [1]]) + pytest.raises(KeyError, lambda: df.loc[slice(None), [1]]) result = df.loc[(slice(None), [1]), :] expected = df.iloc[[0, 3]] @@ -989,7 +989,7 @@ def test_per_axis_per_level_doc_examples(self): def f(): df.loc['A1', (slice(None), 'foo')] - self.assertRaises(UnsortedIndexError, f) + pytest.raises(UnsortedIndexError, f) df = df.sort_index(axis=1) # slicing @@ -1038,17 +1038,17 @@ def test_loc_axis_arguments(self): def f(): df.loc(axis=-1)[:, :, ['C1', 'C3']] - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def f(): df.loc(axis=2)[:, :, ['C1', 'C3']] - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def f(): df.loc(axis='foo')[:, :, ['C1', 'C3']] - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def test_per_axis_per_level_setitem(self): @@ -1153,13 +1153,13 @@ def f(): df.loc[(slice(None), 1), (slice(None), ['foo'])] = np.array( [[100], [100, 100]], dtype='int64') - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def f(): df.loc[(slice(None), 1), (slice(None), ['foo'])] = np.array( [100, 100, 100, 100], dtype='int64') - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # with an alignable rhs df = df_orig.copy() diff --git a/pandas/tests/indexing/test_panel.py b/pandas/tests/indexing/test_panel.py index 8daef6155212c..8aa35a163babc 100644 --- a/pandas/tests/indexing/test_panel.py +++ b/pandas/tests/indexing/test_panel.py @@ -65,7 +65,7 @@ def test_iloc_getitem_panel(self): def f(): p.iloc[0, [True, True], [0, 1, 2]] - self.assertRaises(IndexError, f) + pytest.raises(IndexError, f) # trying to use a label with pytest.raises(ValueError): @@ -89,12 +89,12 @@ def f(): def f(): p.iloc[0, [True, True, True], [0, 1, 2]] - self.assertRaises(IndexError, f) + pytest.raises(IndexError, f) def f(): p.iloc[0, [True, True, True], [2]] - self.assertRaises(IndexError, f) + pytest.raises(IndexError, f) def test_iloc_panel_issue(self): @@ -211,7 +211,7 @@ def f(): wp.loc[['Item1', 'Item2'], :, ['A', 'B']] = wp2.loc[ ['Item1', 'Item2'], :, ['A', 'B']] - self.assertRaises(NotImplementedError, f) + pytest.raises(NotImplementedError, f) # to_assign = wp2.loc[['Item1', 'Item2'], :, ['A', 'B']] # wp.loc[['Item1', 'Item2'], :, ['A', 'B']] = to_assign diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py index f51f050c57624..80d2d5729c610 100644 --- a/pandas/tests/indexing/test_partial.py +++ b/pandas/tests/indexing/test_partial.py @@ -3,6 +3,9 @@ TOD: these should be split among the indexer tests """ + +import pytest + from warnings import catch_warnings import numpy as np @@ -46,12 +49,12 @@ def test_partial_setting(self): def f(): s.iloc[3] = 5. - self.assertRaises(IndexError, f) + pytest.raises(IndexError, f) def f(): s.iat[3] = 5. - self.assertRaises(IndexError, f) + pytest.raises(IndexError, f) # ## frame ## @@ -64,12 +67,12 @@ def f(): def f(): df.iloc[4, 2] = 5. - self.assertRaises(IndexError, f) + pytest.raises(IndexError, f) def f(): df.iat[4, 2] = 5. - self.assertRaises(IndexError, f) + pytest.raises(IndexError, f) # row setting where it exists expected = DataFrame(dict({'A': [0, 4, 4], 'B': [1, 5, 5]})) @@ -204,7 +207,7 @@ def test_partial_setting_mixed_dtype(self): def f(): df.loc[0] = [1, 2, 3] - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # TODO: #15657, these are left as object and not coerced df = DataFrame(columns=['A', 'B']) @@ -237,7 +240,7 @@ def test_series_partial_set(self): tm.assert_series_equal(result, expected, check_index_type=True) # raises as nothing in in the index - self.assertRaises(KeyError, lambda: ser.loc[[3, 3, 3]]) + pytest.raises(KeyError, lambda: ser.loc[[3, 3, 3]]) expected = Series([0.2, 0.2, np.nan], index=[2, 2, 3]) result = ser.loc[[2, 2, 3]] @@ -301,7 +304,7 @@ def test_series_partial_set_with_name(self): tm.assert_series_equal(result, expected, check_index_type=True) # raises as nothing in in the index - self.assertRaises(KeyError, lambda: ser.loc[[3, 3, 3]]) + pytest.raises(KeyError, lambda: ser.loc[[3, 3, 3]]) exp_idx = Index([2, 2, 3], dtype='int64', name='idx') expected = Series([0.2, 0.2, np.nan], index=exp_idx, name='s') @@ -361,25 +364,25 @@ def f(): with catch_warnings(record=True): df.loc[100.0, :] = df.ix[0] - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def f(): with catch_warnings(record=True): df.loc[100, :] = df.ix[0] - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def f(): with catch_warnings(record=True): df.ix[100.0, :] = df.ix[0] - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def f(): with catch_warnings(record=True): df.ix[100, :] = df.ix[0] - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # allow object conversion here df = orig.copy() @@ -425,17 +428,17 @@ def test_partial_set_empty_frame(self): def f(): df.loc[1] = 1 - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def f(): df.loc[1] = Series([1], index=['foo']) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def f(): df.loc[:, 1] = 1 - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # these work as they don't really change # anything but the index diff --git a/pandas/tests/indexing/test_scalar.py b/pandas/tests/indexing/test_scalar.py index 0eeaec3e00fa6..3522974c18061 100644 --- a/pandas/tests/indexing/test_scalar.py +++ b/pandas/tests/indexing/test_scalar.py @@ -1,5 +1,7 @@ """ test scalar indexing, including at and iat """ +import pytest + import numpy as np from pandas import (Series, DataFrame, Timestamp, @@ -30,7 +32,7 @@ def _check(f, func, values=False): for f in [d['labels'], d['ts'], d['floats']]: if f is not None: - self.assertRaises(ValueError, self.check_values, f, 'iat') + pytest.raises(ValueError, self.check_values, f, 'iat') # at for f in [d['ints'], d['uints'], d['labels'], @@ -57,7 +59,7 @@ def _check(f, func, values=False): for f in [d['labels'], d['ts'], d['floats']]: if f is not None: - self.assertRaises(ValueError, _check, f, 'iat') + pytest.raises(ValueError, _check, f, 'iat') # at for f in [d['ints'], d['uints'], d['labels'], @@ -107,8 +109,8 @@ def test_imethods_with_dups(self): result = s.iat[2] self.assertEqual(result, 2) - self.assertRaises(IndexError, lambda: s.iat[10]) - self.assertRaises(IndexError, lambda: s.iat[-10]) + pytest.raises(IndexError, lambda: s.iat[10]) + pytest.raises(IndexError, lambda: s.iat[-10]) result = s.iloc[[2, 3]] expected = Series([2, 3], [2, 2], dtype='int64') @@ -129,22 +131,22 @@ def test_at_to_fail(self): s = Series([1, 2, 3], index=list('abc')) result = s.at['a'] self.assertEqual(result, 1) - self.assertRaises(ValueError, lambda: s.at[0]) + pytest.raises(ValueError, lambda: s.at[0]) df = DataFrame({'A': [1, 2, 3]}, index=list('abc')) result = df.at['a', 'A'] self.assertEqual(result, 1) - self.assertRaises(ValueError, lambda: df.at['a', 0]) + pytest.raises(ValueError, lambda: df.at['a', 0]) s = Series([1, 2, 3], index=[3, 2, 1]) result = s.at[1] self.assertEqual(result, 3) - self.assertRaises(ValueError, lambda: s.at['a']) + pytest.raises(ValueError, lambda: s.at['a']) df = DataFrame({0: [1, 2, 3]}, index=[3, 2, 1]) result = df.at[1, 0] self.assertEqual(result, 3) - self.assertRaises(ValueError, lambda: df.at['a', 0]) + pytest.raises(ValueError, lambda: df.at['a', 0]) # GH 13822, incorrect error string with non-unique columns when missing # column is accessed diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 1d471163790d5..3784840fbfd28 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -1177,7 +1177,7 @@ def test_to_string_specified_header(self): self.assertEqual(df_s, expected) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.to_string(header=['X']) def test_to_string_no_index(self): @@ -2563,7 +2563,7 @@ def test_format_percentiles(): expected = ['0%', '50%', '2.0%', '50%', '66.67%', '99.99%'] assert result == expected - tm.assertRaises(ValueError, fmt.format_percentiles, [0.1, np.nan, 0.5]) - tm.assertRaises(ValueError, fmt.format_percentiles, [-0.001, 0.1, 0.5]) - tm.assertRaises(ValueError, fmt.format_percentiles, [2, 0.1, 0.5]) - tm.assertRaises(ValueError, fmt.format_percentiles, [0.1, 0.5, 'a']) + pytest.raises(ValueError, fmt.format_percentiles, [0.1, np.nan, 0.5]) + pytest.raises(ValueError, fmt.format_percentiles, [-0.001, 0.1, 0.5]) + pytest.raises(ValueError, fmt.format_percentiles, [2, 0.1, 0.5]) + pytest.raises(ValueError, fmt.format_percentiles, [0.1, 0.5, 'a']) diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py index 4fb91c40aba3a..3b8bbf239d941 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/test_style.py @@ -34,7 +34,7 @@ def h(x, foo='bar'): ] def test_init_non_pandas(self): - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): Styler([1, 2, 3]) def test_init_series(self): @@ -358,10 +358,10 @@ def test_highlight_null(self, null_color='red'): def test_nonunique_raises(self): df = pd.DataFrame([[1, 2]], columns=['A', 'A']) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.style - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): Styler(df) def test_caption(self): @@ -494,9 +494,9 @@ def test_display_format(self): def test_display_format_raises(self): df = pd.DataFrame(np.random.randn(2, 2)) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): df.style.format(5) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): df.style.format(True) def test_display_subset(self): @@ -550,33 +550,33 @@ def test_display_dict(self): def test_bad_apply_shape(self): df = pd.DataFrame([[1, 2], [3, 4]]) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.style._apply(lambda x: 'x', subset=pd.IndexSlice[[0, 1], :]) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.style._apply(lambda x: [''], subset=pd.IndexSlice[[0, 1], :]) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.style._apply(lambda x: ['', '', '', '']) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.style._apply(lambda x: ['', '', ''], subset=1) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.style._apply(lambda x: ['', '', ''], axis=1) def test_apply_bad_return(self): def f(x): return '' df = pd.DataFrame([[1, 2], [3, 4]]) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): df.style._apply(f, axis=None) def test_apply_bad_labels(self): def f(x): return pd.DataFrame(index=[1, 2], columns=['a', 'b']) df = pd.DataFrame([[1, 2], [3, 4]]) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.style._apply(f, axis=None) def test_get_level_lengths(self): diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py index 29ead83f3bcd9..2542deb0cedf1 100644 --- a/pandas/tests/io/formats/test_to_latex.py +++ b/pandas/tests/io/formats/test_to_latex.py @@ -470,7 +470,7 @@ def test_to_latex_specified_header(self): assert withoutescape_result == withoutescape_expected - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.to_latex(header=['A']) def test_to_latex_decimal(self, frame): diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py index 2a785375acaea..cbb302ad39dd6 100644 --- a/pandas/tests/io/json/test_json_table_schema.py +++ b/pandas/tests/io/json/test_json_table_schema.py @@ -327,7 +327,7 @@ def test_to_json_categorical_index(self): self.assertEqual(result, expected) def test_date_format_raises(self): - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): self.df.to_json(orient='table', date_format='epoch') # others work diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py index ee79859e9b71a..42456d2630886 100644 --- a/pandas/tests/io/json/test_normalize.py +++ b/pandas/tests/io/json/test_normalize.py @@ -300,10 +300,10 @@ def test_json_normalize_errors(self): self.assertEqual(j.fillna('').to_dict(), expected) - self.assertRaises(KeyError, - json_normalize, data=i['Trades'], - record_path=[['general', 'stocks']], - meta=[['general', 'tradeid'], - ['general', 'trade_version']], - errors='raise' - ) + pytest.raises(KeyError, + json_normalize, data=i['Trades'], + record_path=[['general', 'stocks']], + meta=[['general', 'tradeid'], + ['general', 'trade_version']], + errors='raise' + ) diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 99b0f0493117c..b152f7bb089de 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -96,8 +96,8 @@ def test_frame_non_unique_index(self): df = DataFrame([['a', 'b'], ['c', 'd']], index=[1, 1], columns=['x', 'y']) - self.assertRaises(ValueError, df.to_json, orient='index') - self.assertRaises(ValueError, df.to_json, orient='columns') + pytest.raises(ValueError, df.to_json, orient='index') + pytest.raises(ValueError, df.to_json, orient='columns') assert_frame_equal(df, read_json(df.to_json(orient='split'), orient='split')) @@ -111,9 +111,9 @@ def test_frame_non_unique_columns(self): df = DataFrame([['a', 'b'], ['c', 'd']], index=[1, 2], columns=['x', 'x']) - self.assertRaises(ValueError, df.to_json, orient='index') - self.assertRaises(ValueError, df.to_json, orient='columns') - self.assertRaises(ValueError, df.to_json, orient='records') + pytest.raises(ValueError, df.to_json, orient='index') + pytest.raises(ValueError, df.to_json, orient='columns') + pytest.raises(ValueError, df.to_json, orient='records') assert_frame_equal(df, read_json(df.to_json(orient='split'), orient='split', dtype=False)) @@ -151,12 +151,12 @@ def _check_orient(df, orient, dtype=None, numpy=False, # if we are not unique, then check that we are raising ValueError # for the appropriate orients if not df.index.is_unique and orient in ['index', 'columns']: - self.assertRaises( + pytest.raises( ValueError, lambda: df.to_json(orient=orient)) return if (not df.columns.is_unique and orient in ['index', 'columns', 'records']): - self.assertRaises( + pytest.raises( ValueError, lambda: df.to_json(orient=orient)) return @@ -322,21 +322,21 @@ def _check_all_orients(df, dtype=None, convert_axes=True, _check_orient(df.transpose().transpose(), "index", dtype=False) def test_frame_from_json_bad_data(self): - self.assertRaises(ValueError, read_json, StringIO('{"key":b:a:d}')) + pytest.raises(ValueError, read_json, StringIO('{"key":b:a:d}')) # too few indices json = StringIO('{"columns":["A","B"],' '"index":["2","3"],' '"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}') - self.assertRaises(ValueError, read_json, json, - orient="split") + pytest.raises(ValueError, read_json, json, + orient="split") # too many columns json = StringIO('{"columns":["A","B","C"],' '"index":["1","2","3"],' '"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}') - self.assertRaises(AssertionError, read_json, json, - orient="split") + pytest.raises(AssertionError, read_json, json, + orient="split") # bad key json = StringIO('{"badkey":["A","B"],' @@ -410,7 +410,7 @@ def test_frame_to_json_float_precision(self): def test_frame_to_json_except(self): df = DataFrame([1, 2, 3]) - self.assertRaises(ValueError, df.to_json, orient="garbage") + pytest.raises(ValueError, df.to_json, orient="garbage") def test_frame_empty(self): df = DataFrame(columns=['jim', 'joe']) @@ -514,7 +514,7 @@ def test_blocks_compat_GH9037(self): def test_series_non_unique_index(self): s = Series(['a', 'b'], index=[1, 1]) - self.assertRaises(ValueError, s.to_json, orient='index') + pytest.raises(ValueError, s.to_json, orient='index') assert_series_equal(s, read_json(s.to_json(orient='split'), orient='split', typ='series')) @@ -587,7 +587,7 @@ def _check_all_orients(series, dtype=None, check_index_type=True): def test_series_to_json_except(self): s = Series([1, 2, 3]) - self.assertRaises(ValueError, s.to_json, orient="garbage") + pytest.raises(ValueError, s.to_json, orient="garbage") def test_series_from_json_precise_float(self): s = Series([4.56, 4.56, 4.56]) @@ -695,8 +695,8 @@ def test_w_date(date, date_unit=None): test_w_date('20130101 20:43:42.123456', date_unit='us') test_w_date('20130101 20:43:42.123456789', date_unit='ns') - self.assertRaises(ValueError, df.to_json, date_format='iso', - date_unit='foo') + pytest.raises(ValueError, df.to_json, date_format='iso', + date_unit='foo') def test_date_format_series(self): def test_w_date(date, date_unit=None): @@ -717,8 +717,8 @@ def test_w_date(date, date_unit=None): test_w_date('20130101 20:43:42.123456789', date_unit='ns') ts = Series(Timestamp('20130101 20:43:42.123'), index=self.ts.index) - self.assertRaises(ValueError, ts.to_json, date_format='iso', - date_unit='foo') + pytest.raises(ValueError, ts.to_json, date_format='iso', + date_unit='foo') def test_date_unit(self): df = self.tsframe.copy() @@ -884,12 +884,12 @@ def test_default_handler_numpy_unsupported_dtype(self): def test_default_handler_raises(self): def my_handler_raises(obj): raise TypeError("raisin") - self.assertRaises(TypeError, - DataFrame({'a': [1, 2, object()]}).to_json, - default_handler=my_handler_raises) - self.assertRaises(TypeError, - DataFrame({'a': [1, 2, complex(4, -5)]}).to_json, - default_handler=my_handler_raises) + pytest.raises(TypeError, + DataFrame({'a': [1, 2, object()]}).to_json, + default_handler=my_handler_raises) + pytest.raises(TypeError, + DataFrame({'a': [1, 2, complex(4, -5)]}).to_json, + default_handler=my_handler_raises) def test_categorical(self): # GH4377 df.to_json segfaults with non-ndarray blocks diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index 545165be37178..f0ccce5830a65 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -226,14 +226,14 @@ def test_doublePrecisionTest(self): def test_invalidDoublePrecision(self): input = 30.12345678901234567890 - self.assertRaises(ValueError, ujson.encode, input, double_precision=20) - self.assertRaises(ValueError, ujson.encode, input, double_precision=-1) + pytest.raises(ValueError, ujson.encode, input, double_precision=20) + pytest.raises(ValueError, ujson.encode, input, double_precision=-1) # will throw typeError - self.assertRaises(TypeError, ujson.encode, input, double_precision='9') + pytest.raises(TypeError, ujson.encode, input, double_precision='9') # will throw typeError - self.assertRaises(TypeError, ujson.encode, - input, double_precision=None) + pytest.raises(TypeError, ujson.encode, + input, double_precision=None) def test_encodeStringConversion2(self): input = "A string \\ / \b \f \n \r \t" @@ -446,7 +446,7 @@ def test_datetime_units(self): roundtrip = ujson.decode(ujson.encode(val, date_unit='ns')) self.assertEqual(roundtrip, stamp.value) - self.assertRaises(ValueError, ujson.encode, val, date_unit='foo') + pytest.raises(ValueError, ujson.encode, val, date_unit='foo') def test_encodeToUTF8(self): input = "\xe6\x97\xa5\xd1\x88" @@ -912,7 +912,7 @@ def recursive_attr(self): def __str__(self): return str(self.val) - self.assertRaises(OverflowError, ujson.encode, _TestObject("foo")) + pytest.raises(OverflowError, ujson.encode, _TestObject("foo")) self.assertEqual('"foo"', ujson.encode(_TestObject("foo"), default_handler=str)) @@ -1101,7 +1101,7 @@ def testOdArray(self): def will_raise(): ujson.encode(np.array(1)) - self.assertRaises(TypeError, will_raise) + pytest.raises(TypeError, will_raise) def testArrayNumpyExcept(self): diff --git a/pandas/tests/io/msgpack/test_except.py b/pandas/tests/io/msgpack/test_except.py index 4bcef3607bfa4..6246e0777daee 100644 --- a/pandas/tests/io/msgpack/test_except.py +++ b/pandas/tests/io/msgpack/test_except.py @@ -1,6 +1,7 @@ # coding: utf-8 -import unittest +import pytest + from pandas.io.msgpack import packb, unpackb @@ -8,26 +9,26 @@ class DummyException(Exception): pass -class TestExceptions(unittest.TestCase): +class TestExceptions(object): def test_raise_on_find_unsupported_value(self): import datetime - self.assertRaises(TypeError, packb, datetime.datetime.now()) + pytest.raises(TypeError, packb, datetime.datetime.now()) def test_raise_from_object_hook(self): def hook(obj): raise DummyException - self.assertRaises(DummyException, unpackb, packb({}), object_hook=hook) - self.assertRaises(DummyException, unpackb, packb({'fizz': 'buzz'}), - object_hook=hook) - self.assertRaises(DummyException, unpackb, packb({'fizz': 'buzz'}), - object_pairs_hook=hook) - self.assertRaises(DummyException, unpackb, - packb({'fizz': {'buzz': 'spam'}}), object_hook=hook) - self.assertRaises(DummyException, unpackb, - packb({'fizz': {'buzz': 'spam'}}), - object_pairs_hook=hook) + pytest.raises(DummyException, unpackb, packb({}), object_hook=hook) + pytest.raises(DummyException, unpackb, packb({'fizz': 'buzz'}), + object_hook=hook) + pytest.raises(DummyException, unpackb, packb({'fizz': 'buzz'}), + object_pairs_hook=hook) + pytest.raises(DummyException, unpackb, + packb({'fizz': {'buzz': 'spam'}}), object_hook=hook) + pytest.raises(DummyException, unpackb, + packb({'fizz': {'buzz': 'spam'}}), + object_pairs_hook=hook) def test_invalidvalue(self): - self.assertRaises(ValueError, unpackb, b'\xd9\x97#DL_') + pytest.raises(ValueError, unpackb, b'\xd9\x97#DL_') diff --git a/pandas/tests/io/msgpack/test_limits.py b/pandas/tests/io/msgpack/test_limits.py index a908ee3547634..e906d14a2b5a8 100644 --- a/pandas/tests/io/msgpack/test_limits.py +++ b/pandas/tests/io/msgpack/test_limits.py @@ -1,6 +1,9 @@ # coding: utf-8 from __future__ import (absolute_import, division, print_function, unicode_literals) + +import pytest + import pandas.util.testing as tm from pandas.io.msgpack import packb, unpackb, Packer, Unpacker, ExtType @@ -11,22 +14,22 @@ class TestLimits(tm.TestCase): def test_integer(self): x = -(2 ** 63) assert unpackb(packb(x)) == x - self.assertRaises((OverflowError, ValueError), packb, x - 1) + pytest.raises((OverflowError, ValueError), packb, x - 1) x = 2 ** 64 - 1 assert unpackb(packb(x)) == x - self.assertRaises((OverflowError, ValueError), packb, x + 1) + pytest.raises((OverflowError, ValueError), packb, x + 1) def test_array_header(self): packer = Packer() packer.pack_array_header(2 ** 32 - 1) - self.assertRaises((OverflowError, ValueError), - packer.pack_array_header, 2 ** 32) + pytest.raises((OverflowError, ValueError), + packer.pack_array_header, 2 ** 32) def test_map_header(self): packer = Packer() packer.pack_map_header(2 ** 32 - 1) - self.assertRaises((OverflowError, ValueError), - packer.pack_array_header, 2 ** 32) + pytest.raises((OverflowError, ValueError), + packer.pack_array_header, 2 ** 32) def test_max_str_len(self): d = 'x' * 3 @@ -38,7 +41,7 @@ def test_max_str_len(self): unpacker = Unpacker(max_str_len=2, encoding='utf-8') unpacker.feed(packed) - self.assertRaises(ValueError, unpacker.unpack) + pytest.raises(ValueError, unpacker.unpack) def test_max_bin_len(self): d = b'x' * 3 @@ -50,7 +53,7 @@ def test_max_bin_len(self): unpacker = Unpacker(max_bin_len=2) unpacker.feed(packed) - self.assertRaises(ValueError, unpacker.unpack) + pytest.raises(ValueError, unpacker.unpack) def test_max_array_len(self): d = [1, 2, 3] @@ -62,7 +65,7 @@ def test_max_array_len(self): unpacker = Unpacker(max_array_len=2) unpacker.feed(packed) - self.assertRaises(ValueError, unpacker.unpack) + pytest.raises(ValueError, unpacker.unpack) def test_max_map_len(self): d = {1: 2, 3: 4, 5: 6} @@ -74,7 +77,7 @@ def test_max_map_len(self): unpacker = Unpacker(max_map_len=2) unpacker.feed(packed) - self.assertRaises(ValueError, unpacker.unpack) + pytest.raises(ValueError, unpacker.unpack) def test_max_ext_len(self): d = ExtType(42, b"abc") @@ -86,4 +89,4 @@ def test_max_ext_len(self): unpacker = Unpacker(max_ext_len=2) unpacker.feed(packed) - self.assertRaises(ValueError, unpacker.unpack) + pytest.raises(ValueError, unpacker.unpack) diff --git a/pandas/tests/io/msgpack/test_obj.py b/pandas/tests/io/msgpack/test_obj.py index b067dacb84494..4a6b89907954e 100644 --- a/pandas/tests/io/msgpack/test_obj.py +++ b/pandas/tests/io/msgpack/test_obj.py @@ -1,6 +1,7 @@ # coding: utf-8 -import unittest +import pytest + from pandas.io.msgpack import packb, unpackb @@ -8,7 +9,7 @@ class DecodeError(Exception): pass -class TestObj(unittest.TestCase): +class TestObj(object): def _arr_to_str(self, arr): return ''.join(str(c) for c in arr) @@ -46,15 +47,15 @@ def test_decode_pairs_hook(self): assert unpacked[1] == prod_sum def test_only_one_obj_hook(self): - self.assertRaises(TypeError, unpackb, b'', object_hook=lambda x: x, - object_pairs_hook=lambda x: x) + pytest.raises(TypeError, unpackb, b'', object_hook=lambda x: x, + object_pairs_hook=lambda x: x) def test_bad_hook(self): def f(): packed = packb([3, 1 + 2j], default=lambda o: o) unpacked = unpackb(packed, use_list=1) # noqa - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def test_array_hook(self): packed = packb([1, 2, 3]) @@ -66,11 +67,11 @@ def f(): packed = packb({1: {'__complex__': True, 'real': 1, 'imag': 2}}) unpackb(packed, object_hook=self.bad_complex_decoder) - self.assertRaises(DecodeError, f) + pytest.raises(DecodeError, f) def test_an_exception_in_objecthook2(self): def f(): packed = packb({1: [{'__complex__': True, 'real': 1, 'imag': 2}]}) unpackb(packed, list_hook=self.bad_complex_decoder, use_list=1) - self.assertRaises(DecodeError, f) + pytest.raises(DecodeError, f) diff --git a/pandas/tests/io/msgpack/test_pack.py b/pandas/tests/io/msgpack/test_pack.py index 6f9a271cbd326..c0b3e1b24674f 100644 --- a/pandas/tests/io/msgpack/test_pack.py +++ b/pandas/tests/io/msgpack/test_pack.py @@ -1,14 +1,15 @@ # coding: utf-8 -import unittest +import pytest import struct + from pandas import compat from pandas.compat import u, OrderedDict from pandas.io.msgpack import packb, unpackb, Unpacker, Packer -class TestPack(unittest.TestCase): +class TestPack(object): def check(self, data, use_list=False): re = unpackb(packb(data), use_list=use_list) @@ -64,12 +65,12 @@ def testIgnoreUnicodeErrors(self): assert re == "abcdef" def testStrictUnicodeUnpack(self): - self.assertRaises(UnicodeDecodeError, unpackb, packb(b'abc\xeddef'), - encoding='utf-8', use_list=1) + pytest.raises(UnicodeDecodeError, unpackb, packb(b'abc\xeddef'), + encoding='utf-8', use_list=1) def testStrictUnicodePack(self): - self.assertRaises(UnicodeEncodeError, packb, compat.u("abc\xeddef"), - encoding='ascii', unicode_errors='strict') + pytest.raises(UnicodeEncodeError, packb, compat.u("abc\xeddef"), + encoding='ascii', unicode_errors='strict') def testIgnoreErrorsPack(self): re = unpackb( @@ -79,7 +80,7 @@ def testIgnoreErrorsPack(self): assert re == compat.u("abcdef") def testNoEncoding(self): - self.assertRaises(TypeError, packb, compat.u("abc"), encoding=None) + pytest.raises(TypeError, packb, compat.u("abc"), encoding=None) def testDecodeBinary(self): re = unpackb(packb("abc"), encoding=None, use_list=1) diff --git a/pandas/tests/io/msgpack/test_sequnpack.py b/pandas/tests/io/msgpack/test_sequnpack.py index c9c979c4e0e44..1178176c2c557 100644 --- a/pandas/tests/io/msgpack/test_sequnpack.py +++ b/pandas/tests/io/msgpack/test_sequnpack.py @@ -1,26 +1,26 @@ # coding: utf-8 -import unittest +import pytest from pandas import compat from pandas.io.msgpack import Unpacker, BufferFull from pandas.io.msgpack import OutOfData -class TestPack(unittest.TestCase): +class TestPack(object): def test_partialdata(self): unpacker = Unpacker() unpacker.feed(b'\xa5') - self.assertRaises(StopIteration, next, iter(unpacker)) + pytest.raises(StopIteration, next, iter(unpacker)) unpacker.feed(b'h') - self.assertRaises(StopIteration, next, iter(unpacker)) + pytest.raises(StopIteration, next, iter(unpacker)) unpacker.feed(b'a') - self.assertRaises(StopIteration, next, iter(unpacker)) + pytest.raises(StopIteration, next, iter(unpacker)) unpacker.feed(b'l') - self.assertRaises(StopIteration, next, iter(unpacker)) + pytest.raises(StopIteration, next, iter(unpacker)) unpacker.feed(b'l') - self.assertRaises(StopIteration, next, iter(unpacker)) + pytest.raises(StopIteration, next, iter(unpacker)) unpacker.feed(b'o') assert next(iter(unpacker)) == b'hallo' @@ -33,7 +33,7 @@ def test_foobar(self): assert unpacker.unpack() == ord(b'b') assert unpacker.unpack() == ord(b'a') assert unpacker.unpack() == ord(b'r') - self.assertRaises(OutOfData, unpacker.unpack) + pytest.raises(OutOfData, unpacker.unpack) unpacker.feed(b'foo') unpacker.feed(b'bar') @@ -53,13 +53,13 @@ def test_foobar_skip(self): unpacker.skip() assert unpacker.unpack() == ord(b'a') unpacker.skip() - self.assertRaises(OutOfData, unpacker.unpack) + pytest.raises(OutOfData, unpacker.unpack) def test_maxbuffersize(self): - self.assertRaises(ValueError, Unpacker, read_size=5, max_buffer_size=3) + pytest.raises(ValueError, Unpacker, read_size=5, max_buffer_size=3) unpacker = Unpacker(read_size=3, max_buffer_size=3, use_list=1) unpacker.feed(b'fo') - self.assertRaises(BufferFull, unpacker.feed, b'ob') + pytest.raises(BufferFull, unpacker.feed, b'ob') unpacker.feed(b'o') assert ord('f') == next(unpacker) unpacker.feed(b'b') diff --git a/pandas/tests/io/msgpack/test_unpack.py b/pandas/tests/io/msgpack/test_unpack.py index 24a8e885d19d6..158094d111b54 100644 --- a/pandas/tests/io/msgpack/test_unpack.py +++ b/pandas/tests/io/msgpack/test_unpack.py @@ -15,7 +15,7 @@ def test_unpack_array_header_from_file(self): assert unpacker.unpack() == 2 assert unpacker.unpack() == 3 assert unpacker.unpack() == 4 - self.assertRaises(OutOfData, unpacker.unpack) + pytest.raises(OutOfData, unpacker.unpack) def test_unpacker_hook_refcnt(self): if not hasattr(sys, 'getrefcount'): diff --git a/pandas/tests/io/parser/c_parser_only.py b/pandas/tests/io/parser/c_parser_only.py index 837b7a7922d75..6d3dc8f637012 100644 --- a/pandas/tests/io/parser/c_parser_only.py +++ b/pandas/tests/io/parser/c_parser_only.py @@ -108,22 +108,22 @@ def test_unsupported_dtype(self): df.to_csv(path) # valid but we don't support it (date) - self.assertRaises(TypeError, self.read_csv, path, - dtype={'A': 'datetime64', 'B': 'float64'}, - index_col=0) - self.assertRaises(TypeError, self.read_csv, path, - dtype={'A': 'datetime64', 'B': 'float64'}, - index_col=0, parse_dates=['B']) + pytest.raises(TypeError, self.read_csv, path, + dtype={'A': 'datetime64', 'B': 'float64'}, + index_col=0) + pytest.raises(TypeError, self.read_csv, path, + dtype={'A': 'datetime64', 'B': 'float64'}, + index_col=0, parse_dates=['B']) # valid but we don't support it - self.assertRaises(TypeError, self.read_csv, path, - dtype={'A': 'timedelta64', 'B': 'float64'}, - index_col=0) + pytest.raises(TypeError, self.read_csv, path, + dtype={'A': 'timedelta64', 'B': 'float64'}, + index_col=0) # valid but unsupported - fixed width unicode string - self.assertRaises(TypeError, self.read_csv, path, - dtype={'A': 'U8'}, - index_col=0) + pytest.raises(TypeError, self.read_csv, path, + dtype={'A': 'U8'}, + index_col=0) def test_precise_conversion(self): # see gh-8002 diff --git a/pandas/tests/io/parser/common.py b/pandas/tests/io/parser/common.py index ca60327d7916c..a0c50bb3a573d 100644 --- a/pandas/tests/io/parser/common.py +++ b/pandas/tests/io/parser/common.py @@ -202,8 +202,8 @@ def test_quoting(self): Klosterdruckerei\tKlosterdruckerei (1609-1805)\t"Furststiftische Hofdruckerei, (1609-1805)\tGaller, Alois Klosterdruckerei\tKlosterdruckerei (1609-1805)\tHochfurstliche Buchhandlung """ # noqa - self.assertRaises(Exception, self.read_table, StringIO(bad_line_small), - sep='\t') + pytest.raises(Exception, self.read_table, StringIO(bad_line_small), + sep='\t') good_line_small = bad_line_small + '"' df = self.read_table(StringIO(good_line_small), sep='\t') @@ -290,7 +290,7 @@ def test_read_table_wrong_num_columns(self): 6,7,8,9,10,11,12 11,12,13,14,15,16 """ - self.assertRaises(ValueError, self.read_csv, StringIO(data)) + pytest.raises(ValueError, self.read_csv, StringIO(data)) def test_read_duplicate_index_explicit(self): data = """index,A,B,C,D @@ -440,7 +440,7 @@ def test_read_chunksize_and_nrows(self): tm.assert_frame_equal(reader.get_chunk(size=2), df.iloc[:2]) tm.assert_frame_equal(reader.get_chunk(size=4), df.iloc[2:5]) - with tm.assertRaises(StopIteration): + with pytest.raises(StopIteration): reader.get_chunk(size=3) def test_read_chunksize_named(self): @@ -545,7 +545,7 @@ def test_iterator(self): # test bad parameter (skipfooter) reader = self.read_csv(StringIO(self.data1), index_col=0, iterator=True, skipfooter=1) - self.assertRaises(ValueError, reader.read, 3) + pytest.raises(ValueError, reader.read, 3) def test_pass_names_with_index(self): lines = self.data1.split('\n') @@ -685,7 +685,7 @@ def test_nonexistent_path(self): # gh-2428: pls no segfault # gh-14086: raise more helpful FileNotFoundError path = '%s.csv' % tm.rands(10) - self.assertRaises(compat.FileNotFoundError, self.read_csv, path) + pytest.raises(compat.FileNotFoundError, self.read_csv, path) def test_missing_trailing_delimiters(self): data = """A,B,C,D @@ -874,8 +874,8 @@ def test_catch_too_many_names(self): 4,,6 7,8,9 10,11,12\n""" - tm.assertRaises(ValueError, self.read_csv, StringIO(data), - header=0, names=['a', 'b', 'c', 'd']) + pytest.raises(ValueError, self.read_csv, StringIO(data), + header=0, names=['a', 'b', 'c', 'd']) def test_ignore_leading_whitespace(self): # see gh-3374, gh-6607 @@ -959,8 +959,8 @@ def test_int64_overflow(self): # to cast to either int64 or uint64 will result in # an OverflowError being raised. for conv in (np.int64, np.uint64): - self.assertRaises(OverflowError, self.read_csv, - StringIO(data), converters={'ID': conv}) + pytest.raises(OverflowError, self.read_csv, + StringIO(data), converters={'ID': conv}) # These numbers fall right inside the int64-uint64 range, # so they should be parsed as string. @@ -1080,18 +1080,18 @@ def test_eof_states(self): # ESCAPED_CHAR data = "a,b,c\n4,5,6\n\\" - self.assertRaises(Exception, self.read_csv, - StringIO(data), escapechar='\\') + pytest.raises(Exception, self.read_csv, + StringIO(data), escapechar='\\') # ESCAPE_IN_QUOTED_FIELD data = 'a,b,c\n4,5,6\n"\\' - self.assertRaises(Exception, self.read_csv, - StringIO(data), escapechar='\\') + pytest.raises(Exception, self.read_csv, + StringIO(data), escapechar='\\') # IN_QUOTED_FIELD data = 'a,b,c\n4,5,6\n"' - self.assertRaises(Exception, self.read_csv, - StringIO(data), escapechar='\\') + pytest.raises(Exception, self.read_csv, + StringIO(data), escapechar='\\') def test_uneven_lines_with_usecols(self): # See gh-12203 @@ -1312,8 +1312,8 @@ def test_iteration_open_handle(self): break if self.engine == 'c': - tm.assertRaises(Exception, self.read_table, - f, squeeze=True, header=None) + pytest.raises(Exception, self.read_table, + f, squeeze=True, header=None) else: result = self.read_table(f, squeeze=True, header=None) expected = Series(['DDD', 'EEE', 'FFF', 'GGG'], name=0) @@ -1403,11 +1403,11 @@ def test_inf_parsing(self): def test_raise_on_no_columns(self): # single newline data = "\n" - self.assertRaises(EmptyDataError, self.read_csv, StringIO(data)) + pytest.raises(EmptyDataError, self.read_csv, StringIO(data)) # test with more than a single newline data = "\n\n\n" - self.assertRaises(EmptyDataError, self.read_csv, StringIO(data)) + pytest.raises(EmptyDataError, self.read_csv, StringIO(data)) def test_compact_ints_use_unsigned(self): # see gh-13323 @@ -1695,10 +1695,10 @@ def test_skip_bad_lines(self): # see gh-15925 data = 'a\n1\n1,2,3\n4\n5,6,7' - with tm.assertRaises(ParserError): + with pytest.raises(ParserError): self.read_csv(StringIO(data)) - with tm.assertRaises(ParserError): + with pytest.raises(ParserError): self.read_csv(StringIO(data), error_bad_lines=True) expected = DataFrame({'a': [1, 4]}) diff --git a/pandas/tests/io/parser/compression.py b/pandas/tests/io/parser/compression.py index bdcd10fc64aa5..c7e9401665cdf 100644 --- a/pandas/tests/io/parser/compression.py +++ b/pandas/tests/io/parser/compression.py @@ -60,8 +60,8 @@ def test_zip(self): with tm.ensure_clean() as path: with open(path, 'wb') as f: - self.assertRaises(zipfile.BadZipfile, self.read_csv, - f, compression='zip') + pytest.raises(zipfile.BadZipfile, self.read_csv, + f, compression='zip') def test_gzip(self): try: @@ -110,8 +110,8 @@ def test_bz2(self): result = self.read_csv(path, compression='bz2') tm.assert_frame_equal(result, expected) - self.assertRaises(ValueError, self.read_csv, - path, compression='bz3') + pytest.raises(ValueError, self.read_csv, + path, compression='bz3') with open(path, 'rb') as fin: result = self.read_csv(fin, compression='bz2') diff --git a/pandas/tests/io/parser/dtypes.py b/pandas/tests/io/parser/dtypes.py index 50c9a1bc724fc..6ef2bd8f869dd 100644 --- a/pandas/tests/io/parser/dtypes.py +++ b/pandas/tests/io/parser/dtypes.py @@ -5,6 +5,8 @@ for all of the parsers defined in parsers.py """ +import pytest + import numpy as np import pandas as pd import pandas.util.testing as tm @@ -40,9 +42,9 @@ def test_passing_dtype(self): tm.assert_frame_equal(result, df) # invalid dtype - self.assertRaises(TypeError, self.read_csv, path, - dtype={'A': 'foo', 'B': 'float64'}, - index_col=0) + pytest.raises(TypeError, self.read_csv, path, + dtype={'A': 'foo', 'B': 'float64'}, + index_col=0) # see gh-12048: empty frame actual = self.read_csv(StringIO('A,B'), dtype=str) @@ -213,9 +215,9 @@ def test_raise_on_passed_int_dtype_with_nas(self): 2001,106380451,10 2001,,11 2001,106380451,67""" - self.assertRaises(ValueError, self.read_csv, StringIO(data), - sep=",", skipinitialspace=True, - dtype={'DOY': np.int64}) + pytest.raises(ValueError, self.read_csv, StringIO(data), + sep=",", skipinitialspace=True, + dtype={'DOY': np.int64}) def test_dtype_with_converter(self): data = """a,b diff --git a/pandas/tests/io/parser/header.py b/pandas/tests/io/parser/header.py index a40f14f2a24f8..2f0ca5b311aef 100644 --- a/pandas/tests/io/parser/header.py +++ b/pandas/tests/io/parser/header.py @@ -5,6 +5,8 @@ during parsing for all of the parsers defined in parsers.py """ +import pytest + import numpy as np import pandas.util.testing as tm @@ -30,9 +32,9 @@ def test_bool_header_arg(self): a b""" for arg in [True, False]: - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): self.read_csv(StringIO(data), header=arg) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): self.read_table(StringIO(data), header=arg) def test_no_header_prefix(self): @@ -117,27 +119,27 @@ def test_header_multi_index(self): # no as_recarray with tm.assert_produces_warning( FutureWarning, check_stacklevel=False): - self.assertRaises(ValueError, self.read_csv, - StringIO(data), header=[0, 1, 2, 3], - index_col=[0, 1], as_recarray=True, - tupleize_cols=False) - - # names - self.assertRaises(ValueError, self.read_csv, + pytest.raises(ValueError, self.read_csv, StringIO(data), header=[0, 1, 2, 3], - index_col=[0, 1], names=['foo', 'bar'], + index_col=[0, 1], as_recarray=True, tupleize_cols=False) + # names + pytest.raises(ValueError, self.read_csv, + StringIO(data), header=[0, 1, 2, 3], + index_col=[0, 1], names=['foo', 'bar'], + tupleize_cols=False) + # usecols - self.assertRaises(ValueError, self.read_csv, - StringIO(data), header=[0, 1, 2, 3], - index_col=[0, 1], usecols=['foo', 'bar'], - tupleize_cols=False) + pytest.raises(ValueError, self.read_csv, + StringIO(data), header=[0, 1, 2, 3], + index_col=[0, 1], usecols=['foo', 'bar'], + tupleize_cols=False) # non-numeric index_col - self.assertRaises(ValueError, self.read_csv, - StringIO(data), header=[0, 1, 2, 3], - index_col=['foo', 'bar'], tupleize_cols=False) + pytest.raises(ValueError, self.read_csv, + StringIO(data), header=[0, 1, 2, 3], + index_col=['foo', 'bar'], tupleize_cols=False) def test_header_multiindex_common_format(self): diff --git a/pandas/tests/io/parser/index_col.py b/pandas/tests/io/parser/index_col.py index 6eb15eb3e043c..168f6eda46ed1 100644 --- a/pandas/tests/io/parser/index_col.py +++ b/pandas/tests/io/parser/index_col.py @@ -6,6 +6,8 @@ the parsers defined in parsers.py """ +import pytest + import pandas.util.testing as tm from pandas import DataFrame, Index, MultiIndex @@ -29,8 +31,8 @@ def test_index_col_named(self): xp = self.read_csv(StringIO(data), header=0).set_index('ID') tm.assert_frame_equal(rs, xp) - self.assertRaises(ValueError, self.read_csv, StringIO(no_header), - index_col='ID') + pytest.raises(ValueError, self.read_csv, StringIO(no_header), + index_col='ID') data = """\ 1,2,3,4,hello @@ -51,8 +53,8 @@ def test_index_col_named(self): def test_index_col_is_true(self): # see gh-9798 - self.assertRaises(ValueError, self.read_csv, - StringIO(self.ts_data), index_col=True) + pytest.raises(ValueError, self.read_csv, + StringIO(self.ts_data), index_col=True) def test_infer_index_col(self): data = """A,B,C diff --git a/pandas/tests/io/parser/parse_dates.py b/pandas/tests/io/parser/parse_dates.py index a61a1fb39985f..6dd92783eac60 100644 --- a/pandas/tests/io/parser/parse_dates.py +++ b/pandas/tests/io/parser/parse_dates.py @@ -347,11 +347,11 @@ def test_parse_dates_custom_euroformat(self): tm.assert_frame_equal(df, expected) parser = lambda d: parse_date(d, day_first=True) - self.assertRaises(TypeError, self.read_csv, - StringIO(text), skiprows=[0], - names=['time', 'Q', 'NTU'], index_col=0, - parse_dates=True, date_parser=parser, - na_values=['NA']) + pytest.raises(TypeError, self.read_csv, + StringIO(text), skiprows=[0], + names=['time', 'Q', 'NTU'], index_col=0, + parse_dates=True, date_parser=parser, + na_values=['NA']) def test_parse_tz_aware(self): # See gh-1693 diff --git a/pandas/tests/io/parser/python_parser_only.py b/pandas/tests/io/parser/python_parser_only.py index 55e72ca51790e..c5fa64d067ee6 100644 --- a/pandas/tests/io/parser/python_parser_only.py +++ b/pandas/tests/io/parser/python_parser_only.py @@ -148,8 +148,8 @@ def test_decompression_regex_sep(self): result = self.read_csv(path, sep='::', compression='bz2') tm.assert_frame_equal(result, expected) - self.assertRaises(ValueError, self.read_csv, - path, compression='bz3') + pytest.raises(ValueError, self.read_csv, + path, compression='bz3') def test_read_table_buglet_4x_multiindex(self): # see gh-6607 @@ -213,7 +213,7 @@ def test_multi_char_sep_quotes(self): # We expect no match, so there should be an assertion # error out of the inner context manager. - with tm.assertRaises(AssertionError): + with pytest.raises(AssertionError): with tm.assertRaisesRegexp(ParserError, msg): self.read_csv(StringIO(data), sep=',,', quoting=csv.QUOTE_NONE) @@ -231,6 +231,6 @@ def test_skipfooter_bad_row(self): # We expect no match, so there should be an assertion # error out of the inner context manager. - with tm.assertRaises(AssertionError): + with pytest.raises(AssertionError): with tm.assertRaisesRegexp(ParserError, msg): self.read_csv(StringIO(data)) diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py index 4d6b6c7daa3c6..d084fca976d9c 100644 --- a/pandas/tests/io/parser/test_network.py +++ b/pandas/tests/io/parser/test_network.py @@ -168,10 +168,10 @@ def test_parse_public_s3_bucket_nrows_python(self): @tm.network def test_s3_fails(self): - with tm.assertRaises(IOError): + with pytest.raises(IOError): read_csv('s3://nyqpug/asdf.csv') # Receive a permission error when trying to read a private bucket. # It's irrelevant here that this isn't actually a table. - with tm.assertRaises(IOError): + with pytest.raises(IOError): read_csv('s3://cant_get_it/') diff --git a/pandas/tests/io/parser/test_read_fwf.py b/pandas/tests/io/parser/test_read_fwf.py index dccae06afe4d1..9498a7d83e0de 100644 --- a/pandas/tests/io/parser/test_read_fwf.py +++ b/pandas/tests/io/parser/test_read_fwf.py @@ -243,7 +243,7 @@ def test_bool_header_arg(self): a b""" for arg in [True, False]: - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): read_fwf(StringIO(data), header=arg) def test_full_file(self): @@ -401,5 +401,5 @@ def test_skiprows_inference_empty(self): 78 901 2 """.strip() - with tm.assertRaises(EmptyDataError): + with pytest.raises(EmptyDataError): read_fwf(StringIO(test), skiprows=3) diff --git a/pandas/tests/io/parser/test_textreader.py b/pandas/tests/io/parser/test_textreader.py index b6b6508bab13c..bf1d8d4f3e27c 100644 --- a/pandas/tests/io/parser/test_textreader.py +++ b/pandas/tests/io/parser/test_textreader.py @@ -5,6 +5,8 @@ is integral to the C engine in parsers.py """ +import pytest + from pandas.compat import StringIO, BytesIO, map from pandas import compat @@ -152,7 +154,7 @@ def test_skip_bad_lines(self): reader = TextReader(StringIO(data), delimiter=':', header=None) - self.assertRaises(parser.ParserError, reader.read) + pytest.raises(parser.ParserError, reader.read) reader = TextReader(StringIO(data), delimiter=':', header=None, @@ -191,8 +193,8 @@ def test_header_not_enough_lines(self): assert_array_dicts_equal(expected, recs) # not enough rows - self.assertRaises(parser.ParserError, TextReader, StringIO(data), - delimiter=',', header=5, as_recarray=True) + pytest.raises(parser.ParserError, TextReader, StringIO(data), + delimiter=',', header=5, as_recarray=True) def test_header_not_enough_lines_as_recarray(self): data = ('skip this\n' @@ -212,8 +214,8 @@ def test_header_not_enough_lines_as_recarray(self): assert_array_dicts_equal(expected, recs) # not enough rows - self.assertRaises(parser.ParserError, TextReader, StringIO(data), - delimiter=',', header=5, as_recarray=True) + pytest.raises(parser.ParserError, TextReader, StringIO(data), + delimiter=',', header=5, as_recarray=True) def test_escapechar(self): data = ('\\"hello world\"\n' diff --git a/pandas/tests/io/parser/usecols.py b/pandas/tests/io/parser/usecols.py index 0cf642983e8d3..1ea7353427c30 100644 --- a/pandas/tests/io/parser/usecols.py +++ b/pandas/tests/io/parser/usecols.py @@ -82,8 +82,8 @@ def test_usecols(self): tm.assert_frame_equal(result, expected) # length conflict, passed names and usecols disagree - self.assertRaises(ValueError, self.read_csv, StringIO(data), - names=['a', 'b'], usecols=[1], header=None) + pytest.raises(ValueError, self.read_csv, StringIO(data), + names=['a', 'b'], usecols=[1], header=None) def test_usecols_index_col_False(self): # see gh-9082 diff --git a/pandas/tests/io/sas/test_sas.py b/pandas/tests/io/sas/test_sas.py index 237e3676c3b3d..461c0fe1fd848 100644 --- a/pandas/tests/io/sas/test_sas.py +++ b/pandas/tests/io/sas/test_sas.py @@ -1,3 +1,5 @@ +import pytest + import pandas.util.testing as tm from pandas.compat import StringIO from pandas import read_sas @@ -9,5 +11,5 @@ def test_sas_buffer_format(self): # GH14947 b = StringIO("") - with self.assertRaises(ValueError): + with pytest.raises(ValueError): read_sas(b) diff --git a/pandas/tests/io/test_clipboard.py b/pandas/tests/io/test_clipboard.py index 2e701143357e3..f373c13c3bc58 100644 --- a/pandas/tests/io/test_clipboard.py +++ b/pandas/tests/io/test_clipboard.py @@ -127,9 +127,9 @@ def test_read_clipboard_infer_excel(self): def test_invalid_encoding(self): # test case for testing invalid encoding data = self.data['string'] - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): data.to_clipboard(encoding='ascii') - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): pd.read_clipboard(encoding='ascii') def test_round_trip_valid_encodings(self): diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index c08d235b07c9e..fd29caefb8cb5 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -2,6 +2,7 @@ Tests for the pandas.io.common functionalities """ import mmap +import pytest import os from os.path import isabs @@ -138,4 +139,4 @@ def test_next(self): next_line = next(wrapper) self.assertEqual(next_line.strip(), line.strip()) - self.assertRaises(StopIteration, next, wrapper) + pytest.raises(StopIteration, next, wrapper) diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py index cbfffd785ca0d..02652be2153f1 100644 --- a/pandas/tests/io/test_excel.py +++ b/pandas/tests/io/test_excel.py @@ -287,7 +287,7 @@ def test_excel_table_sheet_by_index(self): tm.assert_frame_equal(df3, df4) import xlrd - with tm.assertRaises(xlrd.XLRDError): + with pytest.raises(xlrd.XLRDError): read_excel(excel, 'asdf') def test_excel_table(self): @@ -399,7 +399,7 @@ def test_reader_dtype(self): expected['c'] = ['001', '002', '003', '004'] tm.assert_frame_equal(actual, expected) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): actual = self.get_exceldf(basename, dtype={'d': 'int64'}) def test_reading_all_sheets(self): @@ -915,13 +915,13 @@ def test_excel_oldindex_format(self): def test_read_excel_bool_header_arg(self): # GH 6114 for arg in [True, False]: - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): pd.read_excel(os.path.join(self.dirpath, 'test1' + self.ext), header=arg) def test_read_excel_chunksize(self): # GH 8011 - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): pd.read_excel(os.path.join(self.dirpath, 'test1' + self.ext), chunksize=100) @@ -1040,7 +1040,7 @@ def test_excel_sheet_by_name_raise(self): df = read_excel(xl, 0) tm.assert_frame_equal(gt, df) - with tm.assertRaises(xlrd.XLRDError): + with pytest.raises(xlrd.XLRDError): read_excel(xl, '0') def test_excelwriter_contextmanager(self): @@ -1675,7 +1675,7 @@ def roundtrip(df, header=True, parser_hdr=0, index=True): # this if will be removed once multi column excel writing # is implemented for now fixing #9794 if j > 1: - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): res = roundtrip(df, use_headers, index=False) else: res = roundtrip(df, use_headers) @@ -1725,7 +1725,7 @@ def roundtrip2(df, header=True, parser_hdr=0, index=True): j = 2 i = 1 df = mkdf(nrows, ncols, r_idx_nlevels=i, c_idx_nlevels=j) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): roundtrip2(df, header=False, index=False) def test_duplicated_columns(self): @@ -1784,7 +1784,7 @@ def test_invalid_columns(self): read_frame = read_excel(path, 'test1') tm.assert_frame_equal(expected, read_frame) - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): write_frame.to_excel(path, 'test1', columns=['C', 'D']) def test_datetimes(self): @@ -2164,7 +2164,7 @@ def test_excel_raise_error_on_multiindex_columns_and_no_index(self): ('2014', 'height'), ('2014', 'weight')]) df = DataFrame(np.random.randn(10, 3), columns=cols) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): with ensure_clean(self.ext) as path: df.to_excel(path, index=False) diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index 0d061d516af28..866ed2cf2f359 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -278,13 +278,13 @@ def test_file_like(self): @network def test_bad_url_protocol(self): - with tm.assertRaises(URLError): + with pytest.raises(URLError): self.read_html('git://github.com', match='.*Water.*') @network def test_invalid_url(self): try: - with tm.assertRaises(URLError): + with pytest.raises(URLError): self.read_html('http://www.a23950sdfa908sd.com', match='.*Water.*') except ValueError as e: @@ -691,7 +691,7 @@ def test_decimal_rows(self): def test_bool_header_arg(self): # GH 6114 for arg in [True, False]: - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): read_html(self.spam_data, header=arg) def test_converters(self): @@ -842,10 +842,10 @@ def test_data_fail(self): spam_data = os.path.join(DATA_PATH, 'spam.html') banklist_data = os.path.join(DATA_PATH, 'banklist.html') - with tm.assertRaises(XMLSyntaxError): + with pytest.raises(XMLSyntaxError): self.read_html(spam_data) - with tm.assertRaises(XMLSyntaxError): + with pytest.raises(XMLSyntaxError): self.read_html(banklist_data) def test_works_on_valid_markup(self): @@ -884,7 +884,7 @@ def test_computer_sales_page(self): def test_invalid_flavor(): url = 'google.com' - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): read_html(url, 'google', flavor='not a* valid**++ flaver') diff --git a/pandas/tests/io/test_packers.py b/pandas/tests/io/test_packers.py index 329748eb5be33..ca6d0605c193b 100644 --- a/pandas/tests/io/test_packers.py +++ b/pandas/tests/io/test_packers.py @@ -148,9 +148,9 @@ class A(object): def __init__(self): self.read = 0 - tm.assertRaises(ValueError, read_msgpack, path_or_buf=None) - tm.assertRaises(ValueError, read_msgpack, path_or_buf={}) - tm.assertRaises(ValueError, read_msgpack, path_or_buf=A()) + pytest.raises(ValueError, read_msgpack, path_or_buf=None) + pytest.raises(ValueError, read_msgpack, path_or_buf={}) + pytest.raises(ValueError, read_msgpack, path_or_buf=A()) class TestNumpy(TestPackers): @@ -536,7 +536,7 @@ def _check_roundtrip(self, obj, comparator, **kwargs): # currently these are not implemetned # i_rec = self.encode_decode(obj) # comparator(obj, i_rec, **kwargs) - self.assertRaises(NotImplementedError, self.encode_decode, obj) + pytest.raises(NotImplementedError, self.encode_decode, obj) def test_sparse_series(self): diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index 1287686874a58..153ac749b4b17 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -308,20 +308,20 @@ def test_api(self): # invalid df = tm.makeDataFrame() - self.assertRaises(ValueError, df.to_hdf, path, - 'df', append=True, format='f') - self.assertRaises(ValueError, df.to_hdf, path, - 'df', append=True, format='fixed') + pytest.raises(ValueError, df.to_hdf, path, + 'df', append=True, format='f') + pytest.raises(ValueError, df.to_hdf, path, + 'df', append=True, format='fixed') - self.assertRaises(TypeError, df.to_hdf, path, - 'df', append=True, format='foo') - self.assertRaises(TypeError, df.to_hdf, path, - 'df', append=False, format='bar') + pytest.raises(TypeError, df.to_hdf, path, + 'df', append=True, format='foo') + pytest.raises(TypeError, df.to_hdf, path, + 'df', append=False, format='bar') # File path doesn't exist path = "" - self.assertRaises(compat.FileNotFoundError, - read_hdf, path, 'df') + pytest.raises(compat.FileNotFoundError, + read_hdf, path, 'df') def test_api_default_format(self): @@ -333,7 +333,7 @@ def test_api_default_format(self): _maybe_remove(store, 'df') store.put('df', df) self.assertFalse(store.get_storer('df').is_table) - self.assertRaises(ValueError, store.append, 'df2', df) + pytest.raises(ValueError, store.append, 'df2', df) pandas.set_option('io.hdf.default_format', 'table') _maybe_remove(store, 'df') @@ -353,7 +353,7 @@ def test_api_default_format(self): df.to_hdf(path, 'df') with HDFStore(path) as store: self.assertFalse(store.get_storer('df').is_table) - self.assertRaises(ValueError, df.to_hdf, path, 'df2', append=True) + pytest.raises(ValueError, df.to_hdf, path, 'df2', append=True) pandas.set_option('io.hdf.default_format', 'table') df.to_hdf(path, 'df3') @@ -473,7 +473,7 @@ def test_versioning(self): # this is an error because its table_type is appendable, but no # version info store.get_node('df2')._v_attrs.pandas_version = None - self.assertRaises(Exception, store.select, 'df2') + pytest.raises(Exception, store.select, 'df2') def test_mode(self): @@ -485,7 +485,7 @@ def check(mode): # constructor if mode in ['r', 'r+']: - self.assertRaises(IOError, HDFStore, path, mode=mode) + pytest.raises(IOError, HDFStore, path, mode=mode) else: store = HDFStore(path, mode=mode) @@ -499,7 +499,7 @@ def check(mode): def f(): with HDFStore(path, mode=mode) as store: # noqa pass - self.assertRaises(IOError, f) + pytest.raises(IOError, f) else: with HDFStore(path, mode=mode) as store: self.assertEqual(store._handle.mode, mode) @@ -508,16 +508,16 @@ def f(): # conv write if mode in ['r', 'r+']: - self.assertRaises(IOError, df.to_hdf, - path, 'df', mode=mode) + pytest.raises(IOError, df.to_hdf, + path, 'df', mode=mode) df.to_hdf(path, 'df', mode='w') else: df.to_hdf(path, 'df', mode=mode) # conv read if mode in ['w']: - self.assertRaises(ValueError, read_hdf, - path, 'df', mode=mode) + pytest.raises(ValueError, read_hdf, + path, 'df', mode=mode) else: result = read_hdf(path, 'df', mode=mode) assert_frame_equal(result, df) @@ -544,7 +544,7 @@ def test_reopen_handle(self): store['a'] = tm.makeTimeSeries() # invalid mode change - self.assertRaises(PossibleDataLossError, store.open, 'w') + pytest.raises(PossibleDataLossError, store.open, 'w') store.close() self.assertFalse(store.is_open) @@ -621,7 +621,7 @@ def test_get(self): right = store['/a'] tm.assert_series_equal(left, right) - self.assertRaises(KeyError, store.get, 'b') + pytest.raises(KeyError, store.get, 'b') def test_getattr(self): @@ -642,10 +642,10 @@ def test_getattr(self): tm.assert_frame_equal(result, df) # errors - self.assertRaises(AttributeError, getattr, store, 'd') + pytest.raises(AttributeError, getattr, store, 'd') for x in ['mode', 'path', 'handle', 'complib']: - self.assertRaises(AttributeError, getattr, store, x) + pytest.raises(AttributeError, getattr, store, x) # not stores for x in ['mode', 'path', 'handle', 'complib']: @@ -665,17 +665,17 @@ def test_put(self): store.put('c', df[:10], format='table') # not OK, not a table - self.assertRaises( + pytest.raises( ValueError, store.put, 'b', df[10:], append=True) # node does not currently exist, test _is_table_type returns False # in this case # _maybe_remove(store, 'f') - # self.assertRaises(ValueError, store.put, 'f', df[10:], + # pytest.raises(ValueError, store.put, 'f', df[10:], # append=True) # can't put to a table (use append instead) - self.assertRaises(ValueError, store.put, 'c', df[10:], append=True) + pytest.raises(ValueError, store.put, 'c', df[10:], append=True) # overwrite table store.put('c', df[:10], format='table', append=False) @@ -717,8 +717,8 @@ def test_put_compression(self): tm.assert_frame_equal(store['c'], df) # can't compress if format='fixed' - self.assertRaises(ValueError, store.put, 'b', df, - format='fixed', complib='zlib') + pytest.raises(ValueError, store.put, 'b', df, + format='fixed', complib='zlib') def test_put_compression_blosc(self): tm.skip_if_no_package('tables', min_version='2.2', @@ -731,8 +731,8 @@ def test_put_compression_blosc(self): with ensure_clean_store(self.path) as store: # can't compress if format='fixed' - self.assertRaises(ValueError, store.put, 'b', df, - format='fixed', complib='blosc') + pytest.raises(ValueError, store.put, 'b', df, + format='fixed', complib='blosc') store.put('c', df, format='table', complib='blosc') tm.assert_frame_equal(store['c'], df) @@ -946,7 +946,7 @@ def check(format, index): else: # only support for fixed types (and they have a perf warning) - self.assertRaises(TypeError, check, 'table', index) + pytest.raises(TypeError, check, 'table', index) # PerformanceWarning with catch_warnings(record=True): @@ -1216,11 +1216,11 @@ def test_append_with_different_block_ordering(self): # store additonal fields in different blocks df['int16_2'] = Series([1] * len(df), dtype='int16') - self.assertRaises(ValueError, store.append, 'df', df) + pytest.raises(ValueError, store.append, 'df', df) # store multile additonal fields in different blocks df['float_3'] = Series([1.] * len(df), dtype='float64') - self.assertRaises(ValueError, store.append, 'df', df) + pytest.raises(ValueError, store.append, 'df', df) def test_ndim_indexables(self): # test using ndim tables in new ways @@ -1254,7 +1254,7 @@ def check_indexers(key, indexers): # pass incorrect number of axes _maybe_remove(store, 'p4d') - self.assertRaises(ValueError, store.append, 'p4d', p4d.iloc[ + pytest.raises(ValueError, store.append, 'p4d', p4d.iloc[ :, :, :10, :], axes=['major_axis', 'minor_axis']) # different than default indexables #1 @@ -1323,11 +1323,11 @@ def check_col(key, name, size): # apply the wrong field (similar to #1) store.append('s3', wp, min_itemsize={'major_axis': 20}) - self.assertRaises(ValueError, store.append, 's3', wp2) + pytest.raises(ValueError, store.append, 's3', wp2) # test truncation of bigger strings store.append('s4', wp) - self.assertRaises(ValueError, store.append, 's4', wp2) + pytest.raises(ValueError, store.append, 's4', wp2) # avoid truncation on elements df = DataFrame([[123, 'asdqwerty'], [345, 'dggnhebbsdfbdfb']]) @@ -1352,7 +1352,7 @@ def check_col(key, name, size): store.append('df_new', df) df_new = DataFrame( [[124, 'abcdefqhij'], [346, 'abcdefghijklmnopqrtsuvwxyz']]) - self.assertRaises(ValueError, store.append, 'df_new', df_new) + pytest.raises(ValueError, store.append, 'df_new', df_new) # min_itemsize on Series index (GH 11412) df = tm.makeMixedDataFrame().set_index('C') @@ -1431,8 +1431,8 @@ def check_col(key, name, size): df = DataFrame(['foo', 'foo', 'foo', 'barh', 'barh', 'barh'], columns=['A']) _maybe_remove(store, 'df') - self.assertRaises(ValueError, store.append, 'df', - df, min_itemsize={'foo': 20, 'foobar': 20}) + pytest.raises(ValueError, store.append, 'df', + df, min_itemsize={'foo': 20, 'foobar': 20}) def test_to_hdf_with_min_itemsize(self): @@ -1690,7 +1690,7 @@ def col(t, column): # try to index a non-table _maybe_remove(store, 'f2') store.put('f2', df) - self.assertRaises(TypeError, store.create_table_index, 'f2') + pytest.raises(TypeError, store.create_table_index, 'f2') def test_append_diff_item_order(self): @@ -1702,8 +1702,8 @@ def test_append_diff_item_order(self): with ensure_clean_store(self.path) as store: store.put('panel', wp1, format='table') - self.assertRaises(ValueError, store.put, 'panel', wp2, - append=True) + pytest.raises(ValueError, store.put, 'panel', wp2, + append=True) def test_append_hierarchical(self): index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'], @@ -1754,10 +1754,10 @@ def test_column_multiindex(self): check_index_type=True, check_column_type=True) - self.assertRaises(ValueError, store.put, 'df2', df, - format='table', data_columns=['A']) - self.assertRaises(ValueError, store.put, 'df3', df, - format='table', data_columns=True) + pytest.raises(ValueError, store.put, 'df2', df, + format='table', data_columns=['A']) + pytest.raises(ValueError, store.put, 'df3', df, + format='table', data_columns=True) # appending multi-column on existing table (see GH 6167) with ensure_clean_store(self.path) as store: @@ -1820,13 +1820,13 @@ def make_index(names=None): _maybe_remove(store, 'df') df = DataFrame(np.zeros((12, 2)), columns=[ 'a', 'b'], index=make_index(['date', 'a', 't'])) - self.assertRaises(ValueError, store.append, 'df', df) + pytest.raises(ValueError, store.append, 'df', df) # dup within level _maybe_remove(store, 'df') df = DataFrame(np.zeros((12, 2)), columns=['a', 'b'], index=make_index(['date', 'date', 'date'])) - self.assertRaises(ValueError, store.append, 'df', df) + pytest.raises(ValueError, store.append, 'df', df) # fully names _maybe_remove(store, 'df') @@ -1885,9 +1885,9 @@ def test_pass_spec_to_storer(self): with ensure_clean_store(self.path) as store: store.put('df', df) - self.assertRaises(TypeError, store.select, 'df', columns=['A']) - self.assertRaises(TypeError, store.select, - 'df', where=[('columns=A')]) + pytest.raises(TypeError, store.select, 'df', columns=['A']) + pytest.raises(TypeError, store.select, + 'df', where=[('columns=A')]) def test_append_misc(self): @@ -1897,13 +1897,13 @@ def test_append_misc(self): # unsuported data types for non-tables p4d = tm.makePanel4D() - self.assertRaises(TypeError, store.put, 'p4d', p4d) + pytest.raises(TypeError, store.put, 'p4d', p4d) # unsuported data types - self.assertRaises(TypeError, store.put, 'abc', None) - self.assertRaises(TypeError, store.put, 'abc', '123') - self.assertRaises(TypeError, store.put, 'abc', 123) - self.assertRaises(TypeError, store.put, 'abc', np.arange(5)) + pytest.raises(TypeError, store.put, 'abc', None) + pytest.raises(TypeError, store.put, 'abc', '123') + pytest.raises(TypeError, store.put, 'abc', 123) + pytest.raises(TypeError, store.put, 'abc', np.arange(5)) df = tm.makeDataFrame() store.append('df', df, chunksize=1) @@ -1945,7 +1945,7 @@ def check(obj, comparator): # 0 len df_empty = DataFrame(columns=list('ABC')) store.append('df', df_empty) - self.assertRaises(KeyError, store.select, 'df') + pytest.raises(KeyError, store.select, 'df') # repeated append of 0/non-zero frames df = DataFrame(np.random.rand(10, 3), columns=list('ABC')) @@ -1964,7 +1964,7 @@ def check(obj, comparator): # 0 len p_empty = Panel(items=list('ABC')) store.append('p', p_empty) - self.assertRaises(KeyError, store.select, 'p') + pytest.raises(KeyError, store.select, 'p') # repeated append of 0/non-zero frames p = Panel(np.random.randn(3, 4, 5), items=list('ABC')) @@ -1987,12 +1987,12 @@ def test_append_raise(self): df = tm.makeDataFrame() df['invalid'] = [['a']] * len(df) self.assertEqual(df.dtypes['invalid'], np.object_) - self.assertRaises(TypeError, store.append, 'df', df) + pytest.raises(TypeError, store.append, 'df', df) # multiple invalid columns df['invalid2'] = [['a']] * len(df) df['invalid3'] = [['a']] * len(df) - self.assertRaises(TypeError, store.append, 'df', df) + pytest.raises(TypeError, store.append, 'df', df) # datetime with embedded nans as object df = tm.makeDataFrame() @@ -2001,21 +2001,21 @@ def test_append_raise(self): s[0:5] = np.nan df['invalid'] = s self.assertEqual(df.dtypes['invalid'], np.object_) - self.assertRaises(TypeError, store.append, 'df', df) + pytest.raises(TypeError, store.append, 'df', df) # directy ndarray - self.assertRaises(TypeError, store.append, 'df', np.arange(10)) + pytest.raises(TypeError, store.append, 'df', np.arange(10)) # series directly - self.assertRaises(TypeError, store.append, - 'df', Series(np.arange(10))) + pytest.raises(TypeError, store.append, + 'df', Series(np.arange(10))) # appending an incompatible table df = tm.makeDataFrame() store.append('df', df) df['foo'] = 'foo' - self.assertRaises(ValueError, store.append, 'df', df) + pytest.raises(ValueError, store.append, 'df', df) def test_table_index_incompatible_dtypes(self): df1 = DataFrame({'a': [1, 2, 3]}) @@ -2024,8 +2024,8 @@ def test_table_index_incompatible_dtypes(self): with ensure_clean_store(self.path) as store: store.put('frame', df1, format='table') - self.assertRaises(TypeError, store.put, 'frame', df2, - format='table', append=True) + pytest.raises(TypeError, store.put, 'frame', df2, + format='table', append=True) def test_table_values_dtypes_roundtrip(self): @@ -2039,7 +2039,7 @@ def test_table_values_dtypes_roundtrip(self): assert_series_equal(df2.dtypes, store['df_i8'].dtypes) # incompatible dtype - self.assertRaises(ValueError, store.append, 'df_i8', df1) + pytest.raises(ValueError, store.append, 'df_i8', df1) # check creation/storage/retrieval of float32 (a bit hacky to # actually create them thought) @@ -2138,7 +2138,7 @@ def test_unimplemented_dtypes_table_columns(self): for n, f in l: df = tm.makeDataFrame() df[n] = f - self.assertRaises( + pytest.raises( TypeError, store.append, 'df1_%s' % n, df) # frame @@ -2150,7 +2150,7 @@ def test_unimplemented_dtypes_table_columns(self): with ensure_clean_store(self.path) as store: # this fails because we have a date in the object block...... - self.assertRaises(TypeError, store.append, 'df_unimplemented', df) + pytest.raises(TypeError, store.append, 'df_unimplemented', df) def test_calendar_roundtrip_issue(self): @@ -2235,7 +2235,7 @@ def test_remove(self): self.assertEqual(len(store), 0) # nonexistence - self.assertRaises(KeyError, store.remove, 'a_nonexistent_store') + pytest.raises(KeyError, store.remove, 'a_nonexistent_store') # pathing store['a'] = ts @@ -2264,7 +2264,7 @@ def test_remove_where(self): # non-existance crit1 = 'index>foo' - self.assertRaises(KeyError, store.remove, 'a', [crit1]) + pytest.raises(KeyError, store.remove, 'a', [crit1]) # try to remove non-table (with crit) # non-table ok (where = None) @@ -2286,8 +2286,8 @@ def test_remove_where(self): # non - empty where _maybe_remove(store, 'wp') store.put('wp', wp, format='table') - self.assertRaises(ValueError, store.remove, - 'wp', ['foo']) + pytest.raises(ValueError, store.remove, + 'wp', ['foo']) def test_remove_startstop(self): # GH #4835 and #6177 @@ -2460,19 +2460,19 @@ def test_invalid_terms(self): store.put('p4d', p4d, format='table') # some invalid terms - self.assertRaises(ValueError, store.select, - 'wp', "minor=['A', 'B']") - self.assertRaises(ValueError, store.select, - 'wp', ["index=['20121114']"]) - self.assertRaises(ValueError, store.select, 'wp', [ + pytest.raises(ValueError, store.select, + 'wp', "minor=['A', 'B']") + pytest.raises(ValueError, store.select, + 'wp', ["index=['20121114']"]) + pytest.raises(ValueError, store.select, 'wp', [ "index=['20121114', '20121114']"]) - self.assertRaises(TypeError, Term) + pytest.raises(TypeError, Term) # more invalid - self.assertRaises( + pytest.raises( ValueError, store.select, 'df', 'df.index[3]') - self.assertRaises(SyntaxError, store.select, 'df', 'index>') - self.assertRaises( + pytest.raises(SyntaxError, store.select, 'df', 'index>') + pytest.raises( ValueError, store.select, 'wp', "major_axis<'20000108' & minor_axis['A', 'B']") @@ -2493,8 +2493,8 @@ def test_invalid_terms(self): 'ABCD'), index=date_range('20130101', periods=10)) dfq.to_hdf(path, 'dfq', format='table') - self.assertRaises(ValueError, read_hdf, path, - 'dfq', where="A>0 or C>0") + pytest.raises(ValueError, read_hdf, path, + 'dfq', where="A>0 or C>0") def test_terms(self): @@ -3097,7 +3097,7 @@ def test_select(self): assert_panel_equal(expected, result) # selectin non-table with a where - # self.assertRaises(ValueError, store.select, + # pytest.raises(ValueError, store.select, # 'wp2', ('column', ['A', 'D'])) # select with columns= @@ -3318,10 +3318,10 @@ def test_select_iterator(self): df = tm.makeTimeDataFrame(500) df.to_hdf(path, 'df_non_table') - self.assertRaises(TypeError, read_hdf, path, - 'df_non_table', chunksize=100) - self.assertRaises(TypeError, read_hdf, path, - 'df_non_table', iterator=True) + pytest.raises(TypeError, read_hdf, path, + 'df_non_table', chunksize=100) + pytest.raises(TypeError, read_hdf, path, + 'df_non_table', iterator=True) with ensure_clean_path(self.path) as path: @@ -3671,12 +3671,12 @@ def test_frame_select(self): # invalid terms df = tm.makeTimeDataFrame() store.append('df_time', df) - self.assertRaises( + pytest.raises( ValueError, store.select, 'df_time', "index>0") # can't select if not written as table # store['frame'] = df - # self.assertRaises(ValueError, store.select, + # pytest.raises(ValueError, store.select, # 'frame', [crit1, crit2]) def test_frame_select_complex(self): @@ -3715,8 +3715,8 @@ def test_frame_select_complex(self): tm.assert_frame_equal(result, expected) # invert not implemented in numexpr :( - self.assertRaises(NotImplementedError, - store.select, 'df', '~(string="bar")') + pytest.raises(NotImplementedError, + store.select, 'df', '~(string="bar")') # invert ok for filters result = store.select('df', "~(columns=['A','B'])") @@ -3804,12 +3804,12 @@ def test_invalid_filtering(self): store.put('df', df, format='table') # not implemented - self.assertRaises(NotImplementedError, store.select, - 'df', "columns=['A'] | columns=['B']") + pytest.raises(NotImplementedError, store.select, + 'df', "columns=['A'] | columns=['B']") # in theory we could deal with this - self.assertRaises(NotImplementedError, store.select, - 'df', "columns=['A','B'] & columns=['C']") + pytest.raises(NotImplementedError, store.select, + 'df', "columns=['A','B'] & columns=['C']") def test_string_select(self): # GH 2973 @@ -3867,11 +3867,11 @@ def test_read_column(self): store.append('df', df) # error - self.assertRaises(KeyError, store.select_column, 'df', 'foo') + pytest.raises(KeyError, store.select_column, 'df', 'foo') def f(): store.select_column('df', 'index', where=['index>5']) - self.assertRaises(Exception, f) + pytest.raises(Exception, f) # valid result = store.select_column('df', 'index') @@ -3879,7 +3879,7 @@ def f(): assert isinstance(result, Series) # not a data indexable column - self.assertRaises( + pytest.raises( ValueError, store.select_column, 'df', 'values_block_0') # a data column @@ -3989,14 +3989,14 @@ def test_coordinates(self): tm.assert_frame_equal(result, expected) # invalid - self.assertRaises(ValueError, store.select, 'df', - where=np.arange(len(df), dtype='float64')) - self.assertRaises(ValueError, store.select, 'df', - where=np.arange(len(df) + 1)) - self.assertRaises(ValueError, store.select, 'df', - where=np.arange(len(df)), start=5) - self.assertRaises(ValueError, store.select, 'df', - where=np.arange(len(df)), start=5, stop=10) + pytest.raises(ValueError, store.select, 'df', + where=np.arange(len(df), dtype='float64')) + pytest.raises(ValueError, store.select, 'df', + where=np.arange(len(df) + 1)) + pytest.raises(ValueError, store.select, 'df', + where=np.arange(len(df)), start=5) + pytest.raises(ValueError, store.select, 'df', + where=np.arange(len(df)), start=5, stop=10) # selection with filter selection = date_range('20000101', periods=500) @@ -4032,12 +4032,12 @@ def test_append_to_multiple(self): with ensure_clean_store(self.path) as store: # exceptions - self.assertRaises(ValueError, store.append_to_multiple, - {'df1': ['A', 'B'], 'df2': None}, df, - selector='df3') - self.assertRaises(ValueError, store.append_to_multiple, - {'df1': None, 'df2': None}, df, selector='df3') - self.assertRaises( + pytest.raises(ValueError, store.append_to_multiple, + {'df1': ['A', 'B'], 'df2': None}, df, + selector='df3') + pytest.raises(ValueError, store.append_to_multiple, + {'df1': None, 'df2': None}, df, selector='df3') + pytest.raises( ValueError, store.append_to_multiple, 'df1', df, 'df1') # regular operation @@ -4097,25 +4097,25 @@ def test_select_as_multiple(self): with ensure_clean_store(self.path) as store: # no tables stored - self.assertRaises(Exception, store.select_as_multiple, - None, where=['A>0', 'B>0'], selector='df1') + pytest.raises(Exception, store.select_as_multiple, + None, where=['A>0', 'B>0'], selector='df1') store.append('df1', df1, data_columns=['A', 'B']) store.append('df2', df2) # exceptions - self.assertRaises(Exception, store.select_as_multiple, - None, where=['A>0', 'B>0'], selector='df1') - self.assertRaises(Exception, store.select_as_multiple, - [None], where=['A>0', 'B>0'], selector='df1') - self.assertRaises(KeyError, store.select_as_multiple, - ['df1', 'df3'], where=['A>0', 'B>0'], - selector='df1') - self.assertRaises(KeyError, store.select_as_multiple, - ['df3'], where=['A>0', 'B>0'], selector='df1') - self.assertRaises(KeyError, store.select_as_multiple, - ['df1', 'df2'], where=['A>0', 'B>0'], - selector='df4') + pytest.raises(Exception, store.select_as_multiple, + None, where=['A>0', 'B>0'], selector='df1') + pytest.raises(Exception, store.select_as_multiple, + [None], where=['A>0', 'B>0'], selector='df1') + pytest.raises(KeyError, store.select_as_multiple, + ['df1', 'df3'], where=['A>0', 'B>0'], + selector='df1') + pytest.raises(KeyError, store.select_as_multiple, + ['df3'], where=['A>0', 'B>0'], selector='df1') + pytest.raises(KeyError, store.select_as_multiple, + ['df1', 'df2'], where=['A>0', 'B>0'], + selector='df4') # default select result = store.select('df1', ['A>0', 'B>0']) @@ -4142,9 +4142,9 @@ def test_select_as_multiple(self): # test excpection for diff rows store.append('df3', tm.makeTimeDataFrame(nper=50)) - self.assertRaises(ValueError, store.select_as_multiple, - ['df1', 'df3'], where=['A>0', 'B>0'], - selector='df1') + pytest.raises(ValueError, store.select_as_multiple, + ['df1', 'df3'], where=['A>0', 'B>0'], + selector='df1') def test_nan_selection_bug_4858(self): @@ -4231,7 +4231,7 @@ def test_start_stop_fixed(self): df.iloc[8:10, -2] = np.nan dfs = df.to_sparse() store.put('dfs', dfs) - with self.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): store.select('dfs', start=0, stop=5) def test_select_filter_corner(self): @@ -4312,7 +4312,7 @@ def test_multiple_open_close(self): def f(): HDFStore(path) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) store1.close() else: @@ -4374,17 +4374,17 @@ def f(): store = HDFStore(path) store.close() - self.assertRaises(ClosedFileError, store.keys) - self.assertRaises(ClosedFileError, lambda: 'df' in store) - self.assertRaises(ClosedFileError, lambda: len(store)) - self.assertRaises(ClosedFileError, lambda: store['df']) - self.assertRaises(ClosedFileError, lambda: store.df) - self.assertRaises(ClosedFileError, store.select, 'df') - self.assertRaises(ClosedFileError, store.get, 'df') - self.assertRaises(ClosedFileError, store.append, 'df2', df) - self.assertRaises(ClosedFileError, store.put, 'df3', df) - self.assertRaises(ClosedFileError, store.get_storer, 'df2') - self.assertRaises(ClosedFileError, store.remove, 'df2') + pytest.raises(ClosedFileError, store.keys) + pytest.raises(ClosedFileError, lambda: 'df' in store) + pytest.raises(ClosedFileError, lambda: len(store)) + pytest.raises(ClosedFileError, lambda: store['df']) + pytest.raises(ClosedFileError, lambda: store.df) + pytest.raises(ClosedFileError, store.select, 'df') + pytest.raises(ClosedFileError, store.get, 'df') + pytest.raises(ClosedFileError, store.append, 'df2', df) + pytest.raises(ClosedFileError, store.put, 'df3', df) + pytest.raises(ClosedFileError, store.get_storer, 'df2') + pytest.raises(ClosedFileError, store.remove, 'df2') def f(): store.select('df') @@ -4425,7 +4425,7 @@ def test_legacy_table_read(self): store.select('df2', typ='legacy_frame') # old version warning - self.assertRaises( + pytest.raises( Exception, store.select, 'wp1', 'minor_axis=B') df2 = store.select('df2') @@ -4636,7 +4636,7 @@ def test_store_datetime_mixed(self): # index=[np.arange(5).repeat(2), # np.tile(np.arange(2), 5)]) - # self.assertRaises(Exception, store.put, 'foo', df, format='table') + # pytest.raises(Exception, store.put, 'foo', df, format='table') def test_append_with_diff_col_name_types_raises_value_error(self): df = DataFrame(np.random.randn(10, 1)) @@ -4650,7 +4650,7 @@ def test_append_with_diff_col_name_types_raises_value_error(self): store.append(name, df) for d in (df2, df3, df4, df5): - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): store.append(name, d) def test_query_with_nested_special_character(self): @@ -4795,8 +4795,8 @@ def test_duplicate_column_name(self): df = DataFrame(columns=["a", "a"], data=[[0, 0]]) with ensure_clean_path(self.path) as path: - self.assertRaises(ValueError, df.to_hdf, - path, 'df', format='fixed') + pytest.raises(ValueError, df.to_hdf, + path, 'df', format='fixed') df.to_hdf(path, 'df', format='table') other = read_hdf(path, 'df') @@ -4871,7 +4871,7 @@ def test_to_hdf_with_object_column_names(self): df = DataFrame(np.random.randn(10, 2), columns=index(2)) with ensure_clean_path(self.path) as path: with catch_warnings(record=True): - with self.assertRaises( + with pytest.raises( ValueError, msg=("cannot have non-object label " "DataIndexableCol")): df.to_hdf(path, 'df', format='table', @@ -4926,21 +4926,21 @@ def test_read_hdf_errors(self): columns=list('ABCDE')) with ensure_clean_path(self.path) as path: - self.assertRaises(IOError, read_hdf, path, 'key') + pytest.raises(IOError, read_hdf, path, 'key') df.to_hdf(path, 'df') store = HDFStore(path, mode='r') store.close() - self.assertRaises(IOError, read_hdf, store, 'df') + pytest.raises(IOError, read_hdf, store, 'df') with open(path, mode='r') as store: - self.assertRaises(NotImplementedError, read_hdf, store, 'df') + pytest.raises(NotImplementedError, read_hdf, store, 'df') def test_invalid_complib(self): df = DataFrame(np.random.rand(4, 5), index=list('abcd'), columns=list('ABCDE')) with ensure_clean_path(self.path) as path: - self.assertRaises(ValueError, df.to_hdf, path, - 'df', complib='blosc:zlib') + pytest.raises(ValueError, df.to_hdf, path, + 'df', complib='blosc:zlib') # GH10443 def test_read_nokey(self): @@ -4955,7 +4955,7 @@ def test_read_nokey(self): reread = read_hdf(path) assert_frame_equal(df, reread) df.to_hdf(path, 'df2', mode='a') - self.assertRaises(ValueError, read_hdf, path) + pytest.raises(ValueError, read_hdf, path) def test_read_nokey_table(self): # GH13231 @@ -4967,13 +4967,13 @@ def test_read_nokey_table(self): reread = read_hdf(path) assert_frame_equal(df, reread) df.to_hdf(path, 'df2', mode='a', format='table') - self.assertRaises(ValueError, read_hdf, path) + pytest.raises(ValueError, read_hdf, path) def test_read_nokey_empty(self): with ensure_clean_path(self.path) as path: store = HDFStore(path) store.close() - self.assertRaises(ValueError, read_hdf, path) + pytest.raises(ValueError, read_hdf, path) def test_read_from_pathlib_path(self): @@ -5055,14 +5055,14 @@ def test_query_compare_column_type(self): for v in [2.1, True, pd.Timestamp('2014-01-01'), pd.Timedelta(1, 's')]: query = 'date {op} v'.format(op=op) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): result = store.select('test', where=query) # strings to other columns must be convertible to type v = 'a' for col in ['int', 'float', 'real_date']: query = '{col} {op} v'.format(op=op, col=col) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): result = store.select('test', where=query) for v, col in zip(['1', '1.1', '2014-01-01'], @@ -5200,15 +5200,15 @@ def test_complex_indexing_error(self): 'C': complex128}, index=list('abcd')) with ensure_clean_store(self.path) as store: - self.assertRaises(TypeError, store.append, - 'df', df, data_columns=['C']) + pytest.raises(TypeError, store.append, + 'df', df, data_columns=['C']) def test_complex_series_error(self): complex128 = np.array([1.0 + 1.0j, 1.0 + 1.0j, 1.0 + 1.0j, 1.0 + 1.0j]) s = Series(complex128, index=list('abcd')) with ensure_clean_path(self.path) as path: - self.assertRaises(TypeError, s.to_hdf, path, 'obj', format='t') + pytest.raises(TypeError, s.to_hdf, path, 'obj', format='t') with ensure_clean_path(self.path) as path: s.to_hdf(path, 'obj', format='t', index=False) @@ -5283,7 +5283,7 @@ def test_append_with_timezones_dateutil(self): tz=gettz('US/Eastern')), B=Timestamp('20130102', tz=gettz('EET'))), index=range(5)) - self.assertRaises(ValueError, store.append, 'df_tz', df) + pytest.raises(ValueError, store.append, 'df_tz', df) # this is ok _maybe_remove(store, 'df_tz') @@ -5297,7 +5297,7 @@ def test_append_with_timezones_dateutil(self): tz=gettz('US/Eastern')), B=Timestamp('20130102', tz=gettz('CET'))), index=range(5)) - self.assertRaises(ValueError, store.append, 'df_tz', df) + pytest.raises(ValueError, store.append, 'df_tz', df) # as index with ensure_clean_store(self.path) as store: @@ -5350,7 +5350,7 @@ def test_append_with_timezones_pytz(self): df = DataFrame(dict(A=Timestamp('20130102', tz='US/Eastern'), B=Timestamp('20130102', tz='EET')), index=range(5)) - self.assertRaises(ValueError, store.append, 'df_tz', df) + pytest.raises(ValueError, store.append, 'df_tz', df) # this is ok _maybe_remove(store, 'df_tz') @@ -5363,7 +5363,7 @@ def test_append_with_timezones_pytz(self): df = DataFrame(dict(A=Timestamp('20130102', tz='US/Eastern'), B=Timestamp('20130102', tz='CET')), index=range(5)) - self.assertRaises(ValueError, store.append, 'df_tz', df) + pytest.raises(ValueError, store.append, 'df_tz', df) # as index with ensure_clean_store(self.path) as store: diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index b4c7f2ba8719e..63fcfb0d2f5ac 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -390,8 +390,8 @@ def _to_sql_fail(self): self.assertTrue(self.pandasSQL.has_table( 'test_frame1'), 'Table not written to DB') - self.assertRaises(ValueError, self.pandasSQL.to_sql, - self.test_frame1, 'test_frame1', if_exists='fail') + pytest.raises(ValueError, self.pandasSQL.to_sql, + self.test_frame1, 'test_frame1', if_exists='fail') self.drop_table('test_frame1') @@ -539,8 +539,8 @@ def test_to_sql_fail(self): sql.has_table('test_frame2', self.conn), 'Table not written to DB') - self.assertRaises(ValueError, sql.to_sql, self.test_frame1, - 'test_frame2', self.conn, if_exists='fail') + pytest.raises(ValueError, sql.to_sql, self.test_frame1, + 'test_frame2', self.conn, if_exists='fail') def test_to_sql_replace(self): sql.to_sql(self.test_frame1, 'test_frame3', @@ -590,8 +590,8 @@ def test_to_sql_series(self): def test_to_sql_panel(self): with catch_warnings(record=True): panel = tm.makePanel() - self.assertRaises(NotImplementedError, sql.to_sql, panel, - 'test_panel', self.conn) + pytest.raises(NotImplementedError, sql.to_sql, panel, + 'test_panel', self.conn) def test_roundtrip(self): sql.to_sql(self.test_frame1, 'test_frame_roundtrip', @@ -679,7 +679,7 @@ def test_timedelta(self): def test_complex(self): df = DataFrame({'a': [1 + 1j, 2j]}) # Complex data type should raise error - self.assertRaises(ValueError, df.to_sql, 'test_complex', self.conn) + pytest.raises(ValueError, df.to_sql, 'test_complex', self.conn) def test_to_sql_index_label(self): temp_frame = DataFrame({'col1': range(4)}) @@ -760,9 +760,9 @@ def test_to_sql_index_label_multiindex(self): "Specified index_labels not written to database") # wrong length of index_label - self.assertRaises(ValueError, sql.to_sql, temp_frame, - 'test_index_label', self.conn, if_exists='replace', - index_label='C') + pytest.raises(ValueError, sql.to_sql, temp_frame, + 'test_index_label', self.conn, if_exists='replace', + index_label='C') def test_multiindex_roundtrip(self): df = DataFrame.from_records([(1, 2.1, 'line1'), (2, 1.5, 'line2')], @@ -1080,8 +1080,8 @@ def test_sql_open_close(self): def test_con_string_import_error(self): if not SQLALCHEMY_INSTALLED: conn = 'mysql://root@localhost/pandas_nosetest' - self.assertRaises(ImportError, sql.read_sql, "SELECT * FROM iris", - conn) + pytest.raises(ImportError, sql.read_sql, "SELECT * FROM iris", + conn) else: pytest.skip('SQLAlchemy is installed') @@ -1090,7 +1090,7 @@ def test_read_sql_delegate(self): iris_frame2 = sql.read_sql("SELECT * FROM iris", self.conn) tm.assert_frame_equal(iris_frame1, iris_frame2) - self.assertRaises(sql.DatabaseError, sql.read_sql, 'iris', self.conn) + pytest.raises(sql.DatabaseError, sql.read_sql, 'iris', self.conn) def test_safe_names_warning(self): # GH 6798 @@ -1250,7 +1250,7 @@ def test_read_table_columns(self): iris_frame.columns.values, ['SepalLength', 'SepalLength']) def test_read_table_absent(self): - self.assertRaises( + pytest.raises( ValueError, sql.read_sql_table, "this_doesnt_exist", con=self.conn) def test_default_type_conversion(self): @@ -1561,8 +1561,8 @@ def test_dtype(self): meta.reflect() sqltype = meta.tables['dtype_test2'].columns['B'].type self.assertTrue(isinstance(sqltype, sqlalchemy.TEXT)) - self.assertRaises(ValueError, df.to_sql, - 'error', self.conn, dtype={'B': str}) + pytest.raises(ValueError, df.to_sql, + 'error', self.conn, dtype={'B': str}) # GH9083 df.to_sql('dtype_test3', self.conn, dtype={'B': sqlalchemy.String(10)}) @@ -1857,8 +1857,8 @@ def test_schema_support(self): res4 = sql.read_sql_table('test_schema_other', self.conn, schema='other') tm.assert_frame_equal(df, res4) - self.assertRaises(ValueError, sql.read_sql_table, 'test_schema_other', - self.conn, schema='public') + pytest.raises(ValueError, sql.read_sql_table, 'test_schema_other', + self.conn, schema='public') # different if_exists options @@ -2060,8 +2060,8 @@ def test_dtype(self): self.assertEqual(self._get_sqlite_column_type( 'dtype_test2', 'B'), 'STRING') - self.assertRaises(ValueError, df.to_sql, - 'error', self.conn, dtype={'B': bool}) + pytest.raises(ValueError, df.to_sql, + 'error', self.conn, dtype={'B': bool}) # single dtype df.to_sql('single_dtype_test', self.conn, dtype='STRING') @@ -2095,7 +2095,7 @@ def test_illegal_names(self): df = DataFrame([[1, 2], [3, 4]], columns=['a', 'b']) # Raise error on blank - self.assertRaises(ValueError, df.to_sql, "", self.conn) + pytest.raises(ValueError, df.to_sql, "", self.conn) for ndx, weird_name in enumerate( ['test_weird_name]', 'test_weird_name[', @@ -2324,23 +2324,23 @@ def clean_up(test_table_to_drop): self.drop_table(test_table_to_drop) # test if invalid value for if_exists raises appropriate error - self.assertRaises(ValueError, - sql.to_sql, - frame=df_if_exists_1, - con=self.conn, - name=table_name, - if_exists='notvalidvalue') + pytest.raises(ValueError, + sql.to_sql, + frame=df_if_exists_1, + con=self.conn, + name=table_name, + if_exists='notvalidvalue') clean_up(table_name) # test if_exists='fail' sql.to_sql(frame=df_if_exists_1, con=self.conn, name=table_name, if_exists='fail') - self.assertRaises(ValueError, - sql.to_sql, - frame=df_if_exists_1, - con=self.conn, - name=table_name, - if_exists='fail') + pytest.raises(ValueError, + sql.to_sql, + frame=df_if_exists_1, + con=self.conn, + name=table_name, + if_exists='fail') # test if_exists='replace' sql.to_sql(frame=df_if_exists_1, con=self.conn, name=table_name, @@ -2642,23 +2642,23 @@ def clean_up(test_table_to_drop): self.drop_table(test_table_to_drop) # test if invalid value for if_exists raises appropriate error - self.assertRaises(ValueError, - sql.to_sql, - frame=df_if_exists_1, - con=self.conn, - name=table_name, - if_exists='notvalidvalue') + pytest.raises(ValueError, + sql.to_sql, + frame=df_if_exists_1, + con=self.conn, + name=table_name, + if_exists='notvalidvalue') clean_up(table_name) # test if_exists='fail' sql.to_sql(frame=df_if_exists_1, con=self.conn, name=table_name, if_exists='fail', index=False) - self.assertRaises(ValueError, - sql.to_sql, - frame=df_if_exists_1, - con=self.conn, - name=table_name, - if_exists='fail') + pytest.raises(ValueError, + sql.to_sql, + frame=df_if_exists_1, + con=self.conn, + name=table_name, + if_exists='fail') # test if_exists='replace' sql.to_sql(frame=df_if_exists_1, con=self.conn, name=table_name, diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 7ffe054978b9b..9dc2bd589bf9b 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -523,7 +523,7 @@ def test_no_index(self): with tm.ensure_clean() as path: original.to_stata(path, write_index=False) written_and_read_again = self.read_dta(path) - tm.assertRaises( + pytest.raises( KeyError, lambda: written_and_read_again['index_not_written']) def test_string_no_dates(self): @@ -677,7 +677,7 @@ def test_excessively_long_string(self): s['s' + str(str_len)] = Series(['a' * str_len, 'b' * str_len, 'c' * str_len]) original = DataFrame(s) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): with tm.ensure_clean() as path: original.to_stata(path) @@ -831,11 +831,11 @@ def test_drop_column(self): columns=columns) tm.assert_frame_equal(expected, reordered) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): columns = ['byte_', 'byte_'] read_stata(self.dta15_117, convert_dates=True, columns=columns) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): columns = ['byte_', 'int_', 'long_', 'not_found'] read_stata(self.dta15_117, convert_dates=True, columns=columns) @@ -889,7 +889,7 @@ def test_categorical_warnings_and_errors(self): original = pd.concat([original[col].astype('category') for col in original], axis=1) with tm.ensure_clean() as path: - tm.assertRaises(ValueError, original.to_stata, path) + pytest.raises(ValueError, original.to_stata, path) original = pd.DataFrame.from_records( [['a'], @@ -1151,7 +1151,7 @@ def test_write_variable_label_errors(self): 'b': 'City Exponent', 'c': u''.join(values)} - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): with tm.ensure_clean() as path: original.to_stata(path, variable_labels=variable_labels_utf8) @@ -1161,7 +1161,7 @@ def test_write_variable_label_errors(self): 'that is too long for Stata which means ' 'that it has more than 80 characters'} - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): with tm.ensure_clean() as path: original.to_stata(path, variable_labels=variable_labels_long) @@ -1188,7 +1188,7 @@ def test_default_date_conversion(self): def test_unsupported_type(self): original = pd.DataFrame({'a': [1 + 2j, 2 + 4j]}) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): with tm.ensure_clean() as path: original.to_stata(path) @@ -1200,7 +1200,7 @@ def test_unsupported_datetype(self): 'strs': ['apple', 'banana', 'cherry'], 'dates': dates}) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): with tm.ensure_clean() as path: original.to_stata(path, convert_dates={'dates': 'tC'}) @@ -1208,13 +1208,13 @@ def test_unsupported_datetype(self): original = pd.DataFrame({'nums': [1.0, 2.0, 3.0], 'strs': ['apple', 'banana', 'cherry'], 'dates': dates}) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): with tm.ensure_clean() as path: original.to_stata(path) def test_repeated_column_labels(self): # GH 13923 - with tm.assertRaises(ValueError) as cm: + with pytest.raises(ValueError) as cm: read_stata(self.dta23, convert_categoricals=True) tm.assertTrue('wolof' in cm.exception) @@ -1239,13 +1239,13 @@ def test_out_of_range_double(self): 'ColumnTooBig': [0.0, np.finfo(np.double).eps, np.finfo(np.double).max]}) - with tm.assertRaises(ValueError) as cm: + with pytest.raises(ValueError) as cm: with tm.ensure_clean() as path: df.to_stata(path) tm.assertTrue('ColumnTooBig' in cm.exception) df.loc[2, 'ColumnTooBig'] = np.inf - with tm.assertRaises(ValueError) as cm: + with pytest.raises(ValueError) as cm: with tm.ensure_clean() as path: df.to_stata(path) tm.assertTrue('ColumnTooBig' in cm.exception) @@ -1271,7 +1271,7 @@ def test_out_of_range_float(self): reread.set_index('index')) original.loc[2, 'ColumnTooBig'] = np.inf - with tm.assertRaises(ValueError) as cm: + with pytest.raises(ValueError) as cm: with tm.ensure_clean() as path: original.to_stata(path) tm.assertTrue('ColumnTooBig' in cm.exception) @@ -1280,6 +1280,6 @@ def test_out_of_range_float(self): def test_invalid_encoding(self): # GH15723, validate encoding original = self.read_csv(self.csv3) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): with tm.ensure_clean() as path: original.to_stata(path, encoding='utf-8') diff --git a/pandas/tests/plotting/test_boxplot_method.py b/pandas/tests/plotting/test_boxplot_method.py index 8755ce419ae20..64d0fec2b5646 100644 --- a/pandas/tests/plotting/test_boxplot_method.py +++ b/pandas/tests/plotting/test_boxplot_method.py @@ -106,7 +106,7 @@ def test_boxplot_return_type_legacy(self): df = DataFrame(randn(6, 4), index=list(string.ascii_letters[:6]), columns=['one', 'two', 'three', 'four']) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.boxplot(return_type='NOTATYPE') result = df.boxplot() @@ -263,13 +263,13 @@ def test_grouped_box_return_type(self): def test_grouped_box_layout(self): df = self.hist_df - self.assertRaises(ValueError, df.boxplot, column=['weight', 'height'], - by=df.gender, layout=(1, 1)) - self.assertRaises(ValueError, df.boxplot, - column=['height', 'weight', 'category'], - layout=(2, 1), return_type='dict') - self.assertRaises(ValueError, df.boxplot, column=['weight', 'height'], - by=df.gender, layout=(-1, -1)) + pytest.raises(ValueError, df.boxplot, column=['weight', 'height'], + by=df.gender, layout=(1, 1)) + pytest.raises(ValueError, df.boxplot, + column=['height', 'weight', 'category'], + layout=(2, 1), return_type='dict') + pytest.raises(ValueError, df.boxplot, column=['weight', 'height'], + by=df.gender, layout=(-1, -1)) # _check_plot_works adds an ax so catch warning. see GH #13188 with tm.assert_produces_warning(UserWarning): @@ -369,7 +369,7 @@ def test_grouped_box_multiple_axes(self): tm.assert_numpy_array_equal(returned, axes[1]) self.assertIs(returned[0].figure, fig) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): fig, axes = self.plt.subplots(2, 3) # pass different number of axes from required with tm.assert_produces_warning(UserWarning): diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index 803907c60d0d0..364a561669ed2 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -98,7 +98,7 @@ def test_nonnumeric_exclude(self): self.assertEqual(len(ax.get_lines()), 1) # B was plotted plt.close(plt.gcf()) - self.assertRaises(TypeError, df['A'].plot) + pytest.raises(TypeError, df['A'].plot) @slow def test_tsplot(self): @@ -130,10 +130,10 @@ def test_both_style_and_color(self): import matplotlib.pyplot as plt # noqa ts = tm.makeTimeSeries() - self.assertRaises(ValueError, ts.plot, style='b-', color='#000099') + pytest.raises(ValueError, ts.plot, style='b-', color='#000099') s = ts.reset_index(drop=True) - self.assertRaises(ValueError, s.plot, style='b-', color='#000099') + pytest.raises(ValueError, s.plot, style='b-', color='#000099') @slow def test_high_freq(self): diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index 448201960b3d1..0e9aa3355a658 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -64,7 +64,7 @@ def test_plot(self): df = DataFrame({'x': [1, 2], 'y': [3, 4]}) # mpl >= 1.5.2 (or slightly below) throw AttributError - with tm.assertRaises((TypeError, AttributeError)): + with pytest.raises((TypeError, AttributeError)): df.plot.line(blarg=True) df = DataFrame(np.random.rand(10, 3), @@ -154,7 +154,7 @@ def test_mpl2_color_cycle_str(self): def test_color_empty_string(self): df = DataFrame(randn(10, 2)) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.plot(color='') def test_color_and_style_arguments(self): @@ -170,7 +170,7 @@ def test_color_and_style_arguments(self): self.assertEqual(color, ['red', 'black']) # passing both 'color' and 'style' arguments should not be allowed # if there is a color symbol in the style strings: - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.plot(color=['red', 'black'], style=['k-', 'r--']) def test_nonnumeric_exclude(self): @@ -401,9 +401,9 @@ def test_subplots_layout(self): self._check_axes_shape(axes, axes_num=3, layout=(4, 1)) self.assertEqual(axes.shape, (4, 1)) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): axes = df.plot(subplots=True, layout=(1, 1)) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): axes = df.plot(subplots=True, layout=(-1, -1)) # single column @@ -453,7 +453,7 @@ def test_subplots_multiple_axes(self): self._check_axes_shape(axes, axes_num=6, layout=(2, 3)) tm.close() - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): fig, axes = self.plt.subplots(2, 3) # pass different number of axes from required df.plot(subplots=True, ax=axes) @@ -560,9 +560,9 @@ def test_negative_log(self): index=list(string.ascii_letters[:6]), columns=['x', 'y', 'z', 'four']) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.plot.area(logy=True) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.plot.area(loglog=True) def _compare_stacked_y_cood(self, normal_lines, stacked_lines): @@ -601,7 +601,7 @@ def test_line_area_stacked(self): self._compare_stacked_y_cood(ax1.lines[2:], ax2.lines[2:]) _check_plot_works(mixed_df.plot, stacked=False) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): mixed_df.plot(stacked=True) _check_plot_works(df.plot, kind=kind, logx=True, stacked=True) @@ -900,9 +900,9 @@ def test_plot_scatter(self): _check_plot_works(df.plot.scatter, x='x', y='y') _check_plot_works(df.plot.scatter, x=1, y=2) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): df.plot.scatter(x='x') - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): df.plot.scatter(y='y') # GH 6951 @@ -965,7 +965,7 @@ def test_plot_scatter_with_c(self): def test_scatter_colors(self): df = DataFrame({'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): df.plot.scatter(x='a', y='b', c='c', color='green') default_colors = self._maybe_unpack_cycler(self.plt.rcParams) @@ -1227,7 +1227,7 @@ def test_boxplot_return_type(self): df = DataFrame(randn(6, 4), index=list(string.ascii_letters[:6]), columns=['one', 'two', 'three', 'four']) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.plot.box(return_type='NOTATYPE') result = df.plot.box(return_type='dict') @@ -1620,7 +1620,7 @@ def test_line_colors(self): self._check_colors(ax.get_lines(), linecolors=custom_colors) tm.close() - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): # Color contains shorthand hex value results in ValueError custom_colors = ['#F00', '#00F', '#FF0', '#000', '#FFF'] # Forced show plot @@ -1677,7 +1677,7 @@ def test_line_colors_and_styles_subplots(self): self._check_colors(ax.get_lines(), linecolors=[c]) tm.close() - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): # Color contains shorthand hex value results in ValueError custom_colors = ['#F00', '#00F', '#FF0', '#000', '#FFF'] # Forced show plot @@ -1947,7 +1947,7 @@ def _check_colors(bp, box_c, whiskers_c, medians_c, caps_c='k', _check_colors(bp, (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), '#123456') - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): # Color contains invalid key results in ValueError df.plot.box(color=dict(boxes='red', xxxx='blue')) @@ -1994,7 +1994,7 @@ def test_all_invalid_plot_data(self): for kind in plotting._core._common_kinds: if not _ok_for_gaussian_kde(kind): continue - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): df.plot(kind=kind) @slow @@ -2005,7 +2005,7 @@ def test_partially_invalid_plot_data(self): for kind in plotting._core._common_kinds: if not _ok_for_gaussian_kde(kind): continue - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): df.plot(kind=kind) with tm.RNGContext(42): @@ -2014,12 +2014,12 @@ def test_partially_invalid_plot_data(self): df = DataFrame(rand(10, 2), dtype=object) df[np.random.rand(df.shape[0]) > 0.5] = 'a' for kind in kinds: - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): df.plot(kind=kind) def test_invalid_kind(self): df = DataFrame(randn(10, 2)) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.plot(kind='aasdf') @slow @@ -2074,14 +2074,14 @@ def test_allow_cmap(self): ax = df.plot.hexbin(x='A', y='B', cmap='YlGn') self.assertEqual(ax.collections[0].cmap.name, 'YlGn') - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): df.plot.hexbin(x='A', y='B', cmap='YlGn', colormap='BuGn') @slow def test_pie_df(self): df = DataFrame(np.random.rand(5, 3), columns=['X', 'Y', 'Z'], index=['a', 'b', 'c', 'd', 'e']) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.plot.pie() ax = _check_plot_works(df.plot.pie, y='Y') @@ -2193,11 +2193,11 @@ def test_errorbar_plot(self): ax = _check_plot_works(s_df.plot, y='y', x='x', yerr=yerr) self._check_has_errorbars(ax, xerr=0, yerr=1) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.plot(yerr=np.random.randn(11)) df_err = DataFrame({'x': ['zzz'] * 12, 'y': ['zzz'] * 12}) - with tm.assertRaises((ValueError, TypeError)): + with pytest.raises((ValueError, TypeError)): df.plot(yerr=df_err) @slow @@ -2288,7 +2288,7 @@ def test_errorbar_asymmetrical(self): self.assertEqual(ax.lines[5].get_xdata()[0], -err[1, 0, 0] / 2) self.assertEqual(ax.lines[6].get_xdata()[0], err[1, 1, 0] / 2) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.plot(yerr=err.T) tm.close() @@ -2477,7 +2477,7 @@ def test_memory_leak(self): gc.collect() for key in results: # check that every plot was collected - with tm.assertRaises(ReferenceError): + with pytest.raises(ReferenceError): # need to actually access something to get an error results[key].lines @@ -2667,13 +2667,13 @@ def test_option_mpl_style(self): check_stacklevel=False): set_option('display.mpl_style', False) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): set_option('display.mpl_style', 'default2') def test_invalid_colormap(self): df = DataFrame(randn(3, 2), columns=['A', 'B']) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.plot(colormap='invalid_colormap') def test_plain_axes(self): diff --git a/pandas/tests/plotting/test_hist_method.py b/pandas/tests/plotting/test_hist_method.py index 4552464ce1e1f..6dd97a1181f22 100644 --- a/pandas/tests/plotting/test_hist_method.py +++ b/pandas/tests/plotting/test_hist_method.py @@ -2,6 +2,8 @@ """ Test cases for .hist method """ +import pytest + from pandas import Series, DataFrame import pandas.util.testing as tm from pandas.util.testing import slow @@ -45,7 +47,7 @@ def test_hist_legacy(self): _check_plot_works(self.ts.hist, figure=fig, ax=ax1) _check_plot_works(self.ts.hist, figure=fig, ax=ax2) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): self.ts.hist(by=self.ts.index, figure=fig) @slow @@ -57,10 +59,10 @@ def test_hist_bins_legacy(self): @slow def test_hist_layout(self): df = self.hist_df - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.height.hist(layout=(1, 1)) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.height.hist(layout=[1, 1]) @slow @@ -134,7 +136,7 @@ def test_plot_fails_when_ax_differs_from_figure(self): fig1 = figure() fig2 = figure() ax1 = fig1.add_subplot(111) - with tm.assertRaises(AssertionError): + with pytest.raises(AssertionError): self.ts.hist(ax=ax1, figure=fig2) @@ -204,7 +206,7 @@ def test_hist_df_legacy(self): tm.close() # propagate attr exception from matplotlib.Axes.hist - with tm.assertRaises(AttributeError): + with pytest.raises(AttributeError): ser.hist(foo='bar') @slow @@ -229,13 +231,13 @@ def test_hist_layout(self): self._check_axes_shape(axes, axes_num=3, layout=expected) # layout too small for all 4 plots - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.hist(layout=(1, 1)) # invalid format for layout - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.hist(layout=(1,)) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.hist(layout=(-1, -1)) @slow @@ -295,7 +297,7 @@ def test_grouped_hist_legacy(self): tm.close() # propagate attr exception from matplotlib.Axes.hist - with tm.assertRaises(AttributeError): + with pytest.raises(AttributeError): grouped_hist(df.A, by=df.C, foo='bar') with tm.assert_produces_warning(FutureWarning): @@ -319,12 +321,12 @@ def test_grouped_hist_legacy2(self): @slow def test_grouped_hist_layout(self): df = self.hist_df - self.assertRaises(ValueError, df.hist, column='weight', by=df.gender, - layout=(1, 1)) - self.assertRaises(ValueError, df.hist, column='height', by=df.category, - layout=(1, 3)) - self.assertRaises(ValueError, df.hist, column='height', by=df.category, - layout=(-1, -1)) + pytest.raises(ValueError, df.hist, column='weight', by=df.gender, + layout=(1, 1)) + pytest.raises(ValueError, df.hist, column='height', by=df.category, + layout=(1, 3)) + pytest.raises(ValueError, df.hist, column='height', by=df.category, + layout=(-1, -1)) with tm.assert_produces_warning(UserWarning): axes = _check_plot_works(df.hist, column='height', by=df.gender, @@ -380,7 +382,7 @@ def test_grouped_hist_multiple_axes(self): tm.assert_numpy_array_equal(returned, axes[1]) self.assertIs(returned[0].figure, fig) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): fig, axes = self.plt.subplots(2, 3) # pass different number of axes from required axes = df.hist(column='height', ax=axes) diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py index fe0b6c103a0e1..07abd0190a417 100644 --- a/pandas/tests/plotting/test_misc.py +++ b/pandas/tests/plotting/test_misc.py @@ -2,6 +2,8 @@ """ Test cases for misc plot functions """ +import pytest + from pandas import Series, DataFrame from pandas.compat import lmap import pandas.util.testing as tm @@ -310,14 +312,14 @@ def test_subplot_titles(self): self.assertEqual([p.get_title() for p in plot], title) # Case len(title) > len(df) - self.assertRaises(ValueError, df.plot, subplots=True, - title=title + ["kittens > puppies"]) + pytest.raises(ValueError, df.plot, subplots=True, + title=title + ["kittens > puppies"]) # Case len(title) < len(df) - self.assertRaises(ValueError, df.plot, subplots=True, title=title[:2]) + pytest.raises(ValueError, df.plot, subplots=True, title=title[:2]) # Case subplots=False and title is of type list - self.assertRaises(ValueError, df.plot, subplots=False, title=title) + pytest.raises(ValueError, df.plot, subplots=False, title=title) # Case df with 3 numeric columns but layout of (2,2) plot = df.drop('SepalWidth', axis=1).plot(subplots=True, layout=(2, 2), diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index 25c2aee4cbe7a..38ce5f44b812f 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -4,6 +4,7 @@ import itertools +import pytest from datetime import datetime @@ -297,7 +298,7 @@ def test_pie_series(self): self.assertEqual(t.get_fontsize(), 7) # includes negative value - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): series = Series([1, 2, 0, 4, -1], index=['a', 'b', 'c', 'd', 'e']) series.plot.pie() @@ -356,7 +357,7 @@ def test_hist_legacy(self): _check_plot_works(self.ts.hist, figure=fig, ax=ax1) _check_plot_works(self.ts.hist, figure=fig, ax=ax2) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): self.ts.hist(by=self.ts.index, figure=fig) @slow @@ -368,10 +369,10 @@ def test_hist_bins_legacy(self): @slow def test_hist_layout(self): df = self.hist_df - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.height.hist(layout=(1, 1)) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.height.hist(layout=[1, 1]) @slow @@ -530,7 +531,7 @@ def test_df_series_secondary_legend(self): @slow def test_plot_fails_with_dupe_color_and_style(self): x = Series(randn(2)) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): x.plot(style='k--', color='k') @slow @@ -636,7 +637,7 @@ def test_invalid_plot_data(self): for kind in plotting._core._common_kinds: if not _ok_for_gaussian_kde(kind): continue - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): s.plot(kind=kind) @slow @@ -652,12 +653,12 @@ def test_partially_invalid_plot_data(self): for kind in plotting._core._common_kinds: if not _ok_for_gaussian_kde(kind): continue - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): s.plot(kind=kind) def test_invalid_kind(self): s = Series([1, 2]) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): s.plot(kind='aasdf') @slow @@ -704,12 +705,12 @@ def test_errorbar_plot(self): self._check_has_errorbars(ax, xerr=0, yerr=1) # check incorrect lengths and types - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): s.plot(yerr=np.arange(11)) s_err = ['zzz'] * 10 # in mpl 1.5+ this is a TypeError - with tm.assertRaises((ValueError, TypeError)): + with pytest.raises((ValueError, TypeError)): s.plot(yerr=s_err) def test_table(self): diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index 75c0efaee85c4..b877a9d181848 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -1110,11 +1110,11 @@ def test_concat_keys_levels_no_overlap(self): df = DataFrame(np.random.randn(1, 3), index=['a']) df2 = DataFrame(np.random.randn(1, 4), index=['b']) - self.assertRaises(ValueError, concat, [df, df], - keys=['one', 'two'], levels=[['foo', 'bar', 'baz']]) + pytest.raises(ValueError, concat, [df, df], + keys=['one', 'two'], levels=[['foo', 'bar', 'baz']]) - self.assertRaises(ValueError, concat, [df, df2], - keys=['one', 'two'], levels=[['foo', 'bar', 'baz']]) + pytest.raises(ValueError, concat, [df, df2], + keys=['one', 'two'], levels=[['foo', 'bar', 'baz']]) def test_concat_rename_index(self): a = DataFrame(np.random.rand(3, 3), @@ -1306,7 +1306,7 @@ def test_concat_mixed_objs(self): # invalid concatente of mixed dims with catch_warnings(record=True): panel = tm.makePanel() - self.assertRaises(ValueError, lambda: concat([panel, s1], axis=1)) + pytest.raises(ValueError, lambda: concat([panel, s1], axis=1)) def test_empty_dtype_coerce(self): @@ -1500,7 +1500,7 @@ def test_concat_exclude_none(self): pieces = [df[:5], None, None, df[5:]] result = concat(pieces) tm.assert_frame_equal(result, df) - self.assertRaises(ValueError, concat, [None, None]) + pytest.raises(ValueError, concat, [None, None]) def test_concat_datetime64_block(self): from pandas.core.indexes.datetimes import date_range @@ -1634,12 +1634,12 @@ def test_concat_invalid(self): # trying to concat a ndframe with a non-ndframe df1 = mkdf(10, 2) for obj in [1, dict(), [1, 2], (1, 2)]: - self.assertRaises(TypeError, lambda x: concat([df1, obj])) + pytest.raises(TypeError, lambda x: concat([df1, obj])) def test_concat_invalid_first_argument(self): df1 = mkdf(10, 2) df2 = mkdf(10, 2) - self.assertRaises(TypeError, concat, df1, df2) + pytest.raises(TypeError, concat, df1, df2) # generator ok though concat(DataFrame(np.random.rand(5, 5)) for _ in range(3)) diff --git a/pandas/tests/reshape/test_hashing.py b/pandas/tests/reshape/test_hashing.py index 7ab9558d961aa..fba3a15182238 100644 --- a/pandas/tests/reshape/test_hashing.py +++ b/pandas/tests/reshape/test_hashing.py @@ -47,7 +47,7 @@ def test_hash_array_mixed(self): def test_hash_array_errors(self): for val in [5, 'foo', pd.Timestamp('20130101')]: - self.assertRaises(TypeError, hash_array, val) + pytest.raises(TypeError, hash_array, val) def check_equal(self, obj, **kwargs): a = hash_pandas_object(obj, **kwargs) @@ -81,7 +81,7 @@ def test_hash_tuples(self): def test_hash_tuples_err(self): for val in [5, 'foo', pd.Timestamp('20130101')]: - self.assertRaises(TypeError, hash_tuples, val) + pytest.raises(TypeError, hash_tuples, val) def test_multiindex_unique(self): mi = MultiIndex.from_tuples([(118, 472), (236, 118), @@ -221,7 +221,7 @@ def test_invalid_key(self): # this only matters for object dtypes def f(): hash_pandas_object(Series(list('abc')), hash_key='foo') - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def test_alread_encoded(self): # if already encoded then ok diff --git a/pandas/tests/reshape/test_join.py b/pandas/tests/reshape/test_join.py index 3075d24d95375..aa42f190926ae 100644 --- a/pandas/tests/reshape/test_join.py +++ b/pandas/tests/reshape/test_join.py @@ -3,6 +3,7 @@ from warnings import catch_warnings from numpy.random import randn import numpy as np +import pytest import pandas as pd from pandas.compat import lrange @@ -193,15 +194,15 @@ def test_join_on(self): self.assertTrue(np.isnan(joined['three']['c'])) # merge column not p resent - self.assertRaises(KeyError, target.join, source, on='E') + pytest.raises(KeyError, target.join, source, on='E') # overlap source_copy = source.copy() source_copy['A'] = 0 - self.assertRaises(ValueError, target.join, source_copy, on='A') + pytest.raises(ValueError, target.join, source_copy, on='A') def test_join_on_fails_with_different_right_index(self): - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df = DataFrame({'a': np.random.choice(['m', 'f'], size=3), 'b': np.random.randn(3)}) df2 = DataFrame({'a': np.random.choice(['m', 'f'], size=10), @@ -210,7 +211,7 @@ def test_join_on_fails_with_different_right_index(self): merge(df, df2, left_on='a', right_index=True) def test_join_on_fails_with_different_left_index(self): - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df = DataFrame({'a': np.random.choice(['m', 'f'], size=3), 'b': np.random.randn(3)}, index=tm.makeCustomIndex(10, 2)) @@ -219,7 +220,7 @@ def test_join_on_fails_with_different_left_index(self): merge(df, df2, right_on='b', left_index=True) def test_join_on_fails_with_different_column_counts(self): - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df = DataFrame({'a': np.random.choice(['m', 'f'], size=3), 'b': np.random.randn(3)}) df2 = DataFrame({'a': np.random.choice(['m', 'f'], size=10), @@ -588,7 +589,7 @@ def _check_diff_index(df_list, result, exp_index): joined = df_list[0].join(df_list[1:], how='inner') _check_diff_index(df_list, joined, df.index[2:8]) - self.assertRaises(ValueError, df_list[0].join, df_list[1:], on='a') + pytest.raises(ValueError, df_list[0].join, df_list[1:], on='a') def test_join_many_mixed(self): df = DataFrame(np.random.randn(8, 4), columns=['A', 'B', 'C', 'D']) @@ -710,10 +711,10 @@ def test_panel_join_many(self): tm.assert_panel_equal(joined, expected) # edge cases - self.assertRaises(ValueError, panels[0].join, panels[1:], - how='outer', lsuffix='foo', rsuffix='bar') - self.assertRaises(ValueError, panels[0].join, panels[1:], - how='right') + pytest.raises(ValueError, panels[0].join, panels[1:], + how='outer', lsuffix='foo', rsuffix='bar') + pytest.raises(ValueError, panels[0].join, panels[1:], + how='right') def _check_join(left, right, result, join_col, how='left', diff --git a/pandas/tests/reshape/test_merge.py b/pandas/tests/reshape/test_merge.py index 8aff478bee5fd..8ddeb4bdda14a 100644 --- a/pandas/tests/reshape/test_merge.py +++ b/pandas/tests/reshape/test_merge.py @@ -104,25 +104,25 @@ def test_merge_index_singlekey_inner(self): assert_frame_equal(result, expected.loc[:, result.columns]) def test_merge_misspecified(self): - self.assertRaises(ValueError, merge, self.left, self.right, - left_index=True) - self.assertRaises(ValueError, merge, self.left, self.right, - right_index=True) + pytest.raises(ValueError, merge, self.left, self.right, + left_index=True) + pytest.raises(ValueError, merge, self.left, self.right, + right_index=True) - self.assertRaises(ValueError, merge, self.left, self.left, - left_on='key', on='key') + pytest.raises(ValueError, merge, self.left, self.left, + left_on='key', on='key') - self.assertRaises(ValueError, merge, self.df, self.df2, - left_on=['key1'], right_on=['key1', 'key2']) + pytest.raises(ValueError, merge, self.df, self.df2, + left_on=['key1'], right_on=['key1', 'key2']) def test_index_and_on_parameters_confusion(self): - self.assertRaises(ValueError, merge, self.df, self.df2, how='left', - left_index=False, right_index=['key1', 'key2']) - self.assertRaises(ValueError, merge, self.df, self.df2, how='left', - left_index=['key1', 'key2'], right_index=False) - self.assertRaises(ValueError, merge, self.df, self.df2, how='left', - left_index=['key1', 'key2'], - right_index=['key1', 'key2']) + pytest.raises(ValueError, merge, self.df, self.df2, how='left', + left_index=False, right_index=['key1', 'key2']) + pytest.raises(ValueError, merge, self.df, self.df2, how='left', + left_index=['key1', 'key2'], right_index=False) + pytest.raises(ValueError, merge, self.df, self.df2, how='left', + left_index=['key1', 'key2'], + right_index=['key1', 'key2']) def test_merge_overlap(self): merged = merge(self.left, self.left, on='key') @@ -254,7 +254,7 @@ def test_no_overlap_more_informative_error(self): df1 = DataFrame({'x': ['a']}, index=[dt]) df2 = DataFrame({'y': ['b', 'c']}, index=[dt, dt]) - self.assertRaises(MergeError, merge, df1, df2) + pytest.raises(MergeError, merge, df1, df2) def test_merge_non_unique_indexes(self): @@ -549,7 +549,7 @@ def test_overlapping_columns_error_message(self): # #2649, #10639 df2.columns = ['key1', 'foo', 'foo'] - self.assertRaises(ValueError, merge, df, df2) + pytest.raises(ValueError, merge, df, df2) def test_merge_on_datetime64tz(self): @@ -663,9 +663,9 @@ def test_indicator(self): assert_frame_equal(test_custom_name, df_result_custom_name) # Check only accepts strings and booleans - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): merge(df1, df2, on='col1', how='outer', indicator=5) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df1.merge(df2, on='col1', how='outer', indicator=5) # Check result integrity @@ -689,20 +689,20 @@ def test_indicator(self): for i in ['_right_indicator', '_left_indicator', '_merge']: df_badcolumn = DataFrame({'col1': [1, 2], i: [2, 2]}) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): merge(df1, df_badcolumn, on='col1', how='outer', indicator=True) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df1.merge(df_badcolumn, on='col1', how='outer', indicator=True) # Check for name conflict with custom name df_badcolumn = DataFrame( {'col1': [1, 2], 'custom_column_name': [2, 2]}) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): merge(df1, df_badcolumn, on='col1', how='outer', indicator='custom_column_name') - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df1.merge(df_badcolumn, on='col1', how='outer', indicator='custom_column_name') @@ -1136,14 +1136,14 @@ def test_join_multi_levels(self): def f(): household.join(portfolio, how='inner') - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) portfolio2 = portfolio.copy() portfolio2.index.set_names(['household_id', 'foo']) def f(): portfolio2.join(portfolio, how='inner') - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def test_join_multi_levels2(self): @@ -1184,7 +1184,7 @@ def test_join_multi_levels2(self): def f(): household.join(log_return, how='inner') - self.assertRaises(NotImplementedError, f) + pytest.raises(NotImplementedError, f) # this is the equivalency result = (merge(household.reset_index(), log_return.reset_index(), @@ -1212,7 +1212,7 @@ def f(): def f(): household.join(log_return, how='outer') - self.assertRaises(NotImplementedError, f) + pytest.raises(NotImplementedError, f) @pytest.fixture diff --git a/pandas/tests/reshape/test_merge_asof.py b/pandas/tests/reshape/test_merge_asof.py index 865c413bad11e..0b5b580563741 100644 --- a/pandas/tests/reshape/test_merge_asof.py +++ b/pandas/tests/reshape/test_merge_asof.py @@ -1,4 +1,5 @@ import os +import pytest import pytz import numpy as np @@ -200,14 +201,14 @@ def test_multi_index(self): # MultiIndex is prohibited trades = self.trades.set_index(['time', 'price']) quotes = self.quotes.set_index('time') - with self.assertRaises(MergeError): + with pytest.raises(MergeError): merge_asof(trades, quotes, left_index=True, right_index=True) trades = self.trades.set_index('time') quotes = self.quotes.set_index(['time', 'bid']) - with self.assertRaises(MergeError): + with pytest.raises(MergeError): merge_asof(trades, quotes, left_index=True, right_index=True) @@ -217,7 +218,7 @@ def test_on_and_index(self): # 'on' parameter and index together is prohibited trades = self.trades.set_index('time') quotes = self.quotes.set_index('time') - with self.assertRaises(MergeError): + with pytest.raises(MergeError): merge_asof(trades, quotes, left_on='price', left_index=True, @@ -225,7 +226,7 @@ def test_on_and_index(self): trades = self.trades.set_index('time') quotes = self.quotes.set_index('time') - with self.assertRaises(MergeError): + with pytest.raises(MergeError): merge_asof(trades, quotes, right_on='bid', left_index=True, @@ -399,7 +400,7 @@ def test_multiby_indexed(self): assert_frame_equal(expected, result) - with self.assertRaises(MergeError): + with pytest.raises(MergeError): pd.merge_asof(left, right, left_index=True, right_index=True, left_by=['k1', 'k2'], right_by=['k1']) @@ -432,18 +433,18 @@ def test_valid_join_keys(self): trades = self.trades quotes = self.quotes - with self.assertRaises(MergeError): + with pytest.raises(MergeError): merge_asof(trades, quotes, left_on='time', right_on='bid', by='ticker') - with self.assertRaises(MergeError): + with pytest.raises(MergeError): merge_asof(trades, quotes, on=['time', 'ticker'], by='ticker') - with self.assertRaises(MergeError): + with pytest.raises(MergeError): merge_asof(trades, quotes, by='ticker') @@ -474,7 +475,7 @@ def test_valid_allow_exact_matches(self): trades = self.trades quotes = self.quotes - with self.assertRaises(MergeError): + with pytest.raises(MergeError): merge_asof(trades, quotes, on='time', by='ticker', @@ -498,27 +499,27 @@ def test_valid_tolerance(self): tolerance=1) # incompat - with self.assertRaises(MergeError): + with pytest.raises(MergeError): merge_asof(trades, quotes, on='time', by='ticker', tolerance=1) # invalid - with self.assertRaises(MergeError): + with pytest.raises(MergeError): merge_asof(trades.reset_index(), quotes.reset_index(), on='index', by='ticker', tolerance=1.0) # invalid negative - with self.assertRaises(MergeError): + with pytest.raises(MergeError): merge_asof(trades, quotes, on='time', by='ticker', tolerance=-Timedelta('1s')) - with self.assertRaises(MergeError): + with pytest.raises(MergeError): merge_asof(trades.reset_index(), quotes.reset_index(), on='index', by='ticker', @@ -532,7 +533,7 @@ def test_non_sorted(self): # we require that we are already sorted on time & quotes self.assertFalse(trades.time.is_monotonic) self.assertFalse(quotes.time.is_monotonic) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): merge_asof(trades, quotes, on='time', by='ticker') @@ -540,7 +541,7 @@ def test_non_sorted(self): trades = self.trades.sort_values('time') self.assertTrue(trades.time.is_monotonic) self.assertFalse(quotes.time.is_monotonic) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): merge_asof(trades, quotes, on='time', by='ticker') @@ -891,7 +892,7 @@ def test_on_specialized_type(self): df1 = df1.sort_values('value').reset_index(drop=True) if dtype == np.float16: - with self.assertRaises(MergeError): + with pytest.raises(MergeError): pd.merge_asof(df1, df2, on='value') continue @@ -928,7 +929,7 @@ def test_on_specialized_type_by_int(self): df1 = df1.sort_values('value').reset_index(drop=True) if dtype == np.float16: - with self.assertRaises(MergeError): + with pytest.raises(MergeError): pd.merge_asof(df1, df2, on='value', by='key') else: result = pd.merge_asof(df1, df2, on='value', by='key') diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 0624505ae619b..242011d6f23da 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -1,5 +1,8 @@ from datetime import datetime, date, timedelta +import pytest + + import numpy as np from collections import OrderedDict @@ -553,17 +556,17 @@ def test_margins_no_values_two_row_two_cols(self): def test_pivot_table_with_margins_set_margin_name(self): # GH 3335 for margin_name in ['foo', 'one', 666, None, ['a', 'b']]: - with self.assertRaises(ValueError): + with pytest.raises(ValueError): # multi-index index pivot_table(self.data, values='D', index=['A', 'B'], columns=['C'], margins=True, margins_name=margin_name) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): # multi-index column pivot_table(self.data, values='D', index=['C'], columns=['A', 'B'], margins=True, margins_name=margin_name) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): # non-multi-index index/column pivot_table(self.data, values='D', index=['A'], columns=['B'], margins=True, @@ -626,10 +629,10 @@ def test_pivot_timegrouper(self): values='Quantity', aggfunc=np.sum) tm.assert_frame_equal(result, expected.T) - self.assertRaises(KeyError, lambda: pivot_table( + pytest.raises(KeyError, lambda: pivot_table( df, index=Grouper(freq='6MS', key='foo'), columns='Buyer', values='Quantity', aggfunc=np.sum)) - self.assertRaises(KeyError, lambda: pivot_table( + pytest.raises(KeyError, lambda: pivot_table( df, index='Buyer', columns=Grouper(freq='6MS', key='foo'), values='Quantity', aggfunc=np.sum)) @@ -646,10 +649,10 @@ def test_pivot_timegrouper(self): values='Quantity', aggfunc=np.sum) tm.assert_frame_equal(result, expected.T) - self.assertRaises(ValueError, lambda: pivot_table( + pytest.raises(ValueError, lambda: pivot_table( df, index=Grouper(freq='6MS', level='foo'), columns='Buyer', values='Quantity', aggfunc=np.sum)) - self.assertRaises(ValueError, lambda: pivot_table( + pytest.raises(ValueError, lambda: pivot_table( df, index='Buyer', columns=Grouper(freq='6MS', level='foo'), values='Quantity', aggfunc=np.sum)) diff --git a/pandas/tests/reshape/test_reshape.py b/pandas/tests/reshape/test_reshape.py index 0eb1e5ff3cf11..8960ae610f8d7 100644 --- a/pandas/tests/reshape/test_reshape.py +++ b/pandas/tests/reshape/test_reshape.py @@ -1,6 +1,8 @@ # -*- coding: utf-8 -*- # pylint: disable-msg=W0612,E1101 +import pytest + from pandas import DataFrame, Series import pandas as pd @@ -428,11 +430,11 @@ def test_dataframe_dummies_prefix_sep(self): assert_frame_equal(result, expected) def test_dataframe_dummies_prefix_bad_length(self): - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): get_dummies(self.df, prefix=['too few'], sparse=self.sparse) def test_dataframe_dummies_prefix_sep_bad_length(self): - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): get_dummies(self.df, prefix_sep=['bad'], sparse=self.sparse) def test_dataframe_dummies_prefix_dict(self): @@ -740,7 +742,7 @@ def test_pairs(self): spec = {'visitdt': ['visitdt%d' % i for i in range(1, 3)], 'wt': ['wt%d' % i for i in range(1, 4)]} - self.assertRaises(ValueError, lreshape, df, spec) + pytest.raises(ValueError, lreshape, df, spec) class TestWideToLong(tm.TestCase): diff --git a/pandas/tests/reshape/test_tile.py b/pandas/tests/reshape/test_tile.py index adda25a210ba6..8aaa8a51d7020 100644 --- a/pandas/tests/reshape/test_tile.py +++ b/pandas/tests/reshape/test_tile.py @@ -1,4 +1,5 @@ import os +import pytest import numpy as np from pandas.compat import zip @@ -85,18 +86,18 @@ def test_bins_from_intervalindex(self): def test_bins_not_monotonic(self): data = [.2, 1.4, 2.5, 6.2, 9.7, 2.1] - self.assertRaises(ValueError, cut, data, [0.1, 1.5, 1, 10]) + pytest.raises(ValueError, cut, data, [0.1, 1.5, 1, 10]) def test_wrong_num_labels(self): data = [.2, 1.4, 2.5, 6.2, 9.7, 2.1] - self.assertRaises(ValueError, cut, data, [0, 1, 10], - labels=['foo', 'bar', 'baz']) + pytest.raises(ValueError, cut, data, [0, 1, 10], + labels=['foo', 'bar', 'baz']) def test_cut_corner(self): # h3h - self.assertRaises(ValueError, cut, [], 2) + pytest.raises(ValueError, cut, [], 2) - self.assertRaises(ValueError, cut, [1, 2, 3], 0.5) + pytest.raises(ValueError, cut, [1, 2, 3], 0.5) def test_cut_out_of_range_more(self): # #1511 @@ -326,11 +327,11 @@ def test_qcut_duplicates_bin(self): result = qcut(values, 3, duplicates='drop') tm.assert_index_equal(result.categories, expected) - self.assertRaises(ValueError, qcut, values, 3) - self.assertRaises(ValueError, qcut, values, 3, duplicates='raise') + pytest.raises(ValueError, qcut, values, 3) + pytest.raises(ValueError, qcut, values, 3, duplicates='raise') # invalid - self.assertRaises(ValueError, qcut, values, 3, duplicates='foo') + pytest.raises(ValueError, qcut, values, 3, duplicates='foo') def test_single_quantile(self): # issue 15431 @@ -489,7 +490,7 @@ def test_datetime_nan(self): def f(): cut(date_range('20130101', periods=3), bins=[0, 2, 4]) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) result = cut(date_range('20130102', periods=5), bins=date_range('20130101', periods=2)) diff --git a/pandas/tests/reshape/test_union_categoricals.py b/pandas/tests/reshape/test_union_categoricals.py index f9224d0126f6c..1c67b13a9c1c9 100644 --- a/pandas/tests/reshape/test_union_categoricals.py +++ b/pandas/tests/reshape/test_union_categoricals.py @@ -1,3 +1,5 @@ +import pytest + import numpy as np import pandas as pd from pandas import Categorical, Series, CategoricalIndex @@ -265,7 +267,7 @@ def test_union_categoricals_sort(self): c1 = Categorical(['b', 'a'], categories=['b', 'a', 'c'], ordered=True) c2 = Categorical(['a', 'c'], categories=['b', 'a', 'c'], ordered=True) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): union_categoricals([c1, c2], sort_categories=True) def test_union_categoricals_sort_false(self): @@ -335,5 +337,5 @@ def test_union_categorical_unwrap(self): result = union_categoricals([c1, c2]) tm.assert_categorical_equal(result, expected) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): union_categoricals([c1, ['a', 'b', 'c']]) diff --git a/pandas/tests/scalar/test_interval.py b/pandas/tests/scalar/test_interval.py index 63e57fb472861..717ef38a5b447 100644 --- a/pandas/tests/scalar/test_interval.py +++ b/pandas/tests/scalar/test_interval.py @@ -29,7 +29,7 @@ def test_contains(self): self.assertIn(0.5, self.interval) self.assertIn(1, self.interval) self.assertNotIn(0, self.interval) - self.assertRaises(TypeError, lambda: self.interval in self.interval) + pytest.raises(TypeError, lambda: self.interval in self.interval) interval = Interval(0, 1, closed='both') self.assertIn(0, interval) diff --git a/pandas/tests/scalar/test_period.py b/pandas/tests/scalar/test_period.py index 4978b801c741b..50c8bcbb68fcb 100644 --- a/pandas/tests/scalar/test_period.py +++ b/pandas/tests/scalar/test_period.py @@ -1,3 +1,5 @@ +import pytest + import numpy as np from datetime import datetime, date, timedelta @@ -293,7 +295,7 @@ def test_construction(self): i4 = Period('2005', freq='M') i5 = Period('2005', freq='m') - self.assertRaises(ValueError, i1.__ne__, i4) + pytest.raises(ValueError, i1.__ne__, i4) self.assertEqual(i4, i5) i1 = Period.now('Q') @@ -332,9 +334,9 @@ def test_construction(self): freq='U') self.assertEqual(i1, expected) - self.assertRaises(ValueError, Period, ordinal=200701) + pytest.raises(ValueError, Period, ordinal=200701) - self.assertRaises(ValueError, Period, '2007-1-1', freq='X') + pytest.raises(ValueError, Period, '2007-1-1', freq='X') def test_construction_bday(self): @@ -493,9 +495,9 @@ def test_period_constructor_offsets(self): freq='U') self.assertEqual(i1, expected) - self.assertRaises(ValueError, Period, ordinal=200701) + pytest.raises(ValueError, Period, ordinal=200701) - self.assertRaises(ValueError, Period, '2007-1-1', freq='X') + pytest.raises(ValueError, Period, '2007-1-1', freq='X') def test_freq_str(self): i1 = Period('1982', freq='Min') @@ -572,7 +574,7 @@ def test_sub_delta(self): result = left - right self.assertEqual(result, 4) - with self.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): left - Period('2007-01', freq='M') def test_to_timestamp(self): @@ -851,13 +853,13 @@ def test_constructor_corner(self): expected = Period('2007-01', freq='2M') self.assertEqual(Period(year=2007, month=1, freq='2M'), expected) - self.assertRaises(ValueError, Period, datetime.now()) - self.assertRaises(ValueError, Period, datetime.now().date()) - self.assertRaises(ValueError, Period, 1.6, freq='D') - self.assertRaises(ValueError, Period, ordinal=1.6, freq='D') - self.assertRaises(ValueError, Period, ordinal=2, value=1, freq='D') + pytest.raises(ValueError, Period, datetime.now()) + pytest.raises(ValueError, Period, datetime.now().date()) + pytest.raises(ValueError, Period, 1.6, freq='D') + pytest.raises(ValueError, Period, ordinal=1.6, freq='D') + pytest.raises(ValueError, Period, ordinal=2, value=1, freq='D') self.assertIs(Period(None), pd.NaT) - self.assertRaises(ValueError, Period, month=1) + pytest.raises(ValueError, Period, month=1) p = Period('2007-01-01', freq='D') @@ -888,9 +890,9 @@ def test_constructor_infer_freq(self): self.assertEqual(p.freq, 'U') def test_badinput(self): - self.assertRaises(ValueError, Period, '-2000', 'A') - self.assertRaises(tslib.DateParseError, Period, '0', 'A') - self.assertRaises(tslib.DateParseError, Period, '1/1/-2000', 'A') + pytest.raises(ValueError, Period, '-2000', 'A') + pytest.raises(tslib.DateParseError, Period, '0', 'A') + pytest.raises(tslib.DateParseError, Period, '1/1/-2000', 'A') def test_multiples(self): result1 = Period('1989', freq='2A') @@ -916,11 +918,11 @@ def test_round_trip(self): class TestPeriodField(tm.TestCase): def test_get_period_field_raises_on_out_of_range(self): - self.assertRaises(ValueError, libperiod.get_period_field, -1, 0, 0) + pytest.raises(ValueError, libperiod.get_period_field, -1, 0, 0) def test_get_period_field_array_raises_on_out_of_range(self): - self.assertRaises(ValueError, libperiod.get_period_field_arr, -1, - np.empty(1), 0) + pytest.raises(ValueError, libperiod.get_period_field_arr, -1, + np.empty(1), 0) class TestComparisons(tm.TestCase): @@ -936,7 +938,7 @@ def test_equal(self): self.assertEqual(self.january1, self.january2) def test_equal_Raises_Value(self): - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): self.january1 == self.day def test_notEqual(self): @@ -947,43 +949,43 @@ def test_greater(self): self.assertTrue(self.february > self.january1) def test_greater_Raises_Value(self): - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): self.january1 > self.day def test_greater_Raises_Type(self): - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): self.january1 > 1 def test_greaterEqual(self): self.assertTrue(self.january1 >= self.january2) def test_greaterEqual_Raises_Value(self): - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): self.january1 >= self.day - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): print(self.january1 >= 1) def test_smallerEqual(self): self.assertTrue(self.january1 <= self.january2) def test_smallerEqual_Raises_Value(self): - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): self.january1 <= self.day def test_smallerEqual_Raises_Type(self): - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): self.january1 <= 1 def test_smaller(self): self.assertTrue(self.january1 < self.february) def test_smaller_Raises_Value(self): - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): self.january1 < self.day def test_smaller_Raises_Type(self): - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): self.january1 < 1 def test_sort(self): @@ -1062,14 +1064,14 @@ def test_add_offset(self): for o in [offsets.YearBegin(2), offsets.MonthBegin(1), offsets.Minute(), np.timedelta64(365, 'D'), timedelta(365)]: - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): p + o if isinstance(o, np.timedelta64): - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): o + p else: - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): o + p for freq in ['M', '2M', '3M']: @@ -1085,14 +1087,14 @@ def test_add_offset(self): for o in [offsets.YearBegin(2), offsets.MonthBegin(1), offsets.Minute(), np.timedelta64(365, 'D'), timedelta(365)]: - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): p + o if isinstance(o, np.timedelta64): - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): o + p else: - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): o + p # freq is Tick @@ -1109,12 +1111,12 @@ def test_add_offset(self): exp = Period('2011-04-03', freq=freq) self.assertEqual(p + np.timedelta64(2, 'D'), exp) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): np.timedelta64(2, 'D') + p exp = Period('2011-04-02', freq=freq) self.assertEqual(p + np.timedelta64(3600 * 24, 's'), exp) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): np.timedelta64(3600 * 24, 's') + p exp = Period('2011-03-30', freq=freq) @@ -1128,14 +1130,14 @@ def test_add_offset(self): for o in [offsets.YearBegin(2), offsets.MonthBegin(1), offsets.Minute(), np.timedelta64(4, 'h'), timedelta(hours=23)]: - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): p + o if isinstance(o, np.timedelta64): - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): o + p else: - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): o + p for freq in ['H', '2H', '3H']: @@ -1151,12 +1153,12 @@ def test_add_offset(self): exp = Period('2011-04-01 12:00', freq=freq) self.assertEqual(p + np.timedelta64(3, 'h'), exp) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): np.timedelta64(3, 'h') + p exp = Period('2011-04-01 10:00', freq=freq) self.assertEqual(p + np.timedelta64(3600, 's'), exp) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): np.timedelta64(3600, 's') + p exp = Period('2011-04-01 11:00', freq=freq) @@ -1170,14 +1172,14 @@ def test_add_offset(self): for o in [offsets.YearBegin(2), offsets.MonthBegin(1), offsets.Minute(), np.timedelta64(3200, 's'), timedelta(hours=23, minutes=30)]: - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): p + o if isinstance(o, np.timedelta64): - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): o + p else: - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): o + p def test_add_offset_nat(self): @@ -1194,7 +1196,7 @@ def test_add_offset_nat(self): self.assertIs(p + o, tslib.NaT) if isinstance(o, np.timedelta64): - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): o + p else: self.assertIs(o + p, tslib.NaT) @@ -1205,7 +1207,7 @@ def test_add_offset_nat(self): self.assertIs(p + o, tslib.NaT) if isinstance(o, np.timedelta64): - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): o + p else: self.assertIs(o + p, tslib.NaT) @@ -1216,7 +1218,7 @@ def test_add_offset_nat(self): self.assertIs(p + o, tslib.NaT) if isinstance(o, np.timedelta64): - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): o + p else: self.assertIs(o + p, tslib.NaT) @@ -1230,7 +1232,7 @@ def test_add_offset_nat(self): self.assertIs(p + o, tslib.NaT) if isinstance(o, np.timedelta64): - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): o + p else: self.assertIs(o + p, tslib.NaT) @@ -1241,7 +1243,7 @@ def test_add_offset_nat(self): self.assertIs(p + o, tslib.NaT) if isinstance(o, np.timedelta64): - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): o + p else: self.assertIs(o + p, tslib.NaT) @@ -1262,7 +1264,7 @@ def test_add_offset_nat(self): self.assertIs(p + o, tslib.NaT) if isinstance(o, np.timedelta64): - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): o + p else: self.assertIs(o + p, tslib.NaT) @@ -1286,7 +1288,7 @@ def test_sub_offset(self): for o in [offsets.YearBegin(2), offsets.MonthBegin(1), offsets.Minute(), np.timedelta64(365, 'D'), timedelta(365)]: - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): p - o for freq in ['M', '2M', '3M']: @@ -1299,7 +1301,7 @@ def test_sub_offset(self): for o in [offsets.YearBegin(2), offsets.MonthBegin(1), offsets.Minute(), np.timedelta64(365, 'D'), timedelta(365)]: - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): p - o # freq is Tick @@ -1321,7 +1323,7 @@ def test_sub_offset(self): for o in [offsets.YearBegin(2), offsets.MonthBegin(1), offsets.Minute(), np.timedelta64(4, 'h'), timedelta(hours=23)]: - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): p - o for freq in ['H', '2H', '3H']: @@ -1342,7 +1344,7 @@ def test_sub_offset(self): for o in [offsets.YearBegin(2), offsets.MonthBegin(1), offsets.Minute(), np.timedelta64(3200, 's'), timedelta(hours=23, minutes=30)]: - with tm.assertRaises(period.IncompatibleFrequency): + with pytest.raises(period.IncompatibleFrequency): p - o def test_sub_offset_nat(self): diff --git a/pandas/tests/scalar/test_timedelta.py b/pandas/tests/scalar/test_timedelta.py index 5b81237c7c000..4cced3e480c78 100644 --- a/pandas/tests/scalar/test_timedelta.py +++ b/pandas/tests/scalar/test_timedelta.py @@ -114,15 +114,15 @@ def test_construction(self): # currently invalid as it has a - on the hhmmdd part (only allowed on # the days) - self.assertRaises(ValueError, - lambda: Timedelta('-10 days -1 h 1.5m 1s 3us')) + pytest.raises(ValueError, + lambda: Timedelta('-10 days -1 h 1.5m 1s 3us')) # only leading neg signs are allowed - self.assertRaises(ValueError, - lambda: Timedelta('10 days -1 h 1.5m 1s 3us')) + pytest.raises(ValueError, + lambda: Timedelta('10 days -1 h 1.5m 1s 3us')) # no units specified - self.assertRaises(ValueError, lambda: Timedelta('3.1415')) + pytest.raises(ValueError, lambda: Timedelta('3.1415')) # invalid construction tm.assertRaisesRegexp(ValueError, "cannot construct a Timedelta", @@ -169,12 +169,12 @@ def test_construction(self): self.assertEqual(to_timedelta(pd.offsets.Hour(2)), Timedelta(u'0 days, 02:00:00')) - self.assertRaises(ValueError, lambda: Timedelta(u'foo bar')) + pytest.raises(ValueError, lambda: Timedelta(u'foo bar')) def test_overflow_on_construction(self): # xref https://github.com/statsmodels/statsmodels/issues/3374 value = pd.Timedelta('1day').value * 20169940 - self.assertRaises(OverflowError, pd.Timedelta, value) + pytest.raises(OverflowError, pd.Timedelta, value) def test_total_seconds_scalar(self): # GH 10939 @@ -248,9 +248,9 @@ def check(value): self.assertEqual(rng.microseconds, 0) self.assertEqual(rng.nanoseconds, 0) - self.assertRaises(AttributeError, lambda: rng.hours) - self.assertRaises(AttributeError, lambda: rng.minutes) - self.assertRaises(AttributeError, lambda: rng.milliseconds) + pytest.raises(AttributeError, lambda: rng.hours) + pytest.raises(AttributeError, lambda: rng.minutes) + pytest.raises(AttributeError, lambda: rng.milliseconds) # GH 10050 check(rng.days) @@ -270,9 +270,9 @@ def check(value): self.assertEqual(rng.seconds, 10 * 3600 + 11 * 60 + 12) self.assertEqual(rng.microseconds, 100 * 1000 + 123) self.assertEqual(rng.nanoseconds, 456) - self.assertRaises(AttributeError, lambda: rng.hours) - self.assertRaises(AttributeError, lambda: rng.minutes) - self.assertRaises(AttributeError, lambda: rng.milliseconds) + pytest.raises(AttributeError, lambda: rng.hours) + pytest.raises(AttributeError, lambda: rng.minutes) + pytest.raises(AttributeError, lambda: rng.milliseconds) # components tup = pd.to_timedelta(-1, 'us').components @@ -394,7 +394,7 @@ def test_round(self): # invalid for freq in ['Y', 'M', 'foobar']: - self.assertRaises(ValueError, lambda: t1.round(freq)) + pytest.raises(ValueError, lambda: t1.round(freq)) t1 = timedelta_range('1 days', periods=3, freq='1 min 2 s 3 us') t2 = -1 * t1 @@ -443,7 +443,7 @@ def test_round(self): # invalid for freq in ['Y', 'M', 'foobar']: - self.assertRaises(ValueError, lambda: t1.round(freq)) + pytest.raises(ValueError, lambda: t1.round(freq)) def test_contains(self): # Checking for any NaT-like objects @@ -505,8 +505,8 @@ def conv(v): self.assertEqual(ct(' - 10000D '), -conv(np.timedelta64(10000, 'D'))) # invalid - self.assertRaises(ValueError, ct, '1foo') - self.assertRaises(ValueError, ct, 'foo') + pytest.raises(ValueError, ct, '1foo') + pytest.raises(ValueError, ct, 'foo') def test_full_format_converters(self): def conv(v): @@ -534,7 +534,7 @@ def conv(v): d1 + np.timedelta64(1000 * (6 * 3600 + 1) + 10, 'ms'))) # invalid - self.assertRaises(ValueError, ct, '- 1days, 00') + pytest.raises(ValueError, ct, '- 1days, 00') def test_overflow(self): # GH 9442 @@ -552,9 +552,9 @@ def test_overflow(self): 1000)) # sum - self.assertRaises(ValueError, lambda: (s - s.min()).sum()) + pytest.raises(ValueError, lambda: (s - s.min()).sum()) s1 = s[0:10000] - self.assertRaises(ValueError, lambda: (s1 - s1.min()).sum()) + pytest.raises(ValueError, lambda: (s1 - s1.min()).sum()) s2 = s[0:1000] result = (s2 - s2.min()).sum() @@ -700,10 +700,10 @@ def test_ops_error_str(self): for l, r in [(td, 'a'), ('a', td)]: - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): l + r - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): l > r self.assertFalse(l == r) diff --git a/pandas/tests/scalar/test_timestamp.py b/pandas/tests/scalar/test_timestamp.py index d891032fb1f8e..ae351b9d1cab9 100644 --- a/pandas/tests/scalar/test_timestamp.py +++ b/pandas/tests/scalar/test_timestamp.py @@ -1,6 +1,7 @@ """ test the scalar Timestamp """ import sys +import pytest import operator import calendar import numpy as np @@ -178,15 +179,15 @@ def test_constructor_invalid(self): def test_constructor_positional(self): # GH 10758 - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): Timestamp(2000, 1) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): Timestamp(2000, 0, 1) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): Timestamp(2000, 13, 1) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): Timestamp(2000, 1, 0) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): Timestamp(2000, 1, 32) # GH 11630 @@ -200,15 +201,15 @@ def test_constructor_positional(self): def test_constructor_keyword(self): # GH 10758 - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): Timestamp(year=2000, month=1) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): Timestamp(year=2000, month=0, day=1) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): Timestamp(year=2000, month=13, day=1) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): Timestamp(year=2000, month=1, day=0) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): Timestamp(year=2000, month=1, day=32) self.assertEqual( @@ -351,7 +352,7 @@ def test_bounds_with_different_units(self): for date_string in out_of_bounds_dates: for unit in time_units: - self.assertRaises(ValueError, Timestamp, np.datetime64( + pytest.raises(ValueError, Timestamp, np.datetime64( date_string, dtype='M8[%s]' % unit)) in_bounds_dates = ('1677-09-23', '2262-04-11', ) @@ -388,8 +389,8 @@ def test_tz_localize_ambiguous(self): rng = date_range('2014-11-02', periods=3, freq='H', tz='US/Eastern') self.assertEqual(rng[1], ts_dst) self.assertEqual(rng[2], ts_no_dst) - self.assertRaises(ValueError, ts.tz_localize, 'US/Eastern', - ambiguous='infer') + pytest.raises(ValueError, ts.tz_localize, 'US/Eastern', + ambiguous='infer') # GH 8025 with tm.assertRaisesRegexp(TypeError, @@ -411,10 +412,10 @@ def test_tz_localize_nonexistent(self): 'Europe/Paris', 'Europe/Belgrade'] for t, tz in zip(times, timezones): ts = Timestamp(t) - self.assertRaises(NonExistentTimeError, ts.tz_localize, - tz) - self.assertRaises(NonExistentTimeError, ts.tz_localize, - tz, errors='raise') + pytest.raises(NonExistentTimeError, ts.tz_localize, + tz) + pytest.raises(NonExistentTimeError, ts.tz_localize, + tz, errors='raise') self.assertIs(ts.tz_localize(tz, errors='coerce'), NaT) @@ -422,8 +423,8 @@ def test_tz_localize_errors_ambiguous(self): # See issue 13057 from pytz.exceptions import AmbiguousTimeError ts = Timestamp('2015-11-1 01:00') - self.assertRaises(AmbiguousTimeError, - ts.tz_localize, 'US/Pacific', errors='coerce') + pytest.raises(AmbiguousTimeError, + ts.tz_localize, 'US/Pacific', errors='coerce') def test_tz_localize_roundtrip(self): for tz in ['UTC', 'Asia/Tokyo', 'US/Eastern', 'dateutil/US/Pacific']: @@ -433,7 +434,7 @@ def test_tz_localize_roundtrip(self): localized = ts.tz_localize(tz) self.assertEqual(localized, Timestamp(t, tz=tz)) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): localized.tz_localize(tz) reset = localized.tz_localize(None) @@ -466,10 +467,10 @@ def test_barely_oob_dts(self): Timestamp(max_ts_us) # One us less than the minimum is an error - self.assertRaises(ValueError, Timestamp, min_ts_us - one_us) + pytest.raises(ValueError, Timestamp, min_ts_us - one_us) # One us more than the maximum is an error - self.assertRaises(ValueError, Timestamp, max_ts_us + one_us) + pytest.raises(ValueError, Timestamp, max_ts_us + one_us) def test_utc_z_designator(self): self.assertEqual(get_timezone( @@ -534,7 +535,7 @@ def check(value, equal): check(ts.hour, 9) check(ts.minute, 6) check(ts.second, 3) - self.assertRaises(AttributeError, lambda: ts.millisecond) + pytest.raises(AttributeError, lambda: ts.millisecond) check(ts.microsecond, 100) check(ts.nanosecond, 1) check(ts.dayofweek, 6) @@ -552,7 +553,7 @@ def check(value, equal): check(ts.hour, 23) check(ts.minute, 59) check(ts.second, 0) - self.assertRaises(AttributeError, lambda: ts.millisecond) + pytest.raises(AttributeError, lambda: ts.millisecond) check(ts.microsecond, 0) check(ts.nanosecond, 0) check(ts.dayofweek, 2) @@ -675,7 +676,7 @@ def test_round(self): # invalid for freq in ['Y', 'M', 'foobar']: - self.assertRaises(ValueError, lambda: dti.round(freq)) + pytest.raises(ValueError, lambda: dti.round(freq)) # GH 14440 & 15578 result = Timestamp('2016-10-17 12:00:00.0015').round('ms') @@ -920,18 +921,18 @@ def test_cant_compare_tz_naive_w_aware(self): a = Timestamp('3/12/2012') b = Timestamp('3/12/2012', tz='utc') - self.assertRaises(Exception, a.__eq__, b) - self.assertRaises(Exception, a.__ne__, b) - self.assertRaises(Exception, a.__lt__, b) - self.assertRaises(Exception, a.__gt__, b) - self.assertRaises(Exception, b.__eq__, a) - self.assertRaises(Exception, b.__ne__, a) - self.assertRaises(Exception, b.__lt__, a) - self.assertRaises(Exception, b.__gt__, a) + pytest.raises(Exception, a.__eq__, b) + pytest.raises(Exception, a.__ne__, b) + pytest.raises(Exception, a.__lt__, b) + pytest.raises(Exception, a.__gt__, b) + pytest.raises(Exception, b.__eq__, a) + pytest.raises(Exception, b.__ne__, a) + pytest.raises(Exception, b.__lt__, a) + pytest.raises(Exception, b.__gt__, a) if sys.version_info < (3, 3): - self.assertRaises(Exception, a.__eq__, b.to_pydatetime()) - self.assertRaises(Exception, a.to_pydatetime().__eq__, b) + pytest.raises(Exception, a.__eq__, b.to_pydatetime()) + pytest.raises(Exception, a.to_pydatetime().__eq__, b) else: self.assertFalse(a == b.to_pydatetime()) self.assertFalse(a.to_pydatetime() == b) @@ -943,18 +944,18 @@ def test_cant_compare_tz_naive_w_aware_explicit_pytz(self): a = Timestamp('3/12/2012') b = Timestamp('3/12/2012', tz=utc) - self.assertRaises(Exception, a.__eq__, b) - self.assertRaises(Exception, a.__ne__, b) - self.assertRaises(Exception, a.__lt__, b) - self.assertRaises(Exception, a.__gt__, b) - self.assertRaises(Exception, b.__eq__, a) - self.assertRaises(Exception, b.__ne__, a) - self.assertRaises(Exception, b.__lt__, a) - self.assertRaises(Exception, b.__gt__, a) + pytest.raises(Exception, a.__eq__, b) + pytest.raises(Exception, a.__ne__, b) + pytest.raises(Exception, a.__lt__, b) + pytest.raises(Exception, a.__gt__, b) + pytest.raises(Exception, b.__eq__, a) + pytest.raises(Exception, b.__ne__, a) + pytest.raises(Exception, b.__lt__, a) + pytest.raises(Exception, b.__gt__, a) if sys.version_info < (3, 3): - self.assertRaises(Exception, a.__eq__, b.to_pydatetime()) - self.assertRaises(Exception, a.to_pydatetime().__eq__, b) + pytest.raises(Exception, a.__eq__, b.to_pydatetime()) + pytest.raises(Exception, a.to_pydatetime().__eq__, b) else: self.assertFalse(a == b.to_pydatetime()) self.assertFalse(a.to_pydatetime() == b) @@ -967,18 +968,18 @@ def test_cant_compare_tz_naive_w_aware_dateutil(self): a = Timestamp('3/12/2012') b = Timestamp('3/12/2012', tz=utc) - self.assertRaises(Exception, a.__eq__, b) - self.assertRaises(Exception, a.__ne__, b) - self.assertRaises(Exception, a.__lt__, b) - self.assertRaises(Exception, a.__gt__, b) - self.assertRaises(Exception, b.__eq__, a) - self.assertRaises(Exception, b.__ne__, a) - self.assertRaises(Exception, b.__lt__, a) - self.assertRaises(Exception, b.__gt__, a) + pytest.raises(Exception, a.__eq__, b) + pytest.raises(Exception, a.__ne__, b) + pytest.raises(Exception, a.__lt__, b) + pytest.raises(Exception, a.__gt__, b) + pytest.raises(Exception, b.__eq__, a) + pytest.raises(Exception, b.__ne__, a) + pytest.raises(Exception, b.__lt__, a) + pytest.raises(Exception, b.__gt__, a) if sys.version_info < (3, 3): - self.assertRaises(Exception, a.__eq__, b.to_pydatetime()) - self.assertRaises(Exception, a.to_pydatetime().__eq__, b) + pytest.raises(Exception, a.__eq__, b.to_pydatetime()) + pytest.raises(Exception, a.to_pydatetime().__eq__, b) else: self.assertFalse(a == b.to_pydatetime()) self.assertFalse(a.to_pydatetime() == b) @@ -1007,11 +1008,11 @@ def test_frequency_misc(self): expected = offsets.Minute(5) self.assertEqual(result, expected) - self.assertRaises(ValueError, frequencies.get_freq_code, (5, 'baz')) + pytest.raises(ValueError, frequencies.get_freq_code, (5, 'baz')) - self.assertRaises(ValueError, frequencies.to_offset, '100foo') + pytest.raises(ValueError, frequencies.to_offset, '100foo') - self.assertRaises(ValueError, frequencies.to_offset, ('', '')) + pytest.raises(ValueError, frequencies.to_offset, ('', '')) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = frequencies.get_standard_freq(offsets.Hour()) @@ -1349,12 +1350,12 @@ def test_timestamp_fields(self): self.assertEqual(idx.freqstr, Timestamp(idx[-1], idx.freq).freqstr) def test_timestamp_date_out_of_range(self): - self.assertRaises(ValueError, Timestamp, '1676-01-01') - self.assertRaises(ValueError, Timestamp, '2263-01-01') + pytest.raises(ValueError, Timestamp, '1676-01-01') + pytest.raises(ValueError, Timestamp, '2263-01-01') # 1475 - self.assertRaises(ValueError, DatetimeIndex, ['1400-01-01']) - self.assertRaises(ValueError, DatetimeIndex, [datetime(1400, 1, 1)]) + pytest.raises(ValueError, DatetimeIndex, ['1400-01-01']) + pytest.raises(ValueError, DatetimeIndex, [datetime(1400, 1, 1)]) def test_timestamp_repr(self): # pre-1900 diff --git a/pandas/tests/series/test_alter_axes.py b/pandas/tests/series/test_alter_axes.py index 5cac86560dba2..a7b8d285bbe54 100644 --- a/pandas/tests/series/test_alter_axes.py +++ b/pandas/tests/series/test_alter_axes.py @@ -1,6 +1,8 @@ # coding=utf-8 # pylint: disable-msg=E1101,W0612 +import pytest + from datetime import datetime import numpy as np @@ -21,12 +23,12 @@ class TestSeriesAlterAxes(TestData, tm.TestCase): def test_setindex(self): # wrong type series = self.series.copy() - self.assertRaises(TypeError, setattr, series, 'index', None) + pytest.raises(TypeError, setattr, series, 'index', None) # wrong length series = self.series.copy() - self.assertRaises(Exception, setattr, series, 'index', - np.arange(len(series) - 1)) + pytest.raises(Exception, setattr, series, 'index', + np.arange(len(series) - 1)) # works series = self.series.copy() diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index 666fca2d791fe..eaa88da94ccd2 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -500,7 +500,7 @@ def testit(): # idxmax, idxmin, min, and max are valid for dates if name not in ['max', 'min']: ds = Series(date_range('1/1/2001', periods=10)) - self.assertRaises(TypeError, f, ds) + pytest.raises(TypeError, f, ds) # skipna or no self.assertTrue(notnull(f(self.series))) @@ -543,10 +543,10 @@ def testit(): # check on string data if name not in ['sum', 'min', 'max']: - self.assertRaises(TypeError, f, Series(list('abc'))) + pytest.raises(TypeError, f, Series(list('abc'))) # Invalid axis. - self.assertRaises(ValueError, f, self.series, axis=1) + pytest.raises(ValueError, f, self.series, axis=1) # Unimplemented numeric_only parameter. if 'numeric_only' in compat.signature(f).args: @@ -669,12 +669,12 @@ def test_all_any_params(self): assert_series_equal(s.any(level=0), Series([False, True, True])) # bool_only is not implemented with level option. - self.assertRaises(NotImplementedError, s.any, bool_only=True, level=0) - self.assertRaises(NotImplementedError, s.all, bool_only=True, level=0) + pytest.raises(NotImplementedError, s.any, bool_only=True, level=0) + pytest.raises(NotImplementedError, s.all, bool_only=True, level=0) # bool_only is not implemented alone. - self.assertRaises(NotImplementedError, s.any, bool_only=True) - self.assertRaises(NotImplementedError, s.all, bool_only=True) + pytest.raises(NotImplementedError, s.any, bool_only=True) + pytest.raises(NotImplementedError, s.all, bool_only=True) def test_modulo(self): with np.errstate(all='ignore'): @@ -866,8 +866,8 @@ def test_dot(self): assert_almost_equal(a.dot(b['1']), expected['1']) assert_almost_equal(a.dot(b2['1']), expected['1']) - self.assertRaises(Exception, a.dot, a.values[:3]) - self.assertRaises(ValueError, a.dot, b.T) + pytest.raises(Exception, a.dot, a.values[:3]) + pytest.raises(ValueError, a.dot, b.T) def test_value_counts_nunique(self): @@ -1061,10 +1061,10 @@ def test_isin(self): def test_isin_with_string_scalar(self): # GH4763 s = Series(['A', 'B', 'C', 'a', 'B', 'B', 'A', 'C']) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): s.isin('a') - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): s = Series(['aaa', 'b', 'c']) s.isin('aaa') @@ -1263,14 +1263,14 @@ def test_ptp(self): expected = pd.Series([np.nan, np.nan], index=['a', 'b']) tm.assert_series_equal(s.ptp(level=0, skipna=False), expected) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): s.ptp(axis=1) s = pd.Series(['a', 'b', 'c', 'd', 'e']) - with self.assertRaises(TypeError): + with pytest.raises(TypeError): s.ptp() - with self.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): s.ptp(numeric_only=True) def test_empty_timeseries_redections_return_nat(self): diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index bc867cc8e0436..68d8e382ef046 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -1,6 +1,8 @@ # coding=utf-8 # pylint: disable-msg=E1101,W0612 +import pytest + import numpy as np import pandas as pd @@ -148,8 +150,8 @@ def test_tab_completion(self): def test_not_hashable(self): s_empty = Series() s = Series([1]) - self.assertRaises(TypeError, hash, s_empty) - self.assertRaises(TypeError, hash, s) + pytest.raises(TypeError, hash, s_empty) + pytest.raises(TypeError, hash, s) def test_contains(self): tm.assert_contains_all(self.ts.index, self.ts) @@ -218,7 +220,7 @@ def test_iteritems(self): def test_raise_on_info(self): s = Series(np.random.randn(10)) - with tm.assertRaises(AttributeError): + with pytest.raises(AttributeError): s.info() def test_copy(self): diff --git a/pandas/tests/series/test_apply.py b/pandas/tests/series/test_apply.py index ac165bd31ef23..afe46e5dcf480 100644 --- a/pandas/tests/series/test_apply.py +++ b/pandas/tests/series/test_apply.py @@ -1,7 +1,10 @@ # coding=utf-8 # pylint: disable-msg=E1101,W0612 +import pytest + from collections import Counter, defaultdict, OrderedDict + import numpy as np import pandas as pd @@ -204,22 +207,22 @@ def test_transform_and_agg_error(self): # we are trying to transform with an aggregator def f(): self.series.transform(['min', 'max']) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def f(): with np.errstate(all='ignore'): self.series.agg(['sqrt', 'max']) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def f(): with np.errstate(all='ignore'): self.series.transform(['sqrt', 'max']) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def f(): with np.errstate(all='ignore'): self.series.agg({'foo': np.sqrt, 'bar': 'sum'}) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def test_demo(self): # demonstration tests @@ -505,7 +508,7 @@ def test_map_categorical(self): tm.assert_series_equal(result, exp) self.assertEqual(result.dtype, np.object) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): s.map(lambda x: x, na_action='ignore') def test_map_datetimetz(self): @@ -526,7 +529,7 @@ def test_map_datetimetz(self): exp = pd.Series(list(range(24)) + [0], name='XX', dtype=np.int64) tm.assert_series_equal(result, exp) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): s.map(lambda x: x, na_action='ignore') # not vectorized diff --git a/pandas/tests/series/test_asof.py b/pandas/tests/series/test_asof.py index 82914a99e2f6c..9c1e4626e1736 100644 --- a/pandas/tests/series/test_asof.py +++ b/pandas/tests/series/test_asof.py @@ -1,5 +1,7 @@ # coding=utf-8 +import pytest + import numpy as np from pandas import (offsets, Series, notnull, isnull, date_range, Timestamp) @@ -139,14 +141,14 @@ def test_errors(self): # non-monotonic self.assertFalse(s.index.is_monotonic) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): s.asof(s.index[0]) # subset with Series N = 10 rng = date_range('1/1/1990', periods=N, freq='53s') s = Series(np.random.randn(N), index=rng) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): s.asof(s.index[0], subset='foo') def test_all_nans(self): diff --git a/pandas/tests/series/test_combine_concat.py b/pandas/tests/series/test_combine_concat.py index 57a5fdfa7731d..cc29c45d74c9d 100644 --- a/pandas/tests/series/test_combine_concat.py +++ b/pandas/tests/series/test_combine_concat.py @@ -1,6 +1,8 @@ # coding=utf-8 # pylint: disable-msg=E1101,W0612 +import pytest + from datetime import datetime from numpy import nan @@ -28,8 +30,8 @@ def test_append(self): else: self.fail("orphaned index!") - self.assertRaises(ValueError, self.ts.append, self.ts, - verify_integrity=True) + pytest.raises(ValueError, self.ts.append, self.ts, + verify_integrity=True) def test_append_many(self): pieces = [self.ts[:5], self.ts[5:10], self.ts[10:]] diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 151ad1863851b..e02698f96ca49 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -1,6 +1,8 @@ # coding=utf-8 # pylint: disable-msg=E1101,W0612 +import pytest + from datetime import datetime, timedelta from numpy import nan @@ -57,8 +59,8 @@ def test_constructor(self): self.assertFalse(self.empty.index.is_all_dates) self.assertFalse(Series({}).index.is_all_dates) - self.assertRaises(Exception, Series, np.random.randn(3, 3), - index=np.arange(3)) + pytest.raises(Exception, Series, np.random.randn(3, 3), + index=np.arange(3)) mixed.name = 'Series' rs = Series(mixed).name @@ -67,7 +69,7 @@ def test_constructor(self): # raise on MultiIndex GH4187 m = MultiIndex.from_arrays([[1, 2], [3, 4]]) - self.assertRaises(NotImplementedError, Series, m) + pytest.raises(NotImplementedError, Series, m) def test_constructor_empty(self): empty = Series() @@ -138,7 +140,7 @@ def test_constructor_categorical(self): tm.assert_categorical_equal(res.values, cat) # GH12574 - self.assertRaises( + pytest.raises( ValueError, lambda: Series(pd.Categorical([1, 2, 3]), dtype='int64')) cat = Series(pd.Categorical([1, 2, 3]), dtype='category') @@ -291,7 +293,7 @@ def test_constructor_pass_nan_nat(self): tm.assert_series_equal(Series(np.array([np.nan, pd.NaT])), exp) def test_constructor_cast(self): - self.assertRaises(ValueError, Series, ['a', 'b', 'c'], dtype=float) + pytest.raises(ValueError, Series, ['a', 'b', 'c'], dtype=float) def test_constructor_dtype_nocast(self): # 1572 @@ -372,13 +374,13 @@ def test_constructor_dtype_datetime64(self): # invalid astypes for t in ['s', 'D', 'us', 'ms']: - self.assertRaises(TypeError, s.astype, 'M8[%s]' % t) + pytest.raises(TypeError, s.astype, 'M8[%s]' % t) # GH3414 related - self.assertRaises(TypeError, lambda x: Series( + pytest.raises(TypeError, lambda x: Series( Series(dates).astype('int') / 1000000, dtype='M8[ms]')) - self.assertRaises(TypeError, - lambda x: Series(dates, dtype='datetime64')) + pytest.raises(TypeError, + lambda x: Series(dates, dtype='datetime64')) # invalid dates can be help as object result = Series([datetime(2, 1, 1)]) @@ -692,9 +694,9 @@ def test_constructor_tuple_of_tuples(self): def test_constructor_set(self): values = set([1, 2, 3, 4, 5]) - self.assertRaises(TypeError, Series, values) + pytest.raises(TypeError, Series, values) values = frozenset(values) - self.assertRaises(TypeError, Series, values) + pytest.raises(TypeError, Series, values) def test_fromDict(self): data = {'a': 0, 'b': 1, 'c': 2, 'd': 3} @@ -781,19 +783,19 @@ def test_constructor_dtype_timedelta64(self): # these are frequency conversion astypes # for t in ['s', 'D', 'us', 'ms']: - # self.assertRaises(TypeError, td.astype, 'm8[%s]' % t) + # pytest.raises(TypeError, td.astype, 'm8[%s]' % t) # valid astype td.astype('int64') # invalid casting - self.assertRaises(TypeError, td.astype, 'int32') + pytest.raises(TypeError, td.astype, 'int32') # this is an invalid casting def f(): Series([timedelta(days=1), 'foo'], dtype='m8[ns]') - self.assertRaises(Exception, f) + pytest.raises(Exception, f) # leave as object here td = Series([timedelta(days=i) for i in range(3)] + ['foo']) @@ -833,7 +835,7 @@ def test_constructor_name_hashable(self): def test_constructor_name_unhashable(self): for n in [['name_list'], np.ones(2), {1: 2}]: for data in [['name_list'], np.ones(2), {1: 2}]: - self.assertRaises(TypeError, Series, data, name=n) + pytest.raises(TypeError, Series, data, name=n) def test_auto_conversion(self): series = Series(list(date_range('1/1/2000', periods=10))) diff --git a/pandas/tests/series/test_datetime_values.py b/pandas/tests/series/test_datetime_values.py index ce82507ce8330..ac3e3a2abbd69 100644 --- a/pandas/tests/series/test_datetime_values.py +++ b/pandas/tests/series/test_datetime_values.py @@ -1,6 +1,8 @@ # coding=utf-8 # pylint: disable-msg=E1101,W0612 +import pytest + from datetime import datetime, date import numpy as np @@ -258,7 +260,7 @@ def get_dir(s): def f(): s.dt.hour[0] = 5 - self.assertRaises(com.SettingWithCopyError, f) + pytest.raises(com.SettingWithCopyError, f) def test_dt_accessor_no_new_attributes(self): # https://github.com/pandas-dev/pandas/issues/10673 diff --git a/pandas/tests/series/test_indexing.py b/pandas/tests/series/test_indexing.py index f1b9aaf1b9e46..1003e84a1a942 100644 --- a/pandas/tests/series/test_indexing.py +++ b/pandas/tests/series/test_indexing.py @@ -1,6 +1,8 @@ # coding=utf-8 # pylint: disable-msg=E1101,W0612 +import pytest + from datetime import datetime, timedelta from numpy import nan @@ -88,7 +90,7 @@ def test_delitem(self): def f(): del s[0] - self.assertRaises(KeyError, f) + pytest.raises(KeyError, f) # only 1 left, del, add, del s = Series(1) @@ -126,8 +128,8 @@ def test_getitem_setitem_ellipsis(self): def test_getitem_negative_out_of_bounds(self): s = Series(tm.rands_array(5, 10), index=tm.rands_array(10, 10)) - self.assertRaises(IndexError, s.__getitem__, -11) - self.assertRaises(IndexError, s.__setitem__, -11, 'foo') + pytest.raises(IndexError, s.__getitem__, -11) + pytest.raises(IndexError, s.__setitem__, -11, 'foo') def test_pop(self): # GH 6600 @@ -156,7 +158,7 @@ def test_getitem_get(self): # missing d = self.ts.index[0] - BDay() - self.assertRaises(KeyError, self.ts.__getitem__, d) + pytest.raises(KeyError, self.ts.__getitem__, d) # None # GH 5652 @@ -260,12 +262,12 @@ def test_getitem_boolean_empty(self): def f(): s[Series([], dtype=bool)] - self.assertRaises(IndexingError, f) + pytest.raises(IndexingError, f) def f(): s[Series([True], dtype=bool)] - self.assertRaises(IndexingError, f) + pytest.raises(IndexingError, f) def test_getitem_generator(self): gen = (x > 0 for x in self.series) @@ -306,8 +308,8 @@ def test_getitem_boolean_object(self): # nans raise exception omask[5:10] = np.nan - self.assertRaises(Exception, s.__getitem__, omask) - self.assertRaises(Exception, s.__setitem__, omask, 5) + pytest.raises(Exception, s.__getitem__, omask) + pytest.raises(Exception, s.__setitem__, omask, 5) def test_getitem_setitem_boolean_corner(self): ts = self.ts @@ -315,13 +317,13 @@ def test_getitem_setitem_boolean_corner(self): # these used to raise...?? - self.assertRaises(Exception, ts.__getitem__, mask_shifted) - self.assertRaises(Exception, ts.__setitem__, mask_shifted, 1) + pytest.raises(Exception, ts.__getitem__, mask_shifted) + pytest.raises(Exception, ts.__setitem__, mask_shifted, 1) # ts[mask_shifted] # ts[mask_shifted] = 1 - self.assertRaises(Exception, ts.loc.__getitem__, mask_shifted) - self.assertRaises(Exception, ts.loc.__setitem__, mask_shifted, 1) + pytest.raises(Exception, ts.loc.__getitem__, mask_shifted) + pytest.raises(Exception, ts.loc.__setitem__, mask_shifted, 1) # ts.loc[mask_shifted] # ts.loc[mask_shifted] = 2 @@ -545,11 +547,11 @@ def test_getitem_median_slice_bug(self): def test_getitem_out_of_bounds(self): # don't segfault, GH #495 - self.assertRaises(IndexError, self.ts.__getitem__, len(self.ts)) + pytest.raises(IndexError, self.ts.__getitem__, len(self.ts)) # GH #917 s = Series([]) - self.assertRaises(IndexError, s.__getitem__, -1) + pytest.raises(IndexError, s.__getitem__, -1) def test_getitem_setitem_integers(self): # caused bug without test @@ -565,8 +567,8 @@ def test_getitem_box_float64(self): def test_getitem_ambiguous_keyerror(self): s = Series(lrange(10), index=lrange(0, 20, 2)) - self.assertRaises(KeyError, s.__getitem__, 1) - self.assertRaises(KeyError, s.loc.__getitem__, 1) + pytest.raises(KeyError, s.__getitem__, 1) + pytest.raises(KeyError, s.loc.__getitem__, 1) def test_getitem_unordered_dup(self): obj = Series(lrange(5), index=['c', 'a', 'a', 'b', 'b']) @@ -592,7 +594,7 @@ def test_getitem_dataframe(self): rng = list(range(10)) s = pd.Series(10, index=rng) df = pd.DataFrame(rng, index=rng) - self.assertRaises(TypeError, s.__getitem__, df > 5) + pytest.raises(TypeError, s.__getitem__, df > 5) def test_getitem_callable(self): # GH 12533 @@ -674,15 +676,15 @@ def test_slice_can_reorder_not_uniquely_indexed(self): def test_slice_float_get_set(self): - self.assertRaises(TypeError, lambda: self.ts[4.0:10.0]) + pytest.raises(TypeError, lambda: self.ts[4.0:10.0]) def f(): self.ts[4.0:10.0] = 0 - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) - self.assertRaises(TypeError, self.ts.__getitem__, slice(4.5, 10.0)) - self.assertRaises(TypeError, self.ts.__setitem__, slice(4.5, 10.0), 0) + pytest.raises(TypeError, self.ts.__getitem__, slice(4.5, 10.0)) + pytest.raises(TypeError, self.ts.__setitem__, slice(4.5, 10.0), 0) def test_slice_floats2(self): s = Series(np.random.rand(10), index=np.arange(10, 20, dtype=float)) @@ -819,10 +821,10 @@ def test_basic_getitem_setitem_corner(self): assert_series_equal(result, expected) # OK - self.assertRaises(Exception, self.ts.__getitem__, - [5, slice(None, None)]) - self.assertRaises(Exception, self.ts.__setitem__, - [5, slice(None, None)], 2) + pytest.raises(Exception, self.ts.__getitem__, + [5, slice(None, None)]) + pytest.raises(Exception, self.ts.__setitem__, + [5, slice(None, None)], 2) def test_basic_getitem_with_labels(self): indices = self.ts.index[[5, 10, 15]] @@ -893,8 +895,8 @@ def test_basic_setitem_with_labels(self): inds_notfound = [0, 4, 5, 6] arr_inds_notfound = np.array([0, 4, 5, 6]) - self.assertRaises(Exception, s.__setitem__, inds_notfound, 0) - self.assertRaises(Exception, s.__setitem__, arr_inds_notfound, 0) + pytest.raises(Exception, s.__setitem__, inds_notfound, 0) + pytest.raises(Exception, s.__setitem__, arr_inds_notfound, 0) # GH12089 # with tz for values @@ -940,8 +942,8 @@ def test_loc_getitem_not_monotonic(self): ts2 = self.ts[::2][[1, 2, 0]] - self.assertRaises(KeyError, ts2.loc.__getitem__, slice(d1, d2)) - self.assertRaises(KeyError, ts2.loc.__setitem__, slice(d1, d2), 0) + pytest.raises(KeyError, ts2.loc.__getitem__, slice(d1, d2)) + pytest.raises(KeyError, ts2.loc.__setitem__, slice(d1, d2), 0) def test_loc_getitem_setitem_integer_slice_keyerrors(self): s = Series(np.random.randn(10), index=lrange(0, 20, 2)) @@ -965,8 +967,8 @@ def test_loc_getitem_setitem_integer_slice_keyerrors(self): # non-monotonic, raise KeyError s2 = s.iloc[lrange(5) + lrange(5, 10)[::-1]] - self.assertRaises(KeyError, s2.loc.__getitem__, slice(3, 11)) - self.assertRaises(KeyError, s2.loc.__setitem__, slice(3, 11), 0) + pytest.raises(KeyError, s2.loc.__getitem__, slice(3, 11)) + pytest.raises(KeyError, s2.loc.__setitem__, slice(3, 11), 0) def test_loc_getitem_iterator(self): idx = iter(self.series.index[:10]) @@ -1084,8 +1086,8 @@ def test_where(self): rs = s2.where(cond[:3], -s2) assert_series_equal(rs, expected) - self.assertRaises(ValueError, s.where, 1) - self.assertRaises(ValueError, s.where, cond[:3].values, -s) + pytest.raises(ValueError, s.where, 1) + pytest.raises(ValueError, s.where, cond[:3].values, -s) # GH 2745 s = Series([1, 2]) @@ -1094,10 +1096,10 @@ def test_where(self): assert_series_equal(s, expected) # failures - self.assertRaises(ValueError, s.__setitem__, tuple([[[True, False]]]), - [0, 2, 3]) - self.assertRaises(ValueError, s.__setitem__, tuple([[[True, False]]]), - []) + pytest.raises(ValueError, s.__setitem__, tuple([[[True, False]]]), + [0, 2, 3]) + pytest.raises(ValueError, s.__setitem__, tuple([[[True, False]]]), + []) # unsafe dtype changes for dtype in [np.int8, np.int16, np.int32, np.int64, np.float16, @@ -1133,7 +1135,7 @@ def test_where(self): s = Series(np.arange(10), dtype=dtype) mask = s < 5 values = [2.5, 3.5, 4.5, 5.5, 6.5] - self.assertRaises(Exception, s.__setitem__, tuple(mask), values) + pytest.raises(Exception, s.__setitem__, tuple(mask), values) # GH3235 s = Series(np.arange(10), dtype='int64') @@ -1155,12 +1157,12 @@ def test_where(self): def f(): s[mask] = [5, 4, 3, 2, 1] - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def f(): s[mask] = [0] * 5 - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # dtype changes s = Series([1, 2, 3, 4]) @@ -1246,7 +1248,7 @@ def test_where_setitem_invalid(self): def f(): s[0:3] = list(range(27)) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) s[0:3] = list(range(3)) expected = Series([0, 1, 2]) @@ -1258,7 +1260,7 @@ def f(): def f(): s[0:4:2] = list(range(27)) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) s = Series(list('abcdef')) s[0:4:2] = list(range(2)) @@ -1271,7 +1273,7 @@ def f(): def f(): s[:-1] = list(range(27)) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) s[-3:-1] = list(range(2)) expected = Series(['a', 'b', 'c', 0, 1, 'f']) @@ -1283,14 +1285,14 @@ def f(): def f(): s[[0, 1, 2]] = list(range(27)) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) s = Series(list('abc')) def f(): s[[0, 1, 2]] = list(range(2)) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # scalar s = Series(list('abc')) @@ -1440,8 +1442,8 @@ def test_mask(self): rs2 = s2.mask(cond[:3], -s2) assert_series_equal(rs, rs2) - self.assertRaises(ValueError, s.mask, 1) - self.assertRaises(ValueError, s.mask, cond[:3].values, -s) + pytest.raises(ValueError, s.mask, 1) + pytest.raises(ValueError, s.mask, cond[:3].values, -s) # dtype changes s = Series([1, 2, 3, 4]) @@ -1562,8 +1564,8 @@ def test_ix_setitem_boolean(self): def test_ix_setitem_corner(self): inds = list(self.series.index[[5, 8, 12]]) self.series.loc[inds] = 5 - self.assertRaises(Exception, self.series.loc.__setitem__, - inds + ['foo'], 5) + pytest.raises(Exception, self.series.loc.__setitem__, + inds + ['foo'], 5) def test_get_set_boolean_different_order(self): ordered = self.series.sort_values() @@ -1604,29 +1606,29 @@ def test_setitem_na(self): def test_basic_indexing(self): s = Series(np.random.randn(5), index=['a', 'b', 'a', 'a', 'b']) - self.assertRaises(IndexError, s.__getitem__, 5) - self.assertRaises(IndexError, s.__setitem__, 5, 0) + pytest.raises(IndexError, s.__getitem__, 5) + pytest.raises(IndexError, s.__setitem__, 5, 0) - self.assertRaises(KeyError, s.__getitem__, 'c') + pytest.raises(KeyError, s.__getitem__, 'c') s = s.sort_index() - self.assertRaises(IndexError, s.__getitem__, 5) - self.assertRaises(IndexError, s.__setitem__, 5, 0) + pytest.raises(IndexError, s.__getitem__, 5) + pytest.raises(IndexError, s.__setitem__, 5, 0) def test_int_indexing(self): s = Series(np.random.randn(6), index=[0, 0, 1, 1, 2, 2]) - self.assertRaises(KeyError, s.__getitem__, 5) + pytest.raises(KeyError, s.__getitem__, 5) - self.assertRaises(KeyError, s.__getitem__, 'c') + pytest.raises(KeyError, s.__getitem__, 'c') # not monotonic s = Series(np.random.randn(6), index=[2, 2, 0, 0, 1, 1]) - self.assertRaises(KeyError, s.__getitem__, 5) + pytest.raises(KeyError, s.__getitem__, 5) - self.assertRaises(KeyError, s.__getitem__, 'c') + pytest.raises(KeyError, s.__getitem__, 'c') def test_datetime_indexing(self): from pandas import date_range @@ -1637,7 +1639,7 @@ def test_datetime_indexing(self): s = Series(len(index), index=index) stamp = Timestamp('1/8/2000') - self.assertRaises(KeyError, s.__getitem__, stamp) + pytest.raises(KeyError, s.__getitem__, stamp) s[stamp] = 0 self.assertEqual(s[stamp], 0) @@ -1645,7 +1647,7 @@ def test_datetime_indexing(self): s = Series(len(index), index=index) s = s[::-1] - self.assertRaises(KeyError, s.__getitem__, stamp) + pytest.raises(KeyError, s.__getitem__, stamp) s[stamp] = 0 self.assertEqual(s[stamp], 0) @@ -1745,8 +1747,8 @@ def test_drop(self): # single string/tuple-like s = Series(range(3), index=list('abc')) - self.assertRaises(ValueError, s.drop, 'bc') - self.assertRaises(ValueError, s.drop, ('a', )) + pytest.raises(ValueError, s.drop, 'bc') + pytest.raises(ValueError, s.drop, ('a', )) # errors='ignore' s = Series(range(3), index=list('abc')) @@ -1757,7 +1759,7 @@ def test_drop(self): assert_series_equal(result, expected) # bad axis - self.assertRaises(ValueError, s.drop, 'one', axis='columns') + pytest.raises(ValueError, s.drop, 'one', axis='columns') # GH 8522 s = Series([2, 3], index=[True, False]) @@ -2000,7 +2002,7 @@ def test_reindex_corner(self): # bad fill method ts = self.ts[::2] - self.assertRaises(Exception, ts.reindex, self.ts.index, method='foo') + pytest.raises(Exception, ts.reindex, self.ts.index, method='foo') def test_reindex_pad(self): @@ -2236,7 +2238,7 @@ def test_setitem_scalar_into_readonly_backing_data(self): series = Series(array) for n in range(len(series)): - with self.assertRaises(ValueError): + with pytest.raises(ValueError): series[n] = 1 self.assertEqual( @@ -2253,7 +2255,7 @@ def test_setitem_slice_into_readonly_backing_data(self): array.flags.writeable = False # make the array immutable series = Series(array) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): series[1:3] = 1 self.assertTrue( @@ -2340,7 +2342,7 @@ def test_duplicate_dates_indexing(self): expected = Series(np.where(mask, 0, ts), index=ts.index) assert_series_equal(cp, expected) - self.assertRaises(KeyError, ts.__getitem__, datetime(2000, 1, 6)) + pytest.raises(KeyError, ts.__getitem__, datetime(2000, 1, 6)) # new index ts[datetime(2000, 1, 6)] = 0 @@ -2501,8 +2503,8 @@ def test_indexing(self): expected = df.loc[[df.index[2]]] # this is a single date, so will raise - self.assertRaises(KeyError, df.__getitem__, '2012-01-02 18:01:02', ) - self.assertRaises(KeyError, df.__getitem__, df.index[2], ) + pytest.raises(KeyError, df.__getitem__, '2012-01-02 18:01:02', ) + pytest.raises(KeyError, df.__getitem__, df.index[2], ) class TestDatetimeIndexing(tm.TestCase): @@ -2526,7 +2528,7 @@ def test_fancy_getitem(self): self.assertEqual(s['2009-1-2'], 48) self.assertEqual(s[datetime(2009, 1, 2)], 48) self.assertEqual(s[lib.Timestamp(datetime(2009, 1, 2))], 48) - self.assertRaises(KeyError, s.__getitem__, '2009-1-3') + pytest.raises(KeyError, s.__getitem__, '2009-1-3') assert_series_equal(s['3/6/2009':'2009-06-05'], s[datetime(2009, 3, 6):datetime(2009, 6, 5)]) diff --git a/pandas/tests/series/test_internals.py b/pandas/tests/series/test_internals.py index 9ca7645e6f974..19170c82953ad 100644 --- a/pandas/tests/series/test_internals.py +++ b/pandas/tests/series/test_internals.py @@ -1,6 +1,8 @@ # coding=utf-8 # pylint: disable-msg=E1101,W0612 +import pytest + from datetime import datetime from numpy import nan @@ -294,7 +296,7 @@ def test_convert(self): def test_convert_no_arg_error(self): s = Series(['1.0', '2']) - self.assertRaises(ValueError, s._convert) + pytest.raises(ValueError, s._convert) def test_convert_preserve_bool(self): s = Series([1, True, 3, 5], dtype=object) diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index dee466bc11a6f..2f7bf6902f5af 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -2,6 +2,8 @@ # pylint: disable-msg=E1101,W0612 import pytz +import pytest + from datetime import timedelta, datetime from distutils.version import LooseVersion @@ -309,14 +311,14 @@ def test_fillna_int(self): def test_fillna_raise(self): s = Series(np.random.randint(-100, 100, 50)) - self.assertRaises(TypeError, s.fillna, [1, 2]) - self.assertRaises(TypeError, s.fillna, (1, 2)) + pytest.raises(TypeError, s.fillna, [1, 2]) + pytest.raises(TypeError, s.fillna, (1, 2)) # related GH 9217, make sure limit is an int and greater than 0 s = Series([1, 2, 3, None]) for limit in [-1, 0, 1., 2.]: for method in ['backfill', 'bfill', 'pad', 'ffill', None]: - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): s.fillna(1, limit=limit, method=method) def test_fillna_nat(self): @@ -382,8 +384,8 @@ def test_fillna(self): exp = Series([0., 1., 5., 3., 4.], index=ts.index) tm.assert_series_equal(ts.fillna(value=5), exp) - self.assertRaises(ValueError, ts.fillna) - self.assertRaises(ValueError, self.ts.fillna, value=0, method='ffill') + pytest.raises(ValueError, ts.fillna) + pytest.raises(ValueError, self.ts.fillna, value=0, method='ffill') # GH 5703 s1 = Series([np.nan]) @@ -520,7 +522,7 @@ def test_dropna_empty(self): self.assertEqual(len(s), 0) # invalid axis - self.assertRaises(ValueError, s.dropna, axis=1) + pytest.raises(ValueError, s.dropna, axis=1) def test_datetime64_tz_dropna(self): # DatetimeBlock @@ -605,7 +607,7 @@ def test_pad_require_monotonicity(self): # neither monotonic increasing or decreasing rng2 = rng[[1, 0, 2]] - self.assertRaises(ValueError, rng2.get_indexer, rng, method='pad') + pytest.raises(ValueError, rng2.get_indexer, rng, method='pad') def test_dropna_preserve_name(self): self.ts[:5] = np.nan @@ -722,7 +724,7 @@ def test_interpolate(self): # Only raises ValueError if there are NaNs. non_ts = self.series.copy() non_ts[0] = np.NaN - self.assertRaises(ValueError, non_ts.interpolate, method='time') + pytest.raises(ValueError, non_ts.interpolate, method='time') def test_interpolate_pchip(self): tm._skip_if_no_scipy() @@ -821,7 +823,7 @@ def test_interpolate_index_values(self): def test_interpolate_non_ts(self): s = Series([1, 3, np.nan, np.nan, np.nan, 11]) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): s.interpolate(method='time') # New interpolation tests @@ -912,7 +914,7 @@ def test_interp_limit(self): s = pd.Series([1, 2, np.nan, np.nan, 5]) for limit in [-1, 0, 1., 2.]: for method in methods: - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): s.interpolate(limit=limit, method=method) def test_interp_limit_forward(self): @@ -932,12 +934,12 @@ def test_interp_limit_forward(self): def test_interp_limit_bad_direction(self): s = Series([1, 3, np.nan, np.nan, np.nan, 11]) - self.assertRaises(ValueError, s.interpolate, method='linear', limit=2, - limit_direction='abc') + pytest.raises(ValueError, s.interpolate, method='linear', limit=2, + limit_direction='abc') # raises an error even if no limit is specified. - self.assertRaises(ValueError, s.interpolate, method='linear', - limit_direction='abc') + pytest.raises(ValueError, s.interpolate, method='linear', + limit_direction='abc') def test_interp_limit_direction(self): # These tests are for issue #9218 -- fill NaNs in both directions. @@ -1021,13 +1023,13 @@ def test_interp_multiIndex(self): assert_series_equal(result, expected) tm._skip_if_no_scipy() - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): s.interpolate(method='polynomial', order=1) def test_interp_nonmono_raise(self): tm._skip_if_no_scipy() s = Series([1, np.nan, 3], index=[0, 2, 1]) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): s.interpolate(method='krogh') def test_interp_datetime64(self): @@ -1048,9 +1050,9 @@ def test_interp_limit_no_nans(self): def test_no_order(self): tm._skip_if_no_scipy() s = Series([0, 1, np.nan, 3]) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): s.interpolate(method='polynomial') - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): s.interpolate(method='spline') def test_spline(self): @@ -1094,10 +1096,10 @@ def test_spline_error(self): s = pd.Series(np.arange(10) ** 2) s[np.random.randint(0, 9, 3)] = np.nan - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): s.interpolate(method='spline') - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): s.interpolate(method='spline', order=0) def test_interp_timedelta64(self): diff --git a/pandas/tests/series/test_operators.py b/pandas/tests/series/test_operators.py index ce22b29ee5299..159b29aca1e7c 100644 --- a/pandas/tests/series/test_operators.py +++ b/pandas/tests/series/test_operators.py @@ -1,6 +1,8 @@ # coding=utf-8 # pylint: disable-msg=E1101,W0612 +import pytest + from collections import Iterable from datetime import datetime, timedelta import operator @@ -246,12 +248,12 @@ def test_operators_empty_int_corner(self): def test_operators_timedelta64(self): # invalid ops - self.assertRaises(Exception, self.objSeries.__add__, 1) - self.assertRaises(Exception, self.objSeries.__add__, - np.array(1, dtype=np.int64)) - self.assertRaises(Exception, self.objSeries.__sub__, 1) - self.assertRaises(Exception, self.objSeries.__sub__, - np.array(1, dtype=np.int64)) + pytest.raises(Exception, self.objSeries.__add__, 1) + pytest.raises(Exception, self.objSeries.__add__, + np.array(1, dtype=np.int64)) + pytest.raises(Exception, self.objSeries.__sub__, 1) + pytest.raises(Exception, self.objSeries.__sub__, + np.array(1, dtype=np.int64)) # seriese ops v1 = date_range('2012-1-1', periods=3, freq='D') @@ -530,8 +532,8 @@ def test_timedelta64_operations_with_integers(self): for op in ['__add__', '__sub__']: sop = getattr(s1, op, None) if sop is not None: - self.assertRaises(TypeError, sop, 1) - self.assertRaises(TypeError, sop, s2.values) + pytest.raises(TypeError, sop, 1) + pytest.raises(TypeError, sop, s2.values) def test_timedelta64_conversions(self): startdate = Series(date_range('2013-01-01', '2013-01-03')) @@ -696,12 +698,12 @@ def run_ops(ops, get_ser, test_ser): result = dt1 - td1[0] exp = (dt1.dt.tz_localize(None) - td1[0]).dt.tz_localize(tz) assert_series_equal(result, exp) - self.assertRaises(TypeError, lambda: td1[0] - dt1) + pytest.raises(TypeError, lambda: td1[0] - dt1) result = dt2 - td2[0] exp = (dt2.dt.tz_localize(None) - td2[0]).dt.tz_localize(tz) assert_series_equal(result, exp) - self.assertRaises(TypeError, lambda: td2[0] - dt2) + pytest.raises(TypeError, lambda: td2[0] - dt2) result = dt1 + td1 exp = (dt1.dt.tz_localize(None) + td1).dt.tz_localize(tz) @@ -719,8 +721,8 @@ def run_ops(ops, get_ser, test_ser): exp = (dt2.dt.tz_localize(None) - td2).dt.tz_localize(tz) assert_series_equal(result, exp) - self.assertRaises(TypeError, lambda: td1 - dt1) - self.assertRaises(TypeError, lambda: td2 - dt2) + pytest.raises(TypeError, lambda: td1 - dt1) + pytest.raises(TypeError, lambda: td2 - dt2) def test_sub_datetime_compat(self): # GH 14088 @@ -768,7 +770,7 @@ def test_ops_nat(self): assert_series_equal(datetime_series - single_nat_dtype_datetime, nat_series_dtype_timedelta) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): -single_nat_dtype_datetime + datetime_series assert_series_equal(datetime_series - single_nat_dtype_timedelta, @@ -787,7 +789,7 @@ def test_ops_nat(self): assert_series_equal(nat_series_dtype_timestamp - single_nat_dtype_datetime, nat_series_dtype_timedelta) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): -single_nat_dtype_datetime + nat_series_dtype_timestamp assert_series_equal(nat_series_dtype_timestamp - @@ -797,7 +799,7 @@ def test_ops_nat(self): nat_series_dtype_timestamp, nat_series_dtype_timestamp) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): timedelta_series - single_nat_dtype_datetime # addition @@ -881,13 +883,13 @@ def test_ops_nat(self): assert_series_equal(timedelta_series * nan, nat_series_dtype_timedelta) assert_series_equal(nan * timedelta_series, nat_series_dtype_timedelta) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): datetime_series * 1 - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): nat_series_dtype_timestamp * 1 - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): datetime_series * 1.0 - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): nat_series_dtype_timestamp * 1.0 # division @@ -896,9 +898,9 @@ def test_ops_nat(self): assert_series_equal(timedelta_series / 2.0, Series([NaT, Timedelta('0.5s')])) assert_series_equal(timedelta_series / nan, nat_series_dtype_timedelta) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): nat_series_dtype_timestamp / 1.0 - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): nat_series_dtype_timestamp / 1 def test_ops_datetimelike_align(self): @@ -1030,12 +1032,12 @@ def test_comparison_invalid(self): s2 = Series(date_range('20010101', periods=5)) for (x, y) in [(s, s2), (s2, s)]: - self.assertRaises(TypeError, lambda: x == y) - self.assertRaises(TypeError, lambda: x != y) - self.assertRaises(TypeError, lambda: x >= y) - self.assertRaises(TypeError, lambda: x > y) - self.assertRaises(TypeError, lambda: x < y) - self.assertRaises(TypeError, lambda: x <= y) + pytest.raises(TypeError, lambda: x == y) + pytest.raises(TypeError, lambda: x != y) + pytest.raises(TypeError, lambda: x >= y) + pytest.raises(TypeError, lambda: x > y) + pytest.raises(TypeError, lambda: x < y) + pytest.raises(TypeError, lambda: x <= y) def test_more_na_comparisons(self): for dtype in [None, object]: @@ -1133,11 +1135,11 @@ def test_nat_comparisons_scalar(self): def test_comparison_different_length(self): a = Series(['a', 'b', 'c']) b = Series(['b', 'a']) - self.assertRaises(ValueError, a.__lt__, b) + pytest.raises(ValueError, a.__lt__, b) a = Series([1, 2]) b = Series([2, 3, 4]) - self.assertRaises(ValueError, a.__eq__, b) + pytest.raises(ValueError, a.__eq__, b) def test_comparison_label_based(self): @@ -1216,7 +1218,7 @@ def test_comparison_label_based(self): assert_series_equal(result, expected) for v in [np.nan, 'foo']: - self.assertRaises(TypeError, lambda: t | v) + pytest.raises(TypeError, lambda: t | v) for v in [False, 0]: result = Series([True, False, True], index=index) | v @@ -1233,7 +1235,7 @@ def test_comparison_label_based(self): expected = Series([False, False, False], index=index) assert_series_equal(result, expected) for v in [np.nan]: - self.assertRaises(TypeError, lambda: t & v) + pytest.raises(TypeError, lambda: t & v) def test_comparison_flex_basic(self): left = pd.Series(np.random.randn(10)) @@ -1388,11 +1390,11 @@ def test_operators_bitwise(self): expected = Series([1, 1, 3, 3], dtype='int32') assert_series_equal(res, expected) - self.assertRaises(TypeError, lambda: s_1111 & 'a') - self.assertRaises(TypeError, lambda: s_1111 & ['a', 'b', 'c', 'd']) - self.assertRaises(TypeError, lambda: s_0123 & np.NaN) - self.assertRaises(TypeError, lambda: s_0123 & 3.14) - self.assertRaises(TypeError, lambda: s_0123 & [0.1, 4, 3.14, 2]) + pytest.raises(TypeError, lambda: s_1111 & 'a') + pytest.raises(TypeError, lambda: s_1111 & ['a', 'b', 'c', 'd']) + pytest.raises(TypeError, lambda: s_0123 & np.NaN) + pytest.raises(TypeError, lambda: s_0123 & 3.14) + pytest.raises(TypeError, lambda: s_0123 & [0.1, 4, 3.14, 2]) # s_0123 will be all false now because of reindexing like s_tft if compat.PY3: @@ -1435,7 +1437,7 @@ def test_scalar_na_cmp_corners(self): def tester(a, b): return a & b - self.assertRaises(TypeError, tester, s, datetime(2005, 1, 1)) + pytest.raises(TypeError, tester, s, datetime(2005, 1, 1)) s = Series([2, 3, 4, 5, 6, 7, 8, 9, datetime(2005, 1, 1)]) s[::2] = np.nan @@ -1452,8 +1454,8 @@ def tester(a, b): # this is an alignment issue; these are equivalent # https://github.com/pandas-dev/pandas/issues/5284 - self.assertRaises(ValueError, lambda: d.__and__(s, axis='columns')) - self.assertRaises(ValueError, tester, s, d) + pytest.raises(ValueError, lambda: d.__and__(s, axis='columns')) + pytest.raises(ValueError, tester, s, d) # this is wrong as its not a boolean result # result = d.__and__(s,axis='index') @@ -1627,10 +1629,10 @@ def test_series_frame_radd_bug(self): assert_frame_equal(result, expected) # really raise this time - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): datetime.now() + self.ts - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): self.ts + datetime.now() def test_series_radd_more(self): @@ -1643,7 +1645,7 @@ def test_series_radd_more(self): for d in data: for dtype in [None, object]: s = Series(d, dtype=dtype) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): 'foo_' + s for dtype in [None, object]: @@ -1680,7 +1682,7 @@ def test_frame_radd_more(self): for d in data: for dtype in [None, object]: s = DataFrame(d, dtype=dtype) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): 'foo_' + s for dtype in [None, object]: diff --git a/pandas/tests/series/test_rank.py b/pandas/tests/series/test_rank.py index f47eae3adc3ae..1a1829eb5829f 100644 --- a/pandas/tests/series/test_rank.py +++ b/pandas/tests/series/test_rank.py @@ -213,7 +213,7 @@ def test_rank_categorical(self): def test_rank_signature(self): s = Series([0, 1]) s.rank(method='average') - self.assertRaises(ValueError, s.rank, 'average') + pytest.raises(ValueError, s.rank, 'average') def test_rank_inf(self): pytest.skip('DataFrame.rank does not currently rank ' diff --git a/pandas/tests/series/test_replace.py b/pandas/tests/series/test_replace.py index 5190eb110f4cf..a9a9204cf7f67 100644 --- a/pandas/tests/series/test_replace.py +++ b/pandas/tests/series/test_replace.py @@ -1,6 +1,8 @@ # coding=utf-8 # pylint: disable-msg=E1101,W0612 +import pytest + import numpy as np import pandas as pd import pandas._libs.lib as lib @@ -72,7 +74,7 @@ def test_replace(self): tm.assert_series_equal(ser.replace(np.nan, 0), ser.fillna(0)) # malformed - self.assertRaises(ValueError, ser.replace, [1, 2, 3], [np.nan, 0]) + pytest.raises(ValueError, ser.replace, [1, 2, 3], [np.nan, 0]) # make sure that we aren't just masking a TypeError because bools don't # implement indexing @@ -117,7 +119,7 @@ def test_replace_with_single_list(self): # make sure things don't get corrupted when fillna call fails s = ser.copy() - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): s.replace([1, 2, 3], inplace=True, method='crash_cymbal') tm.assert_series_equal(s, ser) diff --git a/pandas/tests/series/test_sorting.py b/pandas/tests/series/test_sorting.py index ead3c7dbc3bfd..7ab2ec245f611 100644 --- a/pandas/tests/series/test_sorting.py +++ b/pandas/tests/series/test_sorting.py @@ -1,5 +1,7 @@ # coding=utf-8 +import pytest + import numpy as np import random @@ -61,16 +63,16 @@ def test_sort_values(self): expected = ts.sort_values(ascending=False, na_position='first') assert_series_equal(expected, ordered) - self.assertRaises(ValueError, - lambda: ts.sort_values(ascending=None)) - self.assertRaises(ValueError, - lambda: ts.sort_values(ascending=[])) - self.assertRaises(ValueError, - lambda: ts.sort_values(ascending=[1, 2, 3])) - self.assertRaises(ValueError, - lambda: ts.sort_values(ascending=[False, False])) - self.assertRaises(ValueError, - lambda: ts.sort_values(ascending='foobar')) + pytest.raises(ValueError, + lambda: ts.sort_values(ascending=None)) + pytest.raises(ValueError, + lambda: ts.sort_values(ascending=[])) + pytest.raises(ValueError, + lambda: ts.sort_values(ascending=[1, 2, 3])) + pytest.raises(ValueError, + lambda: ts.sort_values(ascending=[False, False])) + pytest.raises(ValueError, + lambda: ts.sort_values(ascending='foobar')) # inplace=True ts = self.ts.copy() @@ -87,7 +89,7 @@ def test_sort_values(self): def f(): s.sort_values(inplace=True) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def test_sort_index(self): rindex = list(self.ts.index) @@ -110,13 +112,13 @@ def test_sort_index(self): sorted_series = random_order.sort_index(axis=0) assert_series_equal(sorted_series, self.ts) - self.assertRaises(ValueError, lambda: random_order.sort_values(axis=1)) + pytest.raises(ValueError, lambda: random_order.sort_values(axis=1)) sorted_series = random_order.sort_index(level=0, axis=0) assert_series_equal(sorted_series, self.ts) - self.assertRaises(ValueError, - lambda: random_order.sort_index(level=0, axis=1)) + pytest.raises(ValueError, + lambda: random_order.sort_index(level=0, axis=1)) def test_sort_index_inplace(self): diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index 78e55420bb3c8..bafb8ebfd7145 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -1,6 +1,8 @@ # coding=utf-8 # pylint: disable-msg=E1101,W0612 +import pytest + import numpy as np from datetime import datetime, timedelta, time @@ -73,7 +75,7 @@ def test_shift(self): assert_series_equal(shifted2, shifted3) assert_series_equal(ps, shifted2.shift(-1, 'B')) - self.assertRaises(ValueError, ps.shift, freq='D') + pytest.raises(ValueError, ps.shift, freq='D') # legacy support shifted4 = ps.shift(1, freq='B') @@ -104,7 +106,7 @@ def test_shift(self): # incompat tz s2 = Series(date_range('2000-01-01 09:00:00', periods=5, tz='CET'), name='foo') - self.assertRaises(ValueError, lambda: s - s2) + pytest.raises(ValueError, lambda: s - s2) def test_shift2(self): ts = Series(np.random.randn(5), @@ -120,7 +122,7 @@ def test_shift2(self): tm.assert_index_equal(result.index, exp_index) idx = DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-04']) - self.assertRaises(ValueError, idx.shift, 1) + pytest.raises(ValueError, idx.shift, 1) def test_shift_dst(self): # GH 13926 @@ -163,7 +165,7 @@ def test_tshift(self): shifted3 = ps.tshift(freq=BDay()) assert_series_equal(shifted, shifted3) - self.assertRaises(ValueError, ps.tshift, freq='M') + pytest.raises(ValueError, ps.tshift, freq='M') # DatetimeIndex shifted = self.ts.tshift(1) @@ -182,7 +184,7 @@ def test_tshift(self): assert_series_equal(unshifted, inferred_ts) no_freq = self.ts[[0, 5, 7]] - self.assertRaises(ValueError, no_freq.tshift) + pytest.raises(ValueError, no_freq.tshift) def test_truncate(self): offset = BDay() @@ -230,9 +232,9 @@ def test_truncate(self): truncated = ts.truncate(before=self.ts.index[-1] + offset) assert (len(truncated) == 0) - self.assertRaises(ValueError, ts.truncate, - before=self.ts.index[-1] + offset, - after=self.ts.index[0] - offset) + pytest.raises(ValueError, ts.truncate, + before=self.ts.index[-1] + offset, + after=self.ts.index[0] - offset) def test_asfreq(self): ts = Series([0., 1., 2.], index=[datetime(2009, 10, 30), datetime( @@ -401,7 +403,7 @@ def test_empty_series_ops(self): assert_series_equal(a, a + b) assert_series_equal(a, a - b) assert_series_equal(a, b + a) - self.assertRaises(TypeError, lambda x, y: x - y, b, a) + pytest.raises(TypeError, lambda x, y: x - y, b, a) def test_contiguous_boolean_preserve_freq(self): rng = date_range('1/1/2000', '3/1/2000', freq='B') @@ -466,9 +468,9 @@ def test_to_datetime_unit(self): Timestamp('1970-01-03')] + ['NaT'] * 3) tm.assert_index_equal(result, expected) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): to_datetime([1, 2, 'foo'], unit='D') - with self.assertRaises(ValueError): + with pytest.raises(ValueError): to_datetime([1, 2, 111111111], unit='D') # coerce we can process @@ -709,16 +711,16 @@ def test_between_time(self): def test_between_time_types(self): # GH11818 rng = date_range('1/1/2000', '1/5/2000', freq='5min') - self.assertRaises(ValueError, rng.indexer_between_time, - datetime(2010, 1, 2, 1), datetime(2010, 1, 2, 5)) + pytest.raises(ValueError, rng.indexer_between_time, + datetime(2010, 1, 2, 1), datetime(2010, 1, 2, 5)) frame = DataFrame({'A': 0}, index=rng) - self.assertRaises(ValueError, frame.between_time, - datetime(2010, 1, 2, 1), datetime(2010, 1, 2, 5)) + pytest.raises(ValueError, frame.between_time, + datetime(2010, 1, 2, 1), datetime(2010, 1, 2, 5)) series = Series(0, index=rng) - self.assertRaises(ValueError, series.between_time, - datetime(2010, 1, 2, 1), datetime(2010, 1, 2, 5)) + pytest.raises(ValueError, series.between_time, + datetime(2010, 1, 2, 1), datetime(2010, 1, 2, 5)) def test_between_time_formats(self): # GH11818 diff --git a/pandas/tests/series/test_validate.py b/pandas/tests/series/test_validate.py index cf0482b41c80a..6327e265d8c1e 100644 --- a/pandas/tests/series/test_validate.py +++ b/pandas/tests/series/test_validate.py @@ -1,8 +1,8 @@ -from unittest import TestCase +import pytest from pandas.core.series import Series -class TestSeriesValidate(TestCase): +class TestSeriesValidate(object): """Tests for error handling related to data types of method arguments.""" s = Series([1, 2, 3, 4, 5]) @@ -11,23 +11,23 @@ def test_validate_bool_args(self): invalid_values = [1, "True", [1, 2, 3], 5.0] for value in invalid_values: - with self.assertRaises(ValueError): + with pytest.raises(ValueError): self.s.reset_index(inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): self.s._set_name(name='hello', inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): self.s.sort_values(inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): self.s.sort_index(inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): self.s.sort_index(inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): self.s.rename(inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): self.s.dropna(inplace=value) diff --git a/pandas/tests/sparse/test_array.py b/pandas/tests/sparse/test_array.py index 653656fe1e539..df14a3139edab 100644 --- a/pandas/tests/sparse/test_array.py +++ b/pandas/tests/sparse/test_array.py @@ -1,6 +1,8 @@ from pandas.compat import range + import re import operator +import pytest import warnings from numpy import nan @@ -178,7 +180,7 @@ def test_take_negative(self): def test_bad_take(self): assertRaisesRegexp(IndexError, "bounds", lambda: self.arr.take(11)) - self.assertRaises(IndexError, lambda: self.arr.take(-11)) + pytest.raises(IndexError, lambda: self.arr.take(-11)) def test_take_invalid_kwargs(self): msg = r"take\(\) got an unexpected keyword argument 'foo'" @@ -218,11 +220,11 @@ def test_take_filling(self): with tm.assertRaisesRegexp(ValueError, msg): sparse.take(np.array([1, 0, -5]), fill_value=True) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): sparse.take(np.array([1, -6])) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): sparse.take(np.array([1, 5])) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): sparse.take(np.array([1, 5]), fill_value=True) def test_take_filling_fill_value(self): @@ -250,11 +252,11 @@ def test_take_filling_fill_value(self): with tm.assertRaisesRegexp(ValueError, msg): sparse.take(np.array([1, 0, -5]), fill_value=True) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): sparse.take(np.array([1, -6])) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): sparse.take(np.array([1, 5])) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): sparse.take(np.array([1, 5]), fill_value=True) def test_take_filling_all_nan(self): @@ -267,11 +269,11 @@ def test_take_filling_all_nan(self): expected = SparseArray([np.nan, np.nan, np.nan]) tm.assert_sp_array_equal(result, expected) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): sparse.take(np.array([1, -6])) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): sparse.take(np.array([1, 5])) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): sparse.take(np.array([1, 5]), fill_value=True) def test_set_item(self): @@ -496,10 +498,10 @@ def test_getslice_tuple(self): exp = SparseArray(dense[4:, ], fill_value=0) tm.assert_sp_array_equal(res, exp) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): sparse[4:, :] - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): # check numpy compat dense[4:, :] @@ -546,7 +548,7 @@ def _check_op(op, first, second): def _check_inplace_op(op): tmp = arr1.copy() - self.assertRaises(NotImplementedError, op, tmp, arr2) + pytest.raises(NotImplementedError, op, tmp, arr2) with np.errstate(all='ignore'): bin_ops = [operator.add, operator.sub, operator.mul, diff --git a/pandas/tests/sparse/test_frame.py b/pandas/tests/sparse/test_frame.py index d5df25e82de13..d5df744648ff3 100644 --- a/pandas/tests/sparse/test_frame.py +++ b/pandas/tests/sparse/test_frame.py @@ -133,7 +133,7 @@ def test_constructor(self): tm.assert_sp_frame_equal(cons, reindexed, exact_indices=False) # assert level parameter breaks reindex - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): self.frame.reindex(idx, level=0) repr(self.frame) @@ -147,8 +147,8 @@ def test_constructor_ndarray(self): tm.assert_sp_frame_equal(sp, self.frame.reindex(columns=['A'])) # raise on level argument - self.assertRaises(TypeError, self.frame.reindex, columns=['A'], - level=1) + pytest.raises(TypeError, self.frame.reindex, columns=['A'], + level=1) # wrong length index / columns with tm.assertRaisesRegexp(ValueError, "^Index length"): @@ -405,7 +405,7 @@ def test_getitem(self): exp = sdf.reindex(columns=['a', 'b']) tm.assert_sp_frame_equal(result, exp) - self.assertRaises(Exception, sdf.__getitem__, ['a', 'd']) + pytest.raises(Exception, sdf.__getitem__, ['a', 'd']) def test_iloc(self): @@ -465,7 +465,7 @@ def test_getitem_overload(self): subframe = self.frame[indexer] tm.assert_index_equal(subindex, subframe.index) - self.assertRaises(Exception, self.frame.__getitem__, indexer[:-1]) + pytest.raises(Exception, self.frame.__getitem__, indexer[:-1]) def test_setitem(self): @@ -509,8 +509,8 @@ def _check_frame(frame, orig): self.assertEqual(len(frame['I'].sp_values), N // 2) # insert ndarray wrong size - self.assertRaises(Exception, frame.__setitem__, 'foo', - np.random.randn(N - 1)) + pytest.raises(Exception, frame.__setitem__, 'foo', + np.random.randn(N - 1)) # scalar value frame['J'] = 5 @@ -557,13 +557,13 @@ def test_delitem(self): def test_set_columns(self): self.frame.columns = self.frame.columns - self.assertRaises(Exception, setattr, self.frame, 'columns', - self.frame.columns[:-1]) + pytest.raises(Exception, setattr, self.frame, 'columns', + self.frame.columns[:-1]) def test_set_index(self): self.frame.index = self.frame.index - self.assertRaises(Exception, setattr, self.frame, 'index', - self.frame.index[:-1]) + pytest.raises(Exception, setattr, self.frame, 'index', + self.frame.index[:-1]) def test_append(self): a = self.frame[:5] @@ -796,7 +796,7 @@ def test_join(self): tm.assert_sp_frame_equal(joined, self.frame, exact_indices=False) right = self.frame.loc[:, ['B', 'D']] - self.assertRaises(Exception, left.join, right) + pytest.raises(Exception, left.join, right) with tm.assertRaisesRegexp(ValueError, 'Other Series must have a name'): @@ -931,11 +931,11 @@ def test_reindex_method(self): tm.assert_sp_frame_equal(result, expected) # method='bfill' - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): sparse.reindex(columns=range(6), method='bfill') # method='ffill' - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): sparse.reindex(columns=range(6), method='ffill') def test_take(self): @@ -969,8 +969,8 @@ def _check(frame): _check(self.iframe) # for now - self.assertRaises(Exception, _check, self.zframe) - self.assertRaises(Exception, _check, self.fill_frame) + pytest.raises(Exception, _check, self.zframe) + pytest.raises(Exception, _check, self.fill_frame) def test_transpose(self): diff --git a/pandas/tests/sparse/test_indexing.py b/pandas/tests/sparse/test_indexing.py index 4a9bea798be36..d0e5196570adc 100644 --- a/pandas/tests/sparse/test_indexing.py +++ b/pandas/tests/sparse/test_indexing.py @@ -220,7 +220,7 @@ def test_iloc(self): exp = orig.iloc[[1, -2, -4]].to_sparse() tm.assert_sp_series_equal(result, exp) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): sparse.iloc[[1, 3, 5]] def test_iloc_fill_value(self): @@ -792,7 +792,7 @@ def test_iloc(self): exp = orig.iloc[[2], [1, 0]].to_sparse() tm.assert_sp_frame_equal(result, exp) - with tm.assertRaises(IndexError): + with pytest.raises(IndexError): sparse.iloc[[1, 3, 5]] def test_iloc_slice(self): diff --git a/pandas/tests/sparse/test_libsparse.py b/pandas/tests/sparse/test_libsparse.py index 1990e29a4b901..00e01b8ba14bc 100644 --- a/pandas/tests/sparse/test_libsparse.py +++ b/pandas/tests/sparse/test_libsparse.py @@ -184,7 +184,7 @@ def test_intindex_make_union(self): a = IntIndex(5, np.array([0, 1], dtype=np.int32)) b = IntIndex(4, np.array([0, 1], dtype=np.int32)) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): a.make_union(b) @@ -196,7 +196,7 @@ def _check_correct(a, b, expected): assert (result.equals(expected)) def _check_length_exc(a, longer): - self.assertRaises(Exception, a.intersect, longer) + pytest.raises(Exception, a.intersect, longer) def _check_case(xloc, xlen, yloc, ylen, eloc, elen): xindex = BlockIndex(TEST_LENGTH, xloc, xlen) @@ -451,10 +451,10 @@ def test_check_integrity(self): index = BlockIndex(1, locs, lengths) # noqa # block extend beyond end - self.assertRaises(Exception, BlockIndex, 10, [5], [10]) + pytest.raises(Exception, BlockIndex, 10, [5], [10]) # block overlap - self.assertRaises(Exception, BlockIndex, 10, [2, 5], [5, 3]) + pytest.raises(Exception, BlockIndex, 10, [2, 5], [5, 3]) def test_to_int_index(self): locs = [0, 10] diff --git a/pandas/tests/sparse/test_series.py b/pandas/tests/sparse/test_series.py index 8ccc9e1131f60..dcac0f599fdeb 100644 --- a/pandas/tests/sparse/test_series.py +++ b/pandas/tests/sparse/test_series.py @@ -1,6 +1,7 @@ # pylint: disable-msg=E1101,W0612 import operator +import pytest from numpy import nan import numpy as np @@ -353,7 +354,7 @@ def test_shape(self): self.assertEqual(self.ziseries2.shape, (15, )) def test_astype(self): - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): self.bseries.astype(np.int64) def test_astype_all(self): @@ -425,12 +426,12 @@ def _check_getitem(sp, dense): _check_getitem(self.ziseries, self.ziseries.to_dense()) # exception handling - self.assertRaises(Exception, self.bseries.__getitem__, - len(self.bseries) + 1) + pytest.raises(Exception, self.bseries.__getitem__, + len(self.bseries) + 1) # index not contained - self.assertRaises(Exception, self.btseries.__getitem__, - self.btseries.index[-1] + BDay()) + pytest.raises(Exception, self.btseries.__getitem__, + self.btseries.index[-1] + BDay()) def test_get_get_value(self): tm.assert_almost_equal(self.bseries.get(10), self.bseries[10]) @@ -489,8 +490,8 @@ def _compare(idx): self._check_all(_compare_with_dense) - self.assertRaises(Exception, self.bseries.take, - [0, len(self.bseries) + 1]) + pytest.raises(Exception, self.bseries.take, + [0, len(self.bseries) + 1]) # Corner case sp = SparseSeries(np.ones(10) * nan) @@ -1036,25 +1037,25 @@ def test_to_coo_text_names_text_row_levels_nosort(self): def test_to_coo_bad_partition_nonnull_intersection(self): ss = self.sparse_series[0] - self.assertRaises(ValueError, ss.to_coo, ['A', 'B', 'C'], ['C', 'D']) + pytest.raises(ValueError, ss.to_coo, ['A', 'B', 'C'], ['C', 'D']) def test_to_coo_bad_partition_small_union(self): ss = self.sparse_series[0] - self.assertRaises(ValueError, ss.to_coo, ['A'], ['C', 'D']) + pytest.raises(ValueError, ss.to_coo, ['A'], ['C', 'D']) def test_to_coo_nlevels_less_than_two(self): ss = self.sparse_series[0] ss.index = np.arange(len(ss.index)) - self.assertRaises(ValueError, ss.to_coo) + pytest.raises(ValueError, ss.to_coo) def test_to_coo_bad_ilevel(self): ss = self.sparse_series[0] - self.assertRaises(KeyError, ss.to_coo, ['A', 'B'], ['C', 'D', 'E']) + pytest.raises(KeyError, ss.to_coo, ['A', 'B'], ['C', 'D', 'E']) def test_to_coo_duplicate_index_entries(self): ss = pd.concat([self.sparse_series[0], self.sparse_series[0]]).to_sparse() - self.assertRaises(ValueError, ss.to_coo, ['A', 'B'], ['C', 'D']) + pytest.raises(ValueError, ss.to_coo, ['A', 'B'], ['C', 'D']) def test_from_coo_dense_index(self): ss = SparseSeries.from_coo(self.coo_matrices[0], dense_index=True) diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 3b916f0b6792f..df267f2374051 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -1,6 +1,8 @@ # -*- coding: utf-8 -*- import numpy as np +import pytest + from numpy.random import RandomState from numpy import nan from datetime import datetime @@ -126,9 +128,9 @@ def test_unsortable(self): if compat.PY2 and not pd._np_version_under1p10: # RuntimeWarning: tp_compare didn't return -1 or -2 for exception with tm.assert_produces_warning(RuntimeWarning): - tm.assertRaises(TypeError, algos.safe_sort, arr) + pytest.raises(TypeError, algos.safe_sort, arr) else: - tm.assertRaises(TypeError, algos.safe_sort, arr) + pytest.raises(TypeError, algos.safe_sort, arr) def test_exceptions(self): with tm.assertRaisesRegexp(TypeError, @@ -284,7 +286,7 @@ def test_complex_sorting(self): x17 = np.array([complex(i) for i in range(17)], dtype=object) - self.assertRaises(TypeError, algos.factorize, x17[::-1], sort=True) + pytest.raises(TypeError, algos.factorize, x17[::-1], sort=True) def test_uint64_factorize(self): data = np.array([2**63, 1, 2**63], dtype=np.uint64) @@ -499,9 +501,9 @@ class TestIsin(tm.TestCase): def test_invalid(self): - self.assertRaises(TypeError, lambda: algos.isin(1, 1)) - self.assertRaises(TypeError, lambda: algos.isin(1, [1])) - self.assertRaises(TypeError, lambda: algos.isin([1], 1)) + pytest.raises(TypeError, lambda: algos.isin(1, 1)) + pytest.raises(TypeError, lambda: algos.isin(1, [1])) + pytest.raises(TypeError, lambda: algos.isin([1], 1)) def test_basic(self): @@ -620,8 +622,8 @@ def test_value_counts_dtypes(self): result = algos.value_counts(Series([1, 1., '1'])) # object self.assertEqual(len(result), 2) - self.assertRaises(TypeError, lambda s: algos.value_counts(s, bins=1), - ['1', 1]) + pytest.raises(TypeError, lambda s: algos.value_counts(s, bins=1), + ['1', 1]) def test_value_counts_nat(self): td = Series([np.timedelta64(10000), pd.NaT], dtype='timedelta64[ns]') @@ -1355,15 +1357,15 @@ def test_int64_add_overflow(): # Check that the nan boolean arrays override whether or not # the addition overflows. We don't check the result but just # the fact that an OverflowError is not raised. - with tm.assertRaises(AssertionError): + with pytest.raises(AssertionError): with tm.assertRaisesRegexp(OverflowError, msg): algos.checked_add_with_arr(np.array([m, m]), np.array([m, m]), arr_mask=np.array([True, True])) - with tm.assertRaises(AssertionError): + with pytest.raises(AssertionError): with tm.assertRaisesRegexp(OverflowError, msg): algos.checked_add_with_arr(np.array([m, m]), np.array([m, m]), b_mask=np.array([True, True])) - with tm.assertRaises(AssertionError): + with pytest.raises(AssertionError): with tm.assertRaisesRegexp(OverflowError, msg): algos.checked_add_with_arr(np.array([m, m]), np.array([m, m]), arr_mask=np.array([True, False]), diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index 4b9c27d23273d..d91aab6bc3ceb 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -130,17 +130,17 @@ def test_invalida_delgation(self): def f(): delegate.foo - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def f(): delegate.foo = 5 - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def f(): delegate.foo() - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def test_memory_usage(self): # Delegate does not implement memory_usage. @@ -227,10 +227,10 @@ def check_ops_properties(self, props, filter=None, ignore_failures=False): # an object that is datetimelike will raise a TypeError, # otherwise an AttributeError if issubclass(type(o), DatetimeIndexOpsMixin): - self.assertRaises(TypeError, lambda: getattr(o, op)) + pytest.raises(TypeError, lambda: getattr(o, op)) else: - self.assertRaises(AttributeError, - lambda: getattr(o, op)) + pytest.raises(AttributeError, + lambda: getattr(o, op)) def test_binary_ops_docs(self): from pandas import DataFrame, Panel @@ -978,7 +978,7 @@ def test_validate_bool_args(self): invalid_values = [1, "True", [1, 2, 3], 5.0] for value in invalid_values: - with self.assertRaises(ValueError): + with pytest.raises(ValueError): self.int_series.drop_duplicates(inplace=value) @@ -1027,5 +1027,5 @@ class T(NoNewAttributesMixin): def f(): t.b = "test" - self.assertRaises(AttributeError, f) + pytest.raises(AttributeError, f) self.assertFalse(hasattr(t, "b")) diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index 65ef841e624e2..b26c015133697 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -120,7 +120,7 @@ def test_constructor_unsortable(self): self.assertFalse(factor.ordered) # this however will raise as cannot be sorted - self.assertRaises( + pytest.raises( TypeError, lambda: Categorical(arr, ordered=True)) def test_constructor_interval(self): @@ -166,12 +166,12 @@ def test_constructor(self): def f(): Categorical([1, 2], [1, 2, 2]) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def f(): Categorical(["a", "b"], ["a", "b", "b"]) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # The default should be unordered c1 = Categorical(["a", "b", "c", "a"]) @@ -409,31 +409,31 @@ def test_from_codes(self): def f(): Categorical.from_codes([1, 2], [1, 2]) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # no int codes def f(): Categorical.from_codes(["a"], [1, 2]) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # no unique categories def f(): Categorical.from_codes([0, 1, 2], ["a", "a", "b"]) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # NaN categories included def f(): Categorical.from_codes([0, 1, 2], ["a", "b", np.nan]) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # too negative def f(): Categorical.from_codes([-2, 1, 2], ["a", "b", "c"]) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) exp = Categorical(["a", "b", "c"], ordered=False) res = Categorical.from_codes([0, 1, 2], ["a", "b", "c"]) @@ -522,7 +522,7 @@ def test_comparisons(self): def f(): cat > cat_rev - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) cat_rev_base2 = pd.Categorical( ["b", "b", "b"], categories=["c", "b", "a", "d"]) @@ -530,7 +530,7 @@ def f(): def f(): cat_rev > cat_rev_base2 - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) # Only categories with same ordering information can be compared cat_unorderd = cat.set_ordered(False) @@ -539,26 +539,26 @@ def f(): def f(): cat > cat_unorderd - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) # comparison (in both directions) with Series will raise s = Series(["b", "b", "b"]) - self.assertRaises(TypeError, lambda: cat > s) - self.assertRaises(TypeError, lambda: cat_rev > s) - self.assertRaises(TypeError, lambda: s < cat) - self.assertRaises(TypeError, lambda: s < cat_rev) + pytest.raises(TypeError, lambda: cat > s) + pytest.raises(TypeError, lambda: cat_rev > s) + pytest.raises(TypeError, lambda: s < cat) + pytest.raises(TypeError, lambda: s < cat_rev) # comparison with numpy.array will raise in both direction, but only on # newer numpy versions a = np.array(["b", "b", "b"]) - self.assertRaises(TypeError, lambda: cat > a) - self.assertRaises(TypeError, lambda: cat_rev > a) + pytest.raises(TypeError, lambda: cat > a) + pytest.raises(TypeError, lambda: cat_rev > a) # The following work via '__array_priority__ = 1000' # works only on numpy >= 1.7.1 if LooseVersion(np.__version__) > "1.7.1": - self.assertRaises(TypeError, lambda: a < cat) - self.assertRaises(TypeError, lambda: a < cat_rev) + pytest.raises(TypeError, lambda: a < cat) + pytest.raises(TypeError, lambda: a < cat_rev) # Make sure that unequal comparison take the categories order in # account @@ -777,13 +777,13 @@ def test_categories_assigments(self): def f(): s.categories = [1, 2, 3, 4] - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # shorten def f(): s.categories = [1, 2] - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def test_construction_with_ordered(self): # GH 9347, 9190 @@ -968,19 +968,19 @@ def test_reorder_categories(self): def f(): cat.reorder_categories(["a"]) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # still not all "old" in "new" def f(): cat.reorder_categories(["a", "b", "d"]) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # all "old" included in "new", but too long def f(): cat.reorder_categories(["a", "b", "c", "d"]) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def test_add_categories(self): cat = Categorical(["a", "b", "c", "a"], ordered=True) @@ -1006,7 +1006,7 @@ def test_add_categories(self): def f(): cat.add_categories(["d"]) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # GH 9927 cat = Categorical(list("abc"), ordered=True) @@ -1046,7 +1046,7 @@ def test_remove_categories(self): def f(): cat.remove_categories(["c"]) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def test_remove_unused_categories(self): c = Categorical(["a", "b", "c", "d", "a"], @@ -1127,7 +1127,7 @@ def test_codes_immutable(self): def f(): c.codes = np.array([0, 1, 2, 0, 1], dtype='int8') - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # changes in the codes array should raise # np 1.6.1 raises RuntimeError rather than ValueError @@ -1136,7 +1136,7 @@ def f(): def f(): codes[4] = 1 - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # But even after getting the codes, the original array should still be # writeable! @@ -1151,8 +1151,8 @@ def test_min_max(self): # unordered cats have no min/max cat = Categorical(["a", "b", "c", "d"], ordered=False) - self.assertRaises(TypeError, lambda: cat.min()) - self.assertRaises(TypeError, lambda: cat.max()) + pytest.raises(TypeError, lambda: cat.min()) + pytest.raises(TypeError, lambda: cat.max()) cat = Categorical(["a", "b", "c", "d"], ordered=True) _min = cat.min() _max = cat.max() @@ -1480,18 +1480,18 @@ def test_searchsorted(self): tm.assert_numpy_array_equal(res_ser, exp) # Searching for a single value that is not from the Categorical - self.assertRaises(ValueError, lambda: c1.searchsorted('cucumber')) - self.assertRaises(ValueError, lambda: s1.searchsorted('cucumber')) + pytest.raises(ValueError, lambda: c1.searchsorted('cucumber')) + pytest.raises(ValueError, lambda: s1.searchsorted('cucumber')) # Searching for multiple values one of each is not from the Categorical - self.assertRaises(ValueError, - lambda: c1.searchsorted(['bread', 'cucumber'])) - self.assertRaises(ValueError, - lambda: s1.searchsorted(['bread', 'cucumber'])) + pytest.raises(ValueError, + lambda: c1.searchsorted(['bread', 'cucumber'])) + pytest.raises(ValueError, + lambda: s1.searchsorted(['bread', 'cucumber'])) # searchsorted call for unordered Categorical - self.assertRaises(ValueError, lambda: c2.searchsorted('apple')) - self.assertRaises(ValueError, lambda: s2.searchsorted('apple')) + pytest.raises(ValueError, lambda: c2.searchsorted('apple')) + pytest.raises(ValueError, lambda: s2.searchsorted('apple')) with tm.assert_produces_warning(FutureWarning): res = c1.searchsorted(v=['bread']) @@ -1568,36 +1568,36 @@ def test_validate_inplace(self): invalid_values = [1, "True", [1, 2, 3], 5.0] for value in invalid_values: - with self.assertRaises(ValueError): + with pytest.raises(ValueError): cat.set_ordered(value=True, inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): cat.as_ordered(inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): cat.as_unordered(inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): cat.set_categories(['X', 'Y', 'Z'], rename=True, inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): cat.rename_categories(['X', 'Y', 'Z'], inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): cat.reorder_categories( ['X', 'Y', 'Z'], ordered=True, inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): cat.add_categories( new_categories=['D', 'E', 'F'], inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): cat.remove_categories(removals=['D', 'E', 'F'], inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): cat.remove_unused_categories(inplace=value) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): cat.sort_values(inplace=value) @@ -1817,14 +1817,14 @@ def test_construction_frame(self): tm.assert_frame_equal(df, expected) # invalid (shape) - self.assertRaises( + pytest.raises( ValueError, lambda: DataFrame([pd.Categorical(list('abc')), pd.Categorical(list('abdefg'))])) # ndim > 1 - self.assertRaises(NotImplementedError, - lambda: pd.Categorical(np.array([list('abcd')]))) + pytest.raises(NotImplementedError, + lambda: pd.Categorical(np.array([list('abcd')]))) def test_reshaping(self): @@ -1954,15 +1954,15 @@ def test_sequence_like(self): def test_series_delegations(self): # invalid accessor - self.assertRaises(AttributeError, lambda: Series([1, 2, 3]).cat) + pytest.raises(AttributeError, lambda: Series([1, 2, 3]).cat) tm.assertRaisesRegexp( AttributeError, r"Can only use .cat accessor with a 'category' dtype", lambda: Series([1, 2, 3]).cat) - self.assertRaises(AttributeError, lambda: Series(['a', 'b', 'c']).cat) - self.assertRaises(AttributeError, lambda: Series(np.arange(5.)).cat) - self.assertRaises(AttributeError, - lambda: Series([Timestamp('20130101')]).cat) + pytest.raises(AttributeError, lambda: Series(['a', 'b', 'c']).cat) + pytest.raises(AttributeError, lambda: Series(np.arange(5.)).cat) + pytest.raises(AttributeError, + lambda: Series([Timestamp('20130101')]).cat) # Series should delegate calls to '.categories', '.codes', '.ordered' # and the methods '.set_categories()' 'drop_unused_categories()' to the @@ -2007,7 +2007,7 @@ def test_series_delegations(self): def f(): s.set_categories([4, 3, 2, 1]) - self.assertRaises(Exception, f) + pytest.raises(Exception, f) # right: s.cat.set_categories([4,3,2,1]) def test_series_functions_no_warnings(self): @@ -2795,8 +2795,8 @@ def test_groupby_sort(self): def test_min_max(self): # unordered cats have no min/max cat = Series(Categorical(["a", "b", "c", "d"], ordered=False)) - self.assertRaises(TypeError, lambda: cat.min()) - self.assertRaises(TypeError, lambda: cat.max()) + pytest.raises(TypeError, lambda: cat.min()) + pytest.raises(TypeError, lambda: cat.max()) cat = Series(Categorical(["a", "b", "c", "d"], ordered=True)) _min = cat.min() @@ -3395,7 +3395,7 @@ def f(): df = orig.copy() df.iloc[2, 0] = "c" - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # - assign a complete row (mixed values) -> exp_single_row df = orig.copy() @@ -3407,7 +3407,7 @@ def f(): df = orig.copy() df.iloc[2, :] = ["c", 2] - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # - assign multiple rows (mixed values) -> exp_multi_row df = orig.copy() @@ -3418,7 +3418,7 @@ def f(): df = orig.copy() df.iloc[2:4, :] = [["c", 2], ["c", 2]] - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # assign a part of a column with dtype == categorical -> # exp_parts_cats_col @@ -3426,13 +3426,13 @@ def f(): df.iloc[2:4, 0] = pd.Categorical(["b", "b"], categories=["a", "b"]) tm.assert_frame_equal(df, exp_parts_cats_col) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): # different categories -> not sure if this should fail or pass df = orig.copy() df.iloc[2:4, 0] = pd.Categorical( ["b", "b"], categories=["a", "b", "c"]) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): # different values df = orig.copy() df.iloc[2:4, 0] = pd.Categorical( @@ -3444,7 +3444,7 @@ def f(): df.iloc[2:4, 0] = ["b", "b"] tm.assert_frame_equal(df, exp_parts_cats_col) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.iloc[2:4, 0] = ["c", "c"] # loc @@ -3463,7 +3463,7 @@ def f(): df = orig.copy() df.loc["j", "cats"] = "c" - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # - assign a complete row (mixed values) -> exp_single_row df = orig.copy() @@ -3475,7 +3475,7 @@ def f(): df = orig.copy() df.loc["j", :] = ["c", 2] - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # - assign multiple rows (mixed values) -> exp_multi_row df = orig.copy() @@ -3486,7 +3486,7 @@ def f(): df = orig.copy() df.loc["j":"k", :] = [["c", 2], ["c", 2]] - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # assign a part of a column with dtype == categorical -> # exp_parts_cats_col @@ -3495,13 +3495,13 @@ def f(): ["b", "b"], categories=["a", "b"]) tm.assert_frame_equal(df, exp_parts_cats_col) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): # different categories -> not sure if this should fail or pass df = orig.copy() df.loc["j":"k", "cats"] = pd.Categorical( ["b", "b"], categories=["a", "b", "c"]) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): # different values df = orig.copy() df.loc["j":"k", "cats"] = pd.Categorical( @@ -3513,7 +3513,7 @@ def f(): df.loc["j":"k", "cats"] = ["b", "b"] tm.assert_frame_equal(df, exp_parts_cats_col) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.loc["j":"k", "cats"] = ["c", "c"] # loc @@ -3532,7 +3532,7 @@ def f(): df = orig.copy() df.loc["j", df.columns[0]] = "c" - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # - assign a complete row (mixed values) -> exp_single_row df = orig.copy() @@ -3544,7 +3544,7 @@ def f(): df = orig.copy() df.loc["j", :] = ["c", 2] - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # - assign multiple rows (mixed values) -> exp_multi_row df = orig.copy() @@ -3555,7 +3555,7 @@ def f(): df = orig.copy() df.loc["j":"k", :] = [["c", 2], ["c", 2]] - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # assign a part of a column with dtype == categorical -> # exp_parts_cats_col @@ -3564,13 +3564,13 @@ def f(): ["b", "b"], categories=["a", "b"]) tm.assert_frame_equal(df, exp_parts_cats_col) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): # different categories -> not sure if this should fail or pass df = orig.copy() df.loc["j":"k", df.columns[0]] = pd.Categorical( ["b", "b"], categories=["a", "b", "c"]) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): # different values df = orig.copy() df.loc["j":"k", df.columns[0]] = pd.Categorical( @@ -3582,7 +3582,7 @@ def f(): df.loc["j":"k", df.columns[0]] = ["b", "b"] tm.assert_frame_equal(df, exp_parts_cats_col) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.loc["j":"k", df.columns[0]] = ["c", "c"] # iat @@ -3595,7 +3595,7 @@ def f(): df = orig.copy() df.iat[2, 0] = "c" - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # at # - assign a single value -> exp_single_cats_value @@ -3608,7 +3608,7 @@ def f(): df = orig.copy() df.at["j", "cats"] = "c" - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # fancy indexing catsf = pd.Categorical(["a", "a", "c", "c", "a", "a", "a"], @@ -3633,7 +3633,7 @@ def f(): df = orig.copy() df.set_value("j", "cats", "c") - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # Assigning a Category to parts of a int/... column uses the values of # the Catgorical @@ -3723,20 +3723,20 @@ def test_comparisons(self): def f(): cat > cat_rev - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) # categorical cannot be compared to Series or numpy array, and also # not the other way around - self.assertRaises(TypeError, lambda: cat > s) - self.assertRaises(TypeError, lambda: cat_rev > s) - self.assertRaises(TypeError, lambda: cat > a) - self.assertRaises(TypeError, lambda: cat_rev > a) + pytest.raises(TypeError, lambda: cat > s) + pytest.raises(TypeError, lambda: cat_rev > s) + pytest.raises(TypeError, lambda: cat > a) + pytest.raises(TypeError, lambda: cat_rev > a) - self.assertRaises(TypeError, lambda: s < cat) - self.assertRaises(TypeError, lambda: s < cat_rev) + pytest.raises(TypeError, lambda: s < cat) + pytest.raises(TypeError, lambda: s < cat_rev) - self.assertRaises(TypeError, lambda: a < cat) - self.assertRaises(TypeError, lambda: a < cat_rev) + pytest.raises(TypeError, lambda: a < cat) + pytest.raises(TypeError, lambda: a < cat_rev) # unequal comparison should raise for unordered cats cat = Series(Categorical(list("abc"))) @@ -3744,23 +3744,23 @@ def f(): def f(): cat > "b" - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) cat = Series(Categorical(list("abc"), ordered=False)) def f(): cat > "b" - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) # https://github.com/pandas-dev/pandas/issues/9836#issuecomment-92123057 # and following comparisons with scalars not in categories should raise # for unequal comps, but not for equal/not equal cat = Series(Categorical(list("abc"), ordered=True)) - self.assertRaises(TypeError, lambda: cat < "d") - self.assertRaises(TypeError, lambda: cat > "d") - self.assertRaises(TypeError, lambda: "d" < cat) - self.assertRaises(TypeError, lambda: "d" > cat) + pytest.raises(TypeError, lambda: cat < "d") + pytest.raises(TypeError, lambda: cat > "d") + pytest.raises(TypeError, lambda: "d" < cat) + pytest.raises(TypeError, lambda: "d" > cat) tm.assert_series_equal(cat == "d", Series([False, False, False])) tm.assert_series_equal(cat != "d", Series([True, True, True])) @@ -3818,10 +3818,10 @@ def test_cat_equality(self): self.assertTrue(((~(f == a) == (f != a)).all())) # non-equality is not comparable - self.assertRaises(TypeError, lambda: a < b) - self.assertRaises(TypeError, lambda: b < a) - self.assertRaises(TypeError, lambda: a > b) - self.assertRaises(TypeError, lambda: b > a) + pytest.raises(TypeError, lambda: a < b) + pytest.raises(TypeError, lambda: b < a) + pytest.raises(TypeError, lambda: a > b) + pytest.raises(TypeError, lambda: b > a) def test_concat_append(self): cat = pd.Categorical(["a", "b"], categories=["a", "b"]) @@ -3921,7 +3921,7 @@ def test_categorical_index_preserver(self): df3 = DataFrame({'A': a, 'B': pd.Categorical(b, categories=list('abc')) }).set_index('B') - self.assertRaises(TypeError, lambda: pd.concat([df2, df3])) + pytest.raises(TypeError, lambda: pd.concat([df2, df3])) def test_merge(self): # GH 9426 @@ -4046,7 +4046,7 @@ def test_na_actions(self): def f(): df.fillna(value={"cats": 4, "vals": "c"}) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) res = df.fillna(method='pad') tm.assert_frame_equal(res, df_exp_fill) @@ -4104,7 +4104,7 @@ def test_astype_to_other(self): expected = s tm.assert_series_equal(s.astype('category'), expected) tm.assert_series_equal(s.astype(CategoricalDtype()), expected) - self.assertRaises(ValueError, lambda: s.astype('float64')) + pytest.raises(ValueError, lambda: s.astype('float64')) cat = Series(Categorical(['a', 'b', 'b', 'a', 'a', 'c', 'c', 'c'])) exp = Series(['a', 'b', 'b', 'a', 'a', 'c', 'c', 'c']) @@ -4142,7 +4142,7 @@ def cmp(a, b): # invalid conversion (these are NOT a dtype) for invalid in [lambda x: x.astype(pd.Categorical), lambda x: x.astype('object').astype(pd.Categorical)]: - self.assertRaises(TypeError, lambda: invalid(s)) + pytest.raises(TypeError, lambda: invalid(s)) def test_astype_categorical(self): @@ -4150,7 +4150,7 @@ def test_astype_categorical(self): tm.assert_categorical_equal(cat, cat.astype('category')) tm.assert_almost_equal(np.array(cat), cat.astype('object')) - self.assertRaises(ValueError, lambda: cat.astype(float)) + pytest.raises(ValueError, lambda: cat.astype(float)) def test_to_records(self): @@ -4177,28 +4177,28 @@ def test_numeric_like_ops(self): # numeric ops should not succeed for op in ['__add__', '__sub__', '__mul__', '__truediv__']: - self.assertRaises(TypeError, - lambda: getattr(self.cat, op)(self.cat)) + pytest.raises(TypeError, + lambda: getattr(self.cat, op)(self.cat)) # reduction ops should not succeed (unless specifically defined, e.g. # min/max) s = self.cat['value_group'] for op in ['kurt', 'skew', 'var', 'std', 'mean', 'sum', 'median']: - self.assertRaises(TypeError, - lambda: getattr(s, op)(numeric_only=False)) + pytest.raises(TypeError, + lambda: getattr(s, op)(numeric_only=False)) # mad technically works because it takes always the numeric data # numpy ops s = pd.Series(pd.Categorical([1, 2, 3, 4])) - self.assertRaises(TypeError, lambda: np.sum(s)) + pytest.raises(TypeError, lambda: np.sum(s)) # numeric ops on a Series for op in ['__add__', '__sub__', '__mul__', '__truediv__']: - self.assertRaises(TypeError, lambda: getattr(s, op)(2)) + pytest.raises(TypeError, lambda: getattr(s, op)(2)) # invalid ufunc - self.assertRaises(TypeError, lambda: np.log(s)) + pytest.raises(TypeError, lambda: np.log(s)) def test_cat_tab_completition(self): # test the tab completion display diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 5222f8fc18520..435fca14d164f 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -1,5 +1,7 @@ # -*- coding: utf-8 -*- +import pytest + import numpy as np from pandas import Series, Timestamp @@ -153,10 +155,10 @@ def test_random_state(): assert com._random_state() is np.random # Error for floats or strings - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): com._random_state('test') - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): com._random_state(5.5) diff --git a/pandas/tests/test_config.py b/pandas/tests/test_config.py index c58aada193b15..f260895e74dda 100644 --- a/pandas/tests/test_config.py +++ b/pandas/tests/test_config.py @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +import pytest + import pandas as pd import unittest import warnings @@ -40,26 +42,26 @@ def test_is_one_of_factory(self): v(12) v(None) - self.assertRaises(ValueError, v, 1.1) + pytest.raises(ValueError, v, 1.1) def test_register_option(self): self.cf.register_option('a', 1, 'doc') # can't register an already registered option - self.assertRaises(KeyError, self.cf.register_option, 'a', 1, 'doc') + pytest.raises(KeyError, self.cf.register_option, 'a', 1, 'doc') # can't register an already registered option - self.assertRaises(KeyError, self.cf.register_option, 'a.b.c.d1', 1, - 'doc') - self.assertRaises(KeyError, self.cf.register_option, 'a.b.c.d2', 1, - 'doc') + pytest.raises(KeyError, self.cf.register_option, 'a.b.c.d1', 1, + 'doc') + pytest.raises(KeyError, self.cf.register_option, 'a.b.c.d2', 1, + 'doc') # no python keywords - self.assertRaises(ValueError, self.cf.register_option, 'for', 0) - self.assertRaises(ValueError, self.cf.register_option, 'a.for.b', 0) + pytest.raises(ValueError, self.cf.register_option, 'for', 0) + pytest.raises(ValueError, self.cf.register_option, 'a.for.b', 0) # must be valid identifier (ensure attribute access works) - self.assertRaises(ValueError, self.cf.register_option, - 'Oh my Goddess!', 0) + pytest.raises(ValueError, self.cf.register_option, + 'Oh my Goddess!', 0) # we can register options several levels deep # without predefining the intermediate steps @@ -82,7 +84,7 @@ def test_describe_option(self): self.cf.register_option('l', "foo") # non-existent keys raise KeyError - self.assertRaises(KeyError, self.cf.describe_option, 'no.such.key') + pytest.raises(KeyError, self.cf.describe_option, 'no.such.key') # we can get the description for any key we registered self.assertTrue( @@ -128,7 +130,7 @@ def test_case_insensitive(self): self.assertEqual(self.cf.get_option('kAnBaN'), 2) # gets of non-existent keys fail - self.assertRaises(KeyError, self.cf.get_option, 'no_such_option') + pytest.raises(KeyError, self.cf.get_option, 'no_such_option') self.cf.deprecate_option('KanBan') self.assertTrue(self.cf._is_deprecated('kAnBaN')) @@ -144,7 +146,7 @@ def test_get_option(self): self.assertTrue(self.cf.get_option('b.b') is None) # gets of non-existent keys fail - self.assertRaises(KeyError, self.cf.get_option, 'no_such_option') + pytest.raises(KeyError, self.cf.get_option, 'no_such_option') def test_set_option(self): self.cf.register_option('a', 1, 'doc') @@ -163,16 +165,16 @@ def test_set_option(self): self.assertEqual(self.cf.get_option('b.c'), 'wurld') self.assertEqual(self.cf.get_option('b.b'), 1.1) - self.assertRaises(KeyError, self.cf.set_option, 'no.such.key', None) + pytest.raises(KeyError, self.cf.set_option, 'no.such.key', None) def test_set_option_empty_args(self): - self.assertRaises(ValueError, self.cf.set_option) + pytest.raises(ValueError, self.cf.set_option) def test_set_option_uneven_args(self): - self.assertRaises(ValueError, self.cf.set_option, 'a.b', 2, 'b.c') + pytest.raises(ValueError, self.cf.set_option, 'a.b', 2, 'b.c') def test_set_option_invalid_single_argument_type(self): - self.assertRaises(ValueError, self.cf.set_option, 2) + pytest.raises(ValueError, self.cf.set_option, 2) def test_set_option_multiple(self): self.cf.register_option('a', 1, 'doc') @@ -193,23 +195,23 @@ def test_validation(self): self.cf.register_option('a', 1, 'doc', validator=self.cf.is_int) self.cf.register_option('b.c', 'hullo', 'doc2', validator=self.cf.is_text) - self.assertRaises(ValueError, self.cf.register_option, 'a.b.c.d2', - 'NO', 'doc', validator=self.cf.is_int) + pytest.raises(ValueError, self.cf.register_option, 'a.b.c.d2', + 'NO', 'doc', validator=self.cf.is_int) self.cf.set_option('a', 2) # int is_int self.cf.set_option('b.c', 'wurld') # str is_str - self.assertRaises( + pytest.raises( ValueError, self.cf.set_option, 'a', None) # None not is_int - self.assertRaises(ValueError, self.cf.set_option, 'a', 'ab') - self.assertRaises(ValueError, self.cf.set_option, 'b.c', 1) + pytest.raises(ValueError, self.cf.set_option, 'a', 'ab') + pytest.raises(ValueError, self.cf.set_option, 'b.c', 1) validator = self.cf.is_one_of_factory([None, self.cf.is_callable]) self.cf.register_option('b', lambda: None, 'doc', validator=validator) self.cf.set_option('b', '%.1f'.format) # Formatter is callable self.cf.set_option('b', None) # Formatter is none (default) - self.assertRaises(ValueError, self.cf.set_option, 'b', '%.1f') + pytest.raises(ValueError, self.cf.set_option, 'b', '%.1f') def test_reset_option(self): self.cf.register_option('a', 1, 'doc', validator=self.cf.is_int) @@ -279,7 +281,7 @@ def test_deprecate_option(self): self.assertTrue( 'nifty_ver' in str(w[-1])) # with the removal_ver quoted - self.assertRaises( + pytest.raises( KeyError, self.cf.deprecate_option, 'a') # can't depr. twice self.cf.deprecate_option('b.c', 'zounds!') @@ -415,8 +417,8 @@ def f3(key): self.cf.reset_option("a") self.assertEqual(options.a, self.cf.get_option("a", 0)) - self.assertRaises(KeyError, f) - self.assertRaises(KeyError, f2) + pytest.raises(KeyError, f) + pytest.raises(KeyError, f2) # make sure callback kicks when using this form of setting options.c = 1 diff --git a/pandas/tests/test_lib.py b/pandas/tests/test_lib.py index 481b1ca3cb72a..5c3e6adb48808 100644 --- a/pandas/tests/test_lib.py +++ b/pandas/tests/test_lib.py @@ -24,8 +24,8 @@ def test_max_len_string_array(self): self.assertTrue(lib.max_len_string_array(arr), 3) # raises - tm.assertRaises(TypeError, - lambda: lib.max_len_string_array(arr.astype('U'))) + pytest.raises(TypeError, + lambda: lib.max_len_string_array(arr.astype('U'))) def test_fast_unique_multiple_list_gen_sort(self): keys = [['p', 'a'], ['n', 'd'], ['a', 's']] diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index d56366ca8a545..d7ba7f1c6fac6 100755 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -272,14 +272,14 @@ def test_series_getitem(self): tm.assert_series_equal(result, expected) # key error - self.assertRaises(KeyError, s.__getitem__, (2000, 3, 4)) + pytest.raises(KeyError, s.__getitem__, (2000, 3, 4)) def test_series_getitem_corner(self): s = self.ymd['A'] # don't segfault, GH #495 # out of bounds access - self.assertRaises(IndexError, s.__getitem__, len(self.ymd)) + pytest.raises(IndexError, s.__getitem__, len(self.ymd)) # generator result = s[(x > 0 for x in s)] @@ -509,7 +509,7 @@ def test_xs_level(self): def f(x): x[:] = 10 - self.assertRaises(com.SettingWithCopyError, f, result) + pytest.raises(com.SettingWithCopyError, f, result) def test_xs_level_multiple(self): from pandas import read_table @@ -533,7 +533,7 @@ def test_xs_level_multiple(self): def f(x): x[:] = 10 - self.assertRaises(com.SettingWithCopyError, f, result) + pytest.raises(com.SettingWithCopyError, f, result) # GH2107 dates = lrange(20111201, 20111205) @@ -574,7 +574,7 @@ def test_xs_level_series(self): # not implementing this for now - self.assertRaises(TypeError, s.__getitem__, (2000, slice(3, 4))) + pytest.raises(TypeError, s.__getitem__, (2000, slice(3, 4))) # result = s[2000, 3:4] # lv =s.index.get_level_values(1) @@ -641,7 +641,7 @@ def test_getitem_int(self): tm.assert_frame_equal(result, expected) # raises exception - self.assertRaises(KeyError, frame.loc.__getitem__, 3) + pytest.raises(KeyError, frame.loc.__getitem__, 3) # however this will work result = self.frame.iloc[2] @@ -709,8 +709,8 @@ def test_getitem_partial_column_select(self): result = df.ix[('a', 'y'), [1, 0]] tm.assert_frame_equal(result, expected) - self.assertRaises(KeyError, df.loc.__getitem__, - (('a', 'foo'), slice(None, None))) + pytest.raises(KeyError, df.loc.__getitem__, + (('a', 'foo'), slice(None, None))) def test_delevel_infer_dtype(self): tuples = [tuple @@ -1323,7 +1323,7 @@ def f(): df['foo']['one'] = 2 return df - self.assertRaises(com.SettingWithCopyError, f) + pytest.raises(com.SettingWithCopyError, f) try: df = f() @@ -1356,8 +1356,8 @@ def test_count(self): tm.assert_series_equal(result, expect, check_names=False) self.assertEqual(result.index.name, 'a') - self.assertRaises(KeyError, series.count, 'x') - self.assertRaises(KeyError, frame.count, level='x') + pytest.raises(KeyError, series.count, 'x') + pytest.raises(KeyError, frame.count, level='x') AGG_FUNCTIONS = ['sum', 'prod', 'min', 'max', 'median', 'mean', 'skew', 'mad', 'std', 'var', 'sem'] @@ -1552,8 +1552,8 @@ def test_unstack_group_index_overflow(self): self.assertEqual(result.shape, (500, 2)) def test_getitem_lowerdim_corner(self): - self.assertRaises(KeyError, self.frame.loc.__getitem__, - (('bar', 'three'), 'B')) + pytest.raises(KeyError, self.frame.loc.__getitem__, + (('bar', 'three'), 'B')) # in theory should be inserting in a sorted space???? self.frame.loc[('bar', 'three'), 'B'] = 0 @@ -1575,8 +1575,8 @@ def test_partial_ix_missing(self): # self.assertTrue((self.ymd.loc[2000]['A'] == 0).all()) # Pretty sure the second (and maybe even the first) is already wrong. - self.assertRaises(Exception, self.ymd.loc.__getitem__, (2000, 6)) - self.assertRaises(Exception, self.ymd.loc.__getitem__, (2000, 6), 0) + pytest.raises(Exception, self.ymd.loc.__getitem__, (2000, 6)) + pytest.raises(Exception, self.ymd.loc.__getitem__, (2000, 6), 0) # --------------------------------------------------------------------- @@ -1600,7 +1600,7 @@ def test_level_with_tuples(self): tm.assert_series_equal(result, expected) tm.assert_series_equal(result2, expected) - self.assertRaises(KeyError, series.__getitem__, (('foo', 'bar', 0), 2)) + pytest.raises(KeyError, series.__getitem__, (('foo', 'bar', 0), 2)) result = frame.loc[('foo', 'bar', 0)] result2 = frame.xs(('foo', 'bar', 0)) diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py index 20a9238310ccf..1aad2f5224c0d 100644 --- a/pandas/tests/test_nanops.py +++ b/pandas/tests/test_nanops.py @@ -3,6 +3,8 @@ from functools import partial +import pytest + import warnings import numpy as np from pandas import Series, isnull, _np_version_under1p9 @@ -774,7 +776,7 @@ def test_ndarray(self): # Test non-convertible string ndarray s_values = np.array(['foo', 'bar', 'baz'], dtype=object) - self.assertRaises(ValueError, lambda: nanops._ensure_numeric(s_values)) + pytest.raises(ValueError, lambda: nanops._ensure_numeric(s_values)) def test_convertable_values(self): self.assertTrue(np.allclose(nanops._ensure_numeric('1'), 1.0), @@ -785,9 +787,9 @@ def test_convertable_values(self): 'Failed for convertible complex string') def test_non_convertable_values(self): - self.assertRaises(TypeError, lambda: nanops._ensure_numeric('foo')) - self.assertRaises(TypeError, lambda: nanops._ensure_numeric({})) - self.assertRaises(TypeError, lambda: nanops._ensure_numeric([])) + pytest.raises(TypeError, lambda: nanops._ensure_numeric('foo')) + pytest.raises(TypeError, lambda: nanops._ensure_numeric({})) + pytest.raises(TypeError, lambda: nanops._ensure_numeric([])) class TestNanvarFixedValues(tm.TestCase): diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index fbd8aa72c941d..703c8cc80e8f9 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -48,7 +48,7 @@ def test_pickle(self): def test_rank(self): with catch_warnings(record=True): - self.assertRaises(NotImplementedError, lambda: self.panel.rank()) + pytest.raises(NotImplementedError, lambda: self.panel.rank()) def test_cumsum(self): with catch_warnings(record=True): @@ -59,8 +59,8 @@ def not_hashable(self): with catch_warnings(record=True): c_empty = Panel() c = Panel(Panel([[[1]]])) - self.assertRaises(TypeError, hash, c_empty) - self.assertRaises(TypeError, hash, c) + pytest.raises(TypeError, hash, c_empty) + pytest.raises(TypeError, hash, c) class SafeForLongAndSparse(object): @@ -176,7 +176,7 @@ def wrapper(x): if not tm._incompat_bottleneck_version(name): assert_frame_equal(result, obj.apply(skipna_wrapper, axis=i)) - self.assertRaises(Exception, f, axis=obj.ndim) + pytest.raises(Exception, f, axis=obj.ndim) # Unimplemented numeric_only parameter. if 'numeric_only' in signature(f).args: @@ -287,8 +287,8 @@ def test_arith(self): self._test_op(self.panel, lambda x, y: x / y) # panel / 1 self._test_op(self.panel, lambda x, y: x ** y) # panel ** 1 - self.assertRaises(Exception, self.panel.__add__, - self.panel['ItemA']) + pytest.raises(Exception, self.panel.__add__, + self.panel['ItemA']) @staticmethod def _test_op(panel, op): @@ -375,7 +375,7 @@ def test_raise_when_not_implemented(self): ops = ['add', 'sub', 'mul', 'truediv', 'floordiv', 'div', 'mod', 'pow'] for op in ops: - with self.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): getattr(p, op)(d, axis=0) def test_select(self): @@ -440,7 +440,7 @@ def test_abs(self): class CheckIndexing(object): def test_getitem(self): - self.assertRaises(Exception, self.panel.__getitem__, 'ItemQ') + pytest.raises(Exception, self.panel.__getitem__, 'ItemQ') def test_delitem_and_pop(self): with catch_warnings(record=True): @@ -451,7 +451,7 @@ def test_delitem_and_pop(self): del self.panel['ItemB'] self.assertNotIn('ItemB', self.panel.items) - self.assertRaises(Exception, self.panel.__delitem__, 'ItemB') + pytest.raises(Exception, self.panel.__delitem__, 'ItemB') values = np.empty((3, 3, 3)) values[0] = 0 @@ -482,7 +482,7 @@ def test_setitem(self): # LongPanel with one item lp = self.panel.filter(['ItemA', 'ItemB']).to_frame() - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): self.panel['ItemE'] = lp # DataFrame @@ -509,8 +509,8 @@ def test_setitem(self): self.panel['ItemP'] = self.panel['ItemA'] > 0 self.assertEqual(self.panel['ItemP'].values.dtype, np.bool_) - self.assertRaises(TypeError, self.panel.__setitem__, 'foo', - self.panel.loc[['ItemP']]) + pytest.raises(TypeError, self.panel.__setitem__, 'foo', + self.panel.loc[['ItemP']]) # bad shape p = Panel(np.random.randn(4, 3, 2)) @@ -564,7 +564,7 @@ def test_major_xs(self): # not contained idx = self.panel.major_axis[0] - BDay() - self.assertRaises(Exception, self.panel.major_xs, idx) + pytest.raises(Exception, self.panel.major_xs, idx) def test_major_xs_mixed(self): with catch_warnings(record=True): @@ -583,7 +583,7 @@ def test_minor_xs(self): assert_series_equal(xs['ItemA'], ref[idx], check_names=False) # not contained - self.assertRaises(Exception, self.panel.minor_xs, 'E') + pytest.raises(Exception, self.panel.minor_xs, 'E') def test_minor_xs_mixed(self): with catch_warnings(record=True): @@ -979,7 +979,7 @@ def test_constructor_cast(self): # can't cast data = [[['foo', 'bar', 'baz']]] - self.assertRaises(ValueError, Panel, data, dtype=float) + pytest.raises(ValueError, Panel, data, dtype=float) def test_constructor_empty_panel(self): with catch_warnings(record=True): @@ -1122,10 +1122,10 @@ def test_constructor_dict_mixed(self): # corner, blow up data['ItemB'] = data['ItemB'][:-1] - self.assertRaises(Exception, Panel, data) + pytest.raises(Exception, Panel, data) data['ItemB'] = self.panel['ItemB'].values[:, :-1] - self.assertRaises(Exception, Panel, data) + pytest.raises(Exception, Panel, data) def test_ctor_orderedDict(self): with catch_warnings(record=True): @@ -1238,7 +1238,7 @@ def test_astype(self): expected = Panel(str_data, ['a', 'b'], ['c', 'd'], ['e', 'f']) assert_panel_equal(panel.astype(str), expected) - self.assertRaises(NotImplementedError, panel.astype, {0: str}) + pytest.raises(NotImplementedError, panel.astype, {0: str}) def test_apply(self): with catch_warnings(record=True): @@ -1409,9 +1409,9 @@ def test_reindex(self): assert_frame_equal(result['ItemB'], ref.reindex(index=new_major)) # raise exception put both major and major_axis - self.assertRaises(Exception, self.panel.reindex, - major_axis=new_major, - major=new_major) + pytest.raises(Exception, self.panel.reindex, + major_axis=new_major, + major=new_major) # minor new_minor = list(self.panel.minor_axis[:2]) @@ -1511,7 +1511,7 @@ def test_take(self): result = self.panel.take([3, -1, 1, 2], axis=2) assert_panel_equal(result, expected) - self.assertRaises(Exception, self.panel.take, [4, 0, 1, 2], axis=2) + pytest.raises(Exception, self.panel.take, [4, 0, 1, 2], axis=2) def test_sort_index(self): with catch_warnings(record=True): @@ -1563,17 +1563,17 @@ def test_fillna(self): filled = empty.fillna(0) assert_panel_equal(filled, empty) - self.assertRaises(ValueError, self.panel.fillna) - self.assertRaises(ValueError, self.panel.fillna, 5, method='ffill') + pytest.raises(ValueError, self.panel.fillna) + pytest.raises(ValueError, self.panel.fillna, 5, method='ffill') - self.assertRaises(TypeError, self.panel.fillna, [1, 2]) - self.assertRaises(TypeError, self.panel.fillna, (1, 2)) + pytest.raises(TypeError, self.panel.fillna, [1, 2]) + pytest.raises(TypeError, self.panel.fillna, (1, 2)) # limit not implemented when only value is specified p = Panel(np.random.randn(3, 4, 5)) p.iloc[0:2, 0:2, 0:2] = np.nan - self.assertRaises(NotImplementedError, - lambda: p.fillna(999, limit=1)) + pytest.raises(NotImplementedError, + lambda: p.fillna(999, limit=1)) # Test in place fillNA # Expected result @@ -1680,7 +1680,7 @@ def test_transpose(self): result = self.panel.transpose(2, 0, 1) assert_panel_equal(result, expected) - self.assertRaises(ValueError, self.panel.transpose, 0, 0, 1) + pytest.raises(ValueError, self.panel.transpose, 0, 0, 1) def test_transpose_copy(self): with catch_warnings(record=True): @@ -2014,7 +2014,7 @@ def test_tshift(self): assert_panel_equal(unshifted, inferred_ts) no_freq = panel.iloc[:, [0, 5, 7], :] - self.assertRaises(ValueError, no_freq.tshift) + pytest.raises(ValueError, no_freq.tshift) def test_pct_change(self): with catch_warnings(record=True): @@ -2276,7 +2276,7 @@ def check_drop(drop_val, axis_number, aliases, expected): expected = Panel({"One": df}) check_drop('Two', 0, ['items'], expected) - self.assertRaises(ValueError, panel.drop, 'Three') + pytest.raises(ValueError, panel.drop, 'Three') # errors = 'ignore' dropped = panel.drop('Three', errors='ignore') @@ -2405,8 +2405,8 @@ def test_update_raise(self): [1.5, np.nan, 3.], [1.5, np.nan, 3.]]]) - self.assertRaises(Exception, pan.update, *(pan, ), - **{'raise_conflict': True}) + pytest.raises(Exception, pan.update, *(pan, ), + **{'raise_conflict': True}) def test_all_any(self): self.assertTrue((self.panel.all(axis=0).values == nanall( @@ -2423,8 +2423,8 @@ def test_all_any(self): self.panel, axis=2).T).all()) def test_all_any_unhandled(self): - self.assertRaises(NotImplementedError, self.panel.all, bool_only=True) - self.assertRaises(NotImplementedError, self.panel.any, bool_only=True) + pytest.raises(NotImplementedError, self.panel.all, bool_only=True) + pytest.raises(NotImplementedError, self.panel.any, bool_only=True) class TestLongPanel(tm.TestCase): @@ -2580,8 +2580,8 @@ def test_truncate(self): assert_panel_equal(wp_trunc, lp_trunc.to_panel()) # throw proper exception - self.assertRaises(Exception, lp2.truncate, wp.major_axis[-2], - wp.major_axis[2]) + pytest.raises(Exception, lp2.truncate, wp.major_axis[-2], + wp.major_axis[2]) def test_axis_dummies(self): from pandas.core.reshape.reshape import make_axis_dummies @@ -2650,8 +2650,8 @@ def test_join(self): self.assertEqual(len(joined.columns), 3) - self.assertRaises(Exception, lp1.join, - self.panel.filter(['ItemB', 'ItemC'])) + pytest.raises(Exception, lp1.join, + self.panel.filter(['ItemB', 'ItemC'])) def test_pivot(self): with catch_warnings(record=True): @@ -2672,7 +2672,7 @@ def test_pivot(self): a, b, c = (np.array([1, 2, 3, 4, 4]), np.array(['a', 'a', 'a', 'a', 'a']), np.array([1., 2., 3., 4., 5.])) - self.assertRaises(Exception, pivot, a, b, c) + pytest.raises(Exception, pivot, a, b, c) # corner case, empty df = pivot(np.array([]), np.array([]), np.array([])) diff --git a/pandas/tests/test_panel4d.py b/pandas/tests/test_panel4d.py index 8dfbe547e15fb..f55452b44731c 100644 --- a/pandas/tests/test_panel4d.py +++ b/pandas/tests/test_panel4d.py @@ -145,7 +145,7 @@ def wrapper(x): expected = obj.apply(skipna_wrapper, axis=i) assert_panel_equal(result, expected) - self.assertRaises(Exception, f, axis=obj.ndim) + pytest.raises(Exception, f, axis=obj.ndim) class SafeForSparse(object): @@ -220,8 +220,8 @@ def test_arith(self): self._test_op(self.panel4d, lambda x, y: y / x) self._test_op(self.panel4d, lambda x, y: y ** x) - self.assertRaises(Exception, self.panel4d.__add__, - self.panel4d['l1']) + pytest.raises(Exception, self.panel4d.__add__, + self.panel4d['l1']) @staticmethod def _test_op(panel4d, op): @@ -307,7 +307,7 @@ def test_abs(self): class CheckIndexing(object): def test_getitem(self): - self.assertRaises(Exception, self.panel4d.__getitem__, 'ItemQ') + pytest.raises(Exception, self.panel4d.__getitem__, 'ItemQ') def test_delitem_and_pop(self): @@ -319,7 +319,7 @@ def test_delitem_and_pop(self): del self.panel4d['l3'] self.assertNotIn('l3', self.panel4d.labels) - self.assertRaises(Exception, self.panel4d.__delitem__, 'l3') + pytest.raises(Exception, self.panel4d.__delitem__, 'l3') values = np.empty((4, 4, 4, 4)) values[0] = 0 @@ -395,7 +395,7 @@ def test_setitem_by_indexer(self): def func(): self.panel4d.iloc[0] = p - self.assertRaises(NotImplementedError, func) + pytest.raises(NotImplementedError, func) # DataFrame panel4dc = self.panel4d.copy() @@ -478,7 +478,7 @@ def test_major_xs(self): # not contained idx = self.panel4d.major_axis[0] - BDay() - self.assertRaises(Exception, self.panel4d.major_xs, idx) + pytest.raises(Exception, self.panel4d.major_xs, idx) def test_major_xs_mixed(self): self.panel4d['l4'] = 'foo' @@ -497,7 +497,7 @@ def test_minor_xs(self): assert_series_equal(xs['l1'].T['ItemA'], ref[idx], check_names=False) # not contained - self.assertRaises(Exception, self.panel4d.minor_xs, 'E') + pytest.raises(Exception, self.panel4d.minor_xs, 'E') def test_minor_xs_mixed(self): self.panel4d['l4'] = 'foo' @@ -677,7 +677,7 @@ def test_constructor_cast(self): # can't cast data = [[['foo', 'bar', 'baz']]] - self.assertRaises(ValueError, Panel, data, dtype=float) + pytest.raises(ValueError, Panel, data, dtype=float) def test_consolidate(self): with catch_warnings(record=True): @@ -724,10 +724,10 @@ def test_constructor_dict_mixed(self): # corner, blow up data['l2'] = data['l2']['ItemB'] - self.assertRaises(Exception, Panel4D, data) + pytest.raises(Exception, Panel4D, data) data['l2'] = self.panel4d['l2'].values[:, :, :-1] - self.assertRaises(Exception, Panel4D, data) + pytest.raises(Exception, Panel4D, data) def test_constructor_resize(self): with catch_warnings(record=True): @@ -786,8 +786,8 @@ def test_reindex(self): result['l2']['ItemB'], ref['ItemB'].reindex(index=new_major)) # raise exception put both major and major_axis - self.assertRaises(Exception, self.panel4d.reindex, - major_axis=new_major, major=new_major) + pytest.raises(Exception, self.panel4d.reindex, + major_axis=new_major, major=new_major) # minor new_minor = list(self.panel4d.minor_axis[:2]) @@ -824,8 +824,8 @@ def test_reindex(self): def test_not_hashable(self): with catch_warnings(record=True): p4D_empty = Panel4D() - self.assertRaises(TypeError, hash, p4D_empty) - self.assertRaises(TypeError, hash, self.panel4d) + pytest.raises(TypeError, hash, p4D_empty) + pytest.raises(TypeError, hash, self.panel4d) def test_reindex_like(self): # reindex_like @@ -861,8 +861,8 @@ def test_fillna(self): filled = self.panel4d.fillna(0) self.assertTrue(np.isfinite(filled.values).all()) - self.assertRaises(NotImplementedError, - self.panel4d.fillna, method='pad') + pytest.raises(NotImplementedError, + self.panel4d.fillna, method='pad') def test_swapaxes(self): with catch_warnings(record=True): diff --git a/pandas/tests/test_panelnd.py b/pandas/tests/test_panelnd.py index 7ecc773cd7bea..33c37e9c8feb2 100644 --- a/pandas/tests/test_panelnd.py +++ b/pandas/tests/test_panelnd.py @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +import pytest + from warnings import catch_warnings from pandas.core import panelnd from pandas.core.panel import Panel @@ -47,18 +49,18 @@ def test_4d_construction_alt(self): def test_4d_construction_error(self): # create a 4D - self.assertRaises(Exception, - panelnd.create_nd_panel_factory, - klass_name='Panel4D', - orders=['labels', 'items', 'major_axis', - 'minor_axis'], - slices={'items': 'items', - 'major_axis': 'major_axis', - 'minor_axis': 'minor_axis'}, - slicer='foo', - aliases={'major': 'major_axis', - 'minor': 'minor_axis'}, - stat_axis=2) + pytest.raises(Exception, + panelnd.create_nd_panel_factory, + klass_name='Panel4D', + orders=['labels', 'items', 'major_axis', + 'minor_axis'], + slices={'items': 'items', + 'major_axis': 'major_axis', + 'minor_axis': 'minor_axis'}, + slicer='foo', + aliases={'major': 'major_axis', + 'minor': 'minor_axis'}, + stat_axis=2) def test_5d_construction(self): diff --git a/pandas/tests/test_resample.py b/pandas/tests/test_resample.py index 2a8696af36268..e5795eea12135 100644 --- a/pandas/tests/test_resample.py +++ b/pandas/tests/test_resample.py @@ -4,6 +4,7 @@ from datetime import datetime, timedelta from functools import partial +import pytest import numpy as np import pandas as pd @@ -107,18 +108,18 @@ def test_api_changes_v018(self): # invalids as these can be setting operations r = self.series.resample('H') - self.assertRaises(ValueError, lambda: r.iloc[0]) - self.assertRaises(ValueError, lambda: r.iat[0]) - self.assertRaises(ValueError, lambda: r.loc[0]) - self.assertRaises(ValueError, lambda: r.loc[ + pytest.raises(ValueError, lambda: r.iloc[0]) + pytest.raises(ValueError, lambda: r.iat[0]) + pytest.raises(ValueError, lambda: r.loc[0]) + pytest.raises(ValueError, lambda: r.loc[ Timestamp('2013-01-01 00:00:00', offset='H')]) - self.assertRaises(ValueError, lambda: r.at[ + pytest.raises(ValueError, lambda: r.at[ Timestamp('2013-01-01 00:00:00', offset='H')]) def f(): r[0] = 5 - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # str/repr r = self.series.resample('H') @@ -178,7 +179,7 @@ def f(): df = self.series.to_frame('foo') # same as prior versions for DataFrame - self.assertRaises(KeyError, lambda: df.resample('H')[0]) + pytest.raises(KeyError, lambda: df.resample('H')[0]) # compat for Series # but we cannot be sure that we need a warning here @@ -268,9 +269,9 @@ def test_getitem(self): def test_select_bad_cols(self): g = self.frame.resample('H') - self.assertRaises(KeyError, g.__getitem__, ['D']) + pytest.raises(KeyError, g.__getitem__, ['D']) - self.assertRaises(KeyError, g.__getitem__, ['A', 'D']) + pytest.raises(KeyError, g.__getitem__, ['A', 'D']) with tm.assertRaisesRegexp(KeyError, '^[^A]+$'): # A should not be referenced as a bad column... # will have to rethink regex if you change message! @@ -283,13 +284,13 @@ def test_attribute_access(self): # getting with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - self.assertRaises(AttributeError, lambda: r.F) + pytest.raises(AttributeError, lambda: r.F) # setting def f(): r.F = 'bah' - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) def test_api_compat_before_use(self): @@ -371,7 +372,7 @@ def test_fillna(self): result = r.fillna(method='bfill') assert_series_equal(result, expected) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): r.fillna(0) def test_apply_without_aggregation(self): @@ -598,7 +599,7 @@ def f(): t[['A']].agg({'A': ['sum', 'std'], 'B': ['mean', 'std']}) - self.assertRaises(SpecificationError, f) + pytest.raises(SpecificationError, f) def test_agg_nested_dicts(self): @@ -625,7 +626,7 @@ def test_agg_nested_dicts(self): def f(): t.aggregate({'r1': {'A': ['mean', 'sum']}, 'r2': {'B': ['mean', 'sum']}}) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) for t in cases: expected = pd.concat([t['A'].mean(), t['A'].std(), t['B'].mean(), @@ -658,23 +659,23 @@ def test_selection_api_validation(self): index=index) # non DatetimeIndex - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): df.resample('2D', level='v') - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.resample('2D', on='date', level='d') - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): df.resample('2D', on=['a', 'date']) - with tm.assertRaises(KeyError): + with pytest.raises(KeyError): df.resample('2D', level=['a', 'date']) # upsampling not allowed - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.resample('2D', level='d').asfreq() - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): df.resample('2D', on='date').asfreq() exp = df_exp.resample('2D').sum() @@ -754,7 +755,7 @@ def test_resample_interpolate(self): def test_raises_on_non_datetimelike_index(self): # this is a non datetimelike index xp = DataFrame() - self.assertRaises(TypeError, lambda: xp.resample('A').mean()) + pytest.raises(TypeError, lambda: xp.resample('A').mean()) def test_resample_empty_series(self): # GH12771 & GH12868 @@ -839,7 +840,7 @@ def test_resample_loffset_arg_type(self): # GH 13022, 7687 - TODO: fix resample w/ TimedeltaIndex if isinstance(expected.index, TimedeltaIndex): - with tm.assertRaises(AssertionError): + with pytest.raises(AssertionError): assert_frame_equal(result_agg, expected) assert_frame_equal(result_how, expected) else: @@ -1476,7 +1477,7 @@ def test_asfreq_non_unique(self): rng2 = rng.repeat(2).values ts = Series(np.random.randn(len(rng2)), index=rng2) - self.assertRaises(Exception, ts.asfreq, 'B') + pytest.raises(Exception, ts.asfreq, 'B') def test_resample_axis1(self): rng = date_range('1/1/2000', '2/29/2000') @@ -2252,10 +2253,10 @@ def test_selection(self): np.arange(len(index), dtype=np.int64), index], names=['v', 'd'])) - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): df.resample('2D', on='date') - with tm.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): df.resample('2D', level='d') def test_annual_upsample_D_s_f(self): @@ -2318,10 +2319,10 @@ def test_basic_downsample(self): def test_not_subperiod(self): # These are incompatible period rules for resampling ts = _simple_pts('1/1/1990', '6/30/1995', freq='w-wed') - self.assertRaises(ValueError, lambda: ts.resample('a-dec').mean()) - self.assertRaises(ValueError, lambda: ts.resample('q-mar').mean()) - self.assertRaises(ValueError, lambda: ts.resample('M').mean()) - self.assertRaises(ValueError, lambda: ts.resample('w-thu').mean()) + pytest.raises(ValueError, lambda: ts.resample('a-dec').mean()) + pytest.raises(ValueError, lambda: ts.resample('q-mar').mean()) + pytest.raises(ValueError, lambda: ts.resample('M').mean()) + pytest.raises(ValueError, lambda: ts.resample('w-thu').mean()) def test_basic_upsample(self): ts = _simple_pts('1/1/1990', '6/30/1995', freq='M') @@ -2422,7 +2423,7 @@ def test_resample_same_freq(self): def test_resample_incompat_freq(self): - with self.assertRaises(IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): pd.Series(range(3), index=pd.period_range( start='2000', periods=3, freq='M')).resample('W').mean() @@ -2548,7 +2549,7 @@ def test_resample_fill_missing(self): def test_cant_fill_missing_dups(self): rng = PeriodIndex([2000, 2005, 2005, 2007, 2007], freq='A') s = Series(np.random.randn(5), index=rng) - self.assertRaises(Exception, lambda: s.resample('A').ffill()) + pytest.raises(Exception, lambda: s.resample('A').ffill()) def test_resample_5minute(self): rng = period_range('1/1/2000', '1/5/2000', freq='T') diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index 1aa69ce6b231e..107720d90e489 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -2,6 +2,7 @@ # pylint: disable-msg=E1101,W0612 from datetime import datetime, timedelta +import pytest import re from numpy import nan as NA @@ -430,7 +431,7 @@ def test_replace(self): for repl in (None, 3, {'a': 'b'}): for data in (['a', 'b', None], ['a', 'b', 'c', 'ad']): values = klass(data) - self.assertRaises(TypeError, values.str.replace, 'a', repl) + pytest.raises(TypeError, values.str.replace, 'a', repl) def test_replace_callable(self): # GH 15055 @@ -583,8 +584,8 @@ def test_match(self): with tm.assert_produces_warning(FutureWarning): result = values.str.match('.*(BAD[_]+).*(BAD)', as_indexer=True) tm.assert_series_equal(result, exp) - self.assertRaises(ValueError, values.str.match, '.*(BAD[_]+).*(BAD)', - as_indexer=False) + pytest.raises(ValueError, values.str.match, '.*(BAD[_]+).*(BAD)', + as_indexer=False) # mixed mixed = Series(['aBAD_BAD', NA, 'BAD_b_BAD', True, datetime.today(), @@ -655,11 +656,11 @@ def test_extract_expand_False(self): # no groups s_or_idx = klass(['A1', 'B2', 'C3']) f = lambda: s_or_idx.str.extract('[ABC][123]', expand=False) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # only non-capturing groups f = lambda: s_or_idx.str.extract('(?:[AB]).*', expand=False) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # single group renames series/index properly s_or_idx = klass(['A1', 'A2']) @@ -800,11 +801,11 @@ def test_extract_expand_True(self): # no groups s_or_idx = klass(['A1', 'B2', 'C3']) f = lambda: s_or_idx.str.extract('[ABC][123]', expand=True) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # only non-capturing groups f = lambda: s_or_idx.str.extract('(?:[AB]).*', expand=True) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # single group renames series/index properly s_or_idx = klass(['A1', 'A2']) @@ -2619,7 +2620,7 @@ def test_encode_decode(self): def test_encode_decode_errors(self): encodeBase = Series([u('a'), u('b'), u('a\x9d')]) - self.assertRaises(UnicodeEncodeError, encodeBase.str.encode, 'cp1252') + pytest.raises(UnicodeEncodeError, encodeBase.str.encode, 'cp1252') f = lambda x: x.encode('cp1252', 'ignore') result = encodeBase.str.encode('cp1252', 'ignore') @@ -2628,7 +2629,7 @@ def test_encode_decode_errors(self): decodeBase = Series([b'a', b'b', b'a\x9d']) - self.assertRaises(UnicodeDecodeError, decodeBase.str.decode, 'cp1252') + pytest.raises(UnicodeDecodeError, decodeBase.str.decode, 'cp1252') f = lambda x: x.decode('cp1252', 'ignore') result = decodeBase.str.decode('cp1252', 'ignore') @@ -2745,7 +2746,7 @@ def test_method_on_bytes(self): lhs = Series(np.array(list('abc'), 'S1').astype(object)) rhs = Series(np.array(list('def'), 'S1').astype(object)) if compat.PY3: - self.assertRaises(TypeError, lhs.str.cat, rhs) + pytest.raises(TypeError, lhs.str.cat, rhs) else: result = lhs.str.cat(rhs) expected = Series(np.array( diff --git a/pandas/tests/test_testing.py b/pandas/tests/test_testing.py index fc9a828c18f0e..4a9e4f4fbd37a 100644 --- a/pandas/tests/test_testing.py +++ b/pandas/tests/test_testing.py @@ -21,8 +21,8 @@ def _assert_almost_equal_both(self, a, b, **kwargs): assert_almost_equal(b, a, **kwargs) def _assert_not_almost_equal_both(self, a, b, **kwargs): - self.assertRaises(AssertionError, assert_almost_equal, a, b, **kwargs) - self.assertRaises(AssertionError, assert_almost_equal, b, a, **kwargs) + pytest.raises(AssertionError, assert_almost_equal, a, b, **kwargs) + pytest.raises(AssertionError, assert_almost_equal, b, a, **kwargs) def test_assert_almost_equal_numbers(self): self._assert_almost_equal_both(1.1, 1.1) @@ -495,8 +495,8 @@ def _assert_equal(self, x, y, **kwargs): assert_series_equal(y, x, **kwargs) def _assert_not_equal(self, a, b, **kwargs): - self.assertRaises(AssertionError, assert_series_equal, a, b, **kwargs) - self.assertRaises(AssertionError, assert_series_equal, b, a, **kwargs) + pytest.raises(AssertionError, assert_series_equal, a, b, **kwargs) + pytest.raises(AssertionError, assert_series_equal, b, a, **kwargs) def test_equal(self): self._assert_equal(Series(range(3)), Series(range(3))) @@ -520,27 +520,27 @@ def test_less_precise(self): s1 = Series([0.12345], dtype='float64') s2 = Series([0.12346], dtype='float64') - self.assertRaises(AssertionError, assert_series_equal, s1, s2) + pytest.raises(AssertionError, assert_series_equal, s1, s2) self._assert_equal(s1, s2, check_less_precise=True) for i in range(4): self._assert_equal(s1, s2, check_less_precise=i) - self.assertRaises(AssertionError, assert_series_equal, s1, s2, 10) + pytest.raises(AssertionError, assert_series_equal, s1, s2, 10) s1 = Series([0.12345], dtype='float32') s2 = Series([0.12346], dtype='float32') - self.assertRaises(AssertionError, assert_series_equal, s1, s2) + pytest.raises(AssertionError, assert_series_equal, s1, s2) self._assert_equal(s1, s2, check_less_precise=True) for i in range(4): self._assert_equal(s1, s2, check_less_precise=i) - self.assertRaises(AssertionError, assert_series_equal, s1, s2, 10) + pytest.raises(AssertionError, assert_series_equal, s1, s2, 10) # even less than less precise s1 = Series([0.1235], dtype='float32') s2 = Series([0.1236], dtype='float32') - self.assertRaises(AssertionError, assert_series_equal, s1, s2) - self.assertRaises(AssertionError, assert_series_equal, s1, s2, True) + pytest.raises(AssertionError, assert_series_equal, s1, s2) + pytest.raises(AssertionError, assert_series_equal, s1, s2, True) def test_index_dtype(self): df1 = DataFrame.from_records( @@ -589,8 +589,8 @@ def _assert_equal(self, x, y, **kwargs): assert_frame_equal(y, x, **kwargs) def _assert_not_equal(self, a, b, **kwargs): - self.assertRaises(AssertionError, assert_frame_equal, a, b, **kwargs) - self.assertRaises(AssertionError, assert_frame_equal, b, a, **kwargs) + pytest.raises(AssertionError, assert_frame_equal, a, b, **kwargs) + pytest.raises(AssertionError, assert_frame_equal, b, a, **kwargs) def test_equal_with_different_row_order(self): # check_like=True ignores row-column orderings diff --git a/pandas/tests/test_util.py b/pandas/tests/test_util.py index 1fa436df0910d..c9b2e1c9c1c75 100644 --- a/pandas/tests/test_util.py +++ b/pandas/tests/test_util.py @@ -63,11 +63,11 @@ def test_callable_deprecate_kwarg(self): with tm.assert_produces_warning(FutureWarning): result = self.f3(old=x) self.assertEqual(result, x + 1) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): self.f3(old='hello') def test_bad_deprecate_kwarg(self): - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): @deprecate_kwarg('old', 'new', 0) def f4(new=None): pass @@ -336,7 +336,7 @@ def test_more_than_one_ref(self): """ b = b'testing' - with tm.assertRaises(BadMove) as e: + with pytest.raises(BadMove) as e: def handle_success(type_, value, tb): self.assertIs(value.args[0], b) return type(e).handle_success(e, type_, value, tb) # super @@ -385,7 +385,7 @@ def ref_capture(ob): refcount[0] = sys.getrefcount(ob) - 2 return ob - with tm.assertRaises(BadMove): + with pytest.raises(BadMove): # If we intern the string it will still have one reference but now # it is in the intern table so if other people intern the same # string while the mutable buffer holds the first string they will @@ -459,7 +459,7 @@ def test_set_locale(self): new_locale = lang, enc if not tm._can_set_locale(new_locale): - with tm.assertRaises(locale.Error): + with pytest.raises(locale.Error): with tm.set_locale(new_locale): pass else: diff --git a/pandas/tests/test_window.py b/pandas/tests/test_window.py index 98724fe665e58..101ecec783533 100644 --- a/pandas/tests/test_window.py +++ b/pandas/tests/test_window.py @@ -71,9 +71,9 @@ def test_getitem(self): def test_select_bad_cols(self): df = DataFrame([[1, 2]], columns=['A', 'B']) g = df.rolling(window=5) - self.assertRaises(KeyError, g.__getitem__, ['C']) # g[['C']] + pytest.raises(KeyError, g.__getitem__, ['C']) # g[['C']] - self.assertRaises(KeyError, g.__getitem__, ['A', 'C']) # g[['A', 'C']] + pytest.raises(KeyError, g.__getitem__, ['A', 'C']) # g[['A', 'C']] with tm.assertRaisesRegexp(KeyError, '^[^A]+$'): # A should not be referenced as a bad column... # will have to rethink regex if you change message! @@ -84,7 +84,7 @@ def test_attribute_access(self): df = DataFrame([[1, 2]], columns=['A', 'B']) r = df.rolling(window=5) tm.assert_series_equal(r.A.sum(), r['A'].sum()) - self.assertRaises(AttributeError, lambda: r.F) + pytest.raises(AttributeError, lambda: r.F) def tests_skip_nuisance(self): @@ -191,7 +191,7 @@ def f(): r.aggregate({'r1': {'A': ['mean', 'sum']}, 'r2': {'B': ['mean', 'sum']}}) - self.assertRaises(SpecificationError, f) + pytest.raises(SpecificationError, f) expected = pd.concat([r['A'].mean(), r['A'].std(), r['B'].mean(), r['B'].std()], axis=1) @@ -336,13 +336,13 @@ def test_constructor(self): # not valid for w in [2., 'foo', np.array([2])]: - with self.assertRaises(ValueError): + with pytest.raises(ValueError): c(win_type='boxcar', window=2, min_periods=w) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): c(win_type='boxcar', window=2, min_periods=1, center=w) for wt in ['foobar', 1]: - with self.assertRaises(ValueError): + with pytest.raises(ValueError): c(win_type=wt, window=2) def test_numpy_compat(self): @@ -384,16 +384,16 @@ def test_constructor(self): # GH 13383 c(0) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): c(-1) # not valid for w in [2., 'foo', np.array([2])]: - with self.assertRaises(ValueError): + with pytest.raises(ValueError): c(window=w) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): c(window=2, min_periods=w) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): c(window=2, min_periods=1, center=w) def test_constructor_with_win_type(self): @@ -402,7 +402,7 @@ def test_constructor_with_win_type(self): for o in [self.series, self.frame]: c = o.rolling c(0, win_type='boxcar') - with self.assertRaises(ValueError): + with pytest.raises(ValueError): c(-1, win_type='boxcar') def test_constructor_with_timedelta_window(self): @@ -466,9 +466,9 @@ def test_constructor(self): # not valid for w in [2., 'foo', np.array([2])]: - with self.assertRaises(ValueError): + with pytest.raises(ValueError): c(min_periods=w) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): c(min_periods=1, center=w) def test_numpy_compat(self): @@ -509,28 +509,28 @@ def test_constructor(self): c(halflife=0.75, alpha=None) # not valid: mutually exclusive - with self.assertRaises(ValueError): + with pytest.raises(ValueError): c(com=0.5, alpha=0.5) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): c(span=1.5, halflife=0.75) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): c(alpha=0.5, span=1.5) # not valid: com < 0 - with self.assertRaises(ValueError): + with pytest.raises(ValueError): c(com=-0.5) # not valid: span < 1 - with self.assertRaises(ValueError): + with pytest.raises(ValueError): c(span=0.5) # not valid: halflife <= 0 - with self.assertRaises(ValueError): + with pytest.raises(ValueError): c(halflife=0) # not valid: alpha <= 0 or alpha > 1 for alpha in (-0.5, 1.5): - with self.assertRaises(ValueError): + with pytest.raises(ValueError): c(alpha=alpha) def test_numpy_compat(self): @@ -784,7 +784,7 @@ def test_centered_axis_validation(self): Series(np.ones(10)).rolling(window=3, center=True, axis=0).mean() # bad axis - with self.assertRaises(ValueError): + with pytest.raises(ValueError): Series(np.ones(10)).rolling(window=3, center=True, axis=1).mean() # ok ok @@ -794,7 +794,7 @@ def test_centered_axis_validation(self): axis=1).mean() # bad axis - with self.assertRaises(ValueError): + with pytest.raises(ValueError): (DataFrame(np.ones((10, 10))) .rolling(window=3, center=True, axis=2).mean()) @@ -887,7 +887,7 @@ def test_cmov_window_frame(self): tm.assert_frame_equal(DataFrame(xp), rs) # invalid method - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): (DataFrame(vals).rolling(5, win_type='boxcar', center=True) .std()) @@ -1056,8 +1056,8 @@ def test_rolling_min(self): b = mom.rolling_min(a, window=100, min_periods=1) tm.assert_almost_equal(b, np.ones(len(a))) - self.assertRaises(ValueError, mom.rolling_min, np.array([1, 2, 3]), - window=3, min_periods=5) + pytest.raises(ValueError, mom.rolling_min, np.array([1, 2, 3]), + window=3, min_periods=5) def test_rolling_max(self): @@ -1069,8 +1069,8 @@ def test_rolling_max(self): b = mom.rolling_max(a, window=100, min_periods=1) tm.assert_almost_equal(a, b) - self.assertRaises(ValueError, mom.rolling_max, np.array([1, 2, 3]), - window=3, min_periods=5) + pytest.raises(ValueError, mom.rolling_max, np.array([1, 2, 3]), + window=3, min_periods=5) def test_rolling_quantile(self): qs = [0.0, .1, .5, .9, 1.0] @@ -1097,13 +1097,13 @@ def alt(x): def test_rolling_quantile_param(self): ser = Series([0.0, .1, .5, .9, 1.0]) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): ser.rolling(3).quantile(-0.1) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): ser.rolling(3).quantile(10.0) - with self.assertRaises(TypeError): + with pytest.raises(TypeError): ser.rolling(3).quantile('foo') def test_rolling_apply(self): @@ -1549,8 +1549,8 @@ def test_ewma_span_com_args(self): B = mom.ewma(self.arr, span=20) tm.assert_almost_equal(A, B) - self.assertRaises(ValueError, mom.ewma, self.arr, com=9.5, span=20) - self.assertRaises(ValueError, mom.ewma, self.arr) + pytest.raises(ValueError, mom.ewma, self.arr, com=9.5, span=20) + pytest.raises(ValueError, mom.ewma, self.arr) def test_ewma_halflife_arg(self): with catch_warnings(record=True): @@ -1558,13 +1558,13 @@ def test_ewma_halflife_arg(self): B = mom.ewma(self.arr, halflife=10.0) tm.assert_almost_equal(A, B) - self.assertRaises(ValueError, mom.ewma, self.arr, span=20, - halflife=50) - self.assertRaises(ValueError, mom.ewma, self.arr, com=9.5, - halflife=50) - self.assertRaises(ValueError, mom.ewma, self.arr, com=9.5, span=20, - halflife=50) - self.assertRaises(ValueError, mom.ewma, self.arr) + pytest.raises(ValueError, mom.ewma, self.arr, span=20, + halflife=50) + pytest.raises(ValueError, mom.ewma, self.arr, com=9.5, + halflife=50) + pytest.raises(ValueError, mom.ewma, self.arr, com=9.5, span=20, + halflife=50) + pytest.raises(ValueError, mom.ewma, self.arr) def test_ewma_alpha_old_api(self): # GH 10789 @@ -1580,13 +1580,13 @@ def test_ewma_alpha_old_api(self): def test_ewma_alpha_arg_old_api(self): # GH 10789 with catch_warnings(record=True): - self.assertRaises(ValueError, mom.ewma, self.arr) - self.assertRaises(ValueError, mom.ewma, self.arr, - com=10.0, alpha=0.5) - self.assertRaises(ValueError, mom.ewma, self.arr, - span=10.0, alpha=0.5) - self.assertRaises(ValueError, mom.ewma, self.arr, - halflife=10.0, alpha=0.5) + pytest.raises(ValueError, mom.ewma, self.arr) + pytest.raises(ValueError, mom.ewma, self.arr, + com=10.0, alpha=0.5) + pytest.raises(ValueError, mom.ewma, self.arr, + span=10.0, alpha=0.5) + pytest.raises(ValueError, mom.ewma, self.arr, + halflife=10.0, alpha=0.5) def test_ewm_alpha(self): # GH 10789 @@ -1602,34 +1602,34 @@ def test_ewm_alpha(self): def test_ewm_alpha_arg(self): # GH 10789 s = Series(self.arr) - self.assertRaises(ValueError, s.ewm) - self.assertRaises(ValueError, s.ewm, com=10.0, alpha=0.5) - self.assertRaises(ValueError, s.ewm, span=10.0, alpha=0.5) - self.assertRaises(ValueError, s.ewm, halflife=10.0, alpha=0.5) + pytest.raises(ValueError, s.ewm) + pytest.raises(ValueError, s.ewm, com=10.0, alpha=0.5) + pytest.raises(ValueError, s.ewm, span=10.0, alpha=0.5) + pytest.raises(ValueError, s.ewm, halflife=10.0, alpha=0.5) def test_ewm_domain_checks(self): # GH 12492 s = Series(self.arr) # com must satisfy: com >= 0 - self.assertRaises(ValueError, s.ewm, com=-0.1) + pytest.raises(ValueError, s.ewm, com=-0.1) s.ewm(com=0.0) s.ewm(com=0.1) # span must satisfy: span >= 1 - self.assertRaises(ValueError, s.ewm, span=-0.1) - self.assertRaises(ValueError, s.ewm, span=0.0) - self.assertRaises(ValueError, s.ewm, span=0.9) + pytest.raises(ValueError, s.ewm, span=-0.1) + pytest.raises(ValueError, s.ewm, span=0.0) + pytest.raises(ValueError, s.ewm, span=0.9) s.ewm(span=1.0) s.ewm(span=1.1) # halflife must satisfy: halflife > 0 - self.assertRaises(ValueError, s.ewm, halflife=-0.1) - self.assertRaises(ValueError, s.ewm, halflife=0.0) + pytest.raises(ValueError, s.ewm, halflife=-0.1) + pytest.raises(ValueError, s.ewm, halflife=0.0) s.ewm(halflife=0.1) # alpha must satisfy: 0 < alpha <= 1 - self.assertRaises(ValueError, s.ewm, alpha=-0.1) - self.assertRaises(ValueError, s.ewm, alpha=0.0) + pytest.raises(ValueError, s.ewm, alpha=-0.1) + pytest.raises(ValueError, s.ewm, alpha=0.0) s.ewm(alpha=0.1) s.ewm(alpha=1.0) - self.assertRaises(ValueError, s.ewm, alpha=1.1) + pytest.raises(ValueError, s.ewm, alpha=1.1) def test_ew_empty_arrays(self): arr = np.array([], dtype=np.float64) @@ -2396,7 +2396,7 @@ def get_result(obj, obj2=None): def test_flex_binary_moment(self): # GH3155 # don't blow the stack - self.assertRaises(TypeError, rwindow._flex_binary_moment, 5, 6, None) + pytest.raises(TypeError, rwindow._flex_binary_moment, 5, 6, None) def test_corr_sanity(self): # GH 3155 @@ -2485,7 +2485,7 @@ def func(A, B, com, **kwargs): Series([1.]), Series([1.]), 50, min_periods=min_periods) tm.assert_series_equal(result, Series([np.NaN])) - self.assertRaises(Exception, func, A, randn(50), 20, min_periods=5) + pytest.raises(Exception, func, A, randn(50), 20, min_periods=5) def test_expanding_apply(self): ser = Series([]) @@ -3047,7 +3047,7 @@ def test_mutated(self): def f(): self.frame.groupby('A', foo=1) - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) g = self.frame.groupby('A') self.assertFalse(g.mutated) @@ -3216,16 +3216,16 @@ def test_valid(self): df = self.regular # not a valid freq - with self.assertRaises(ValueError): + with pytest.raises(ValueError): df.rolling(window='foobar') # not a datetimelike index - with self.assertRaises(ValueError): + with pytest.raises(ValueError): df.reset_index().rolling(window='foobar') # non-fixed freqs for freq in ['2MS', pd.offsets.MonthBegin(2)]: - with self.assertRaises(ValueError): + with pytest.raises(ValueError): df.rolling(window=freq) for freq in ['1D', pd.offsets.Day(2), '2ms']: @@ -3233,11 +3233,11 @@ def test_valid(self): # non-integer min_periods for minp in [1.0, 'foo', np.array([1, 2, 3])]: - with self.assertRaises(ValueError): + with pytest.raises(ValueError): df.rolling(window='1D', min_periods=minp) # center is not implemented - with self.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): df.rolling(window='1D', center=True) def test_on(self): @@ -3245,7 +3245,7 @@ def test_on(self): df = self.regular # not a valid column - with self.assertRaises(ValueError): + with pytest.raises(ValueError): df.rolling(window='2s', on='foobar') # column is valid @@ -3254,7 +3254,7 @@ def test_on(self): df.rolling(window='2d', on='C').sum() # invalid columns - with self.assertRaises(ValueError): + with pytest.raises(ValueError): df.rolling(window='2d', on='B') # ok even though on non-selected @@ -3279,11 +3279,11 @@ def test_monotonic_on(self): df.index = reversed(df.index.tolist()) self.assertFalse(df.index.is_monotonic) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): df.rolling('2s').sum() df = df.reset_index() - with self.assertRaises(ValueError): + with pytest.raises(ValueError): df.rolling('2s', on='A').sum() def test_frame_on(self): diff --git a/pandas/tests/tools/test_numeric.py b/pandas/tests/tools/test_numeric.py index 96b49c5fb97a6..5fa3f38f31ae1 100644 --- a/pandas/tests/tools/test_numeric.py +++ b/pandas/tests/tools/test_numeric.py @@ -162,7 +162,7 @@ def test_scalar(self): self.assertEqual(pd.to_numeric('1'), 1) self.assertEqual(pd.to_numeric('1.1'), 1.1) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): to_numeric('XX', errors='raise') self.assertEqual(to_numeric('XX', errors='ignore'), 'XX') diff --git a/pandas/tests/tseries/test_frequencies.py b/pandas/tests/tseries/test_frequencies.py index 327dad6d47634..e3ab01499e676 100644 --- a/pandas/tests/tseries/test_frequencies.py +++ b/pandas/tests/tseries/test_frequencies.py @@ -1,6 +1,7 @@ from datetime import datetime, timedelta from pandas.compat import range +import pytest import numpy as np from pandas import (Index, DatetimeIndex, Timestamp, Series, @@ -198,7 +199,7 @@ def test_to_offset_pd_timedelta(self): assert (expected == result) td = Timedelta(microseconds=0) - tm.assertRaises(ValueError, lambda: frequencies.to_offset(td)) + pytest.raises(ValueError, lambda: frequencies.to_offset(td)) def test_anchored_shortcuts(self): result = frequencies.to_offset('W') @@ -427,11 +428,11 @@ def test_resolution_bumping(self): self.assertEqual(Reso.get_stride_from_decimal(1.2345, 'D'), (106660800, 'L')) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): Reso.get_stride_from_decimal(0.5, 'N') # too much precision in the input can prevent - with self.assertRaises(ValueError): + with pytest.raises(ValueError): Reso.get_stride_from_decimal(0.3429324798798269273987982, 'H') def test_get_freq_code(self): @@ -492,11 +493,11 @@ class TestFrequencyInference(tm.TestCase): def test_raise_if_period_index(self): index = PeriodIndex(start="1/1/1990", periods=20, freq="M") - self.assertRaises(TypeError, frequencies.infer_freq, index) + pytest.raises(TypeError, frequencies.infer_freq, index) def test_raise_if_too_few(self): index = _dti(['12/31/1998', '1/3/1999']) - self.assertRaises(ValueError, frequencies.infer_freq, index) + pytest.raises(ValueError, frequencies.infer_freq, index) def test_business_daily(self): index = _dti(['12/31/1998', '1/3/1999', '1/4/1999']) @@ -567,7 +568,7 @@ def test_week_of_month(self): def test_fifth_week_of_month(self): # Only supports freq up to WOM-4. See #9425 func = lambda: date_range('2014-01-01', freq='WOM-5MON') - self.assertRaises(ValueError, func) + pytest.raises(ValueError, func) def test_fifth_week_of_month_infer(self): # Only attempts to infer up to WOM-4. See #9425 @@ -742,14 +743,13 @@ def test_invalid_index_types(self): # test all index types for i in [tm.makeIntIndex(10), tm.makeFloatIndex(10), tm.makePeriodIndex(10)]: - self.assertRaises(TypeError, lambda: frequencies.infer_freq(i)) + pytest.raises(TypeError, lambda: frequencies.infer_freq(i)) # GH 10822 # odd error message on conversions to datetime for unicode if not is_platform_windows(): for i in [tm.makeStringIndex(10), tm.makeUnicodeIndex(10)]: - self.assertRaises(ValueError, - lambda: frequencies.infer_freq(i)) + pytest.raises(ValueError, lambda: frequencies.infer_freq(i)) def test_string_datetimelike_compat(self): @@ -767,33 +767,32 @@ def test_series(self): # invalid type of Series for s in [Series(np.arange(10)), Series(np.arange(10.))]: - self.assertRaises(TypeError, lambda: frequencies.infer_freq(s)) + pytest.raises(TypeError, lambda: frequencies.infer_freq(s)) # a non-convertible string - self.assertRaises(ValueError, - lambda: frequencies.infer_freq( - Series(['foo', 'bar']))) + pytest.raises(ValueError, lambda: frequencies.infer_freq( + Series(['foo', 'bar']))) # cannot infer on PeriodIndex for freq in [None, 'L']: s = Series(period_range('2013', periods=10, freq=freq)) - self.assertRaises(TypeError, lambda: frequencies.infer_freq(s)) + pytest.raises(TypeError, lambda: frequencies.infer_freq(s)) for freq in ['Y']: msg = frequencies._INVALID_FREQ_ERROR with tm.assertRaisesRegexp(ValueError, msg): s = Series(period_range('2013', periods=10, freq=freq)) - self.assertRaises(TypeError, lambda: frequencies.infer_freq(s)) + pytest.raises(TypeError, lambda: frequencies.infer_freq(s)) # DateTimeIndex for freq in ['M', 'L', 'S']: s = Series(date_range('20130101', periods=10, freq=freq)) inferred = frequencies.infer_freq(s) - self.assertEqual(inferred, freq) + assert inferred == freq s = Series(date_range('20130101', '20130110')) inferred = frequencies.infer_freq(s) - self.assertEqual(inferred, 'D') + assert inferred == 'D' def test_legacy_offset_warnings(self): freqs = ['WEEKDAY', 'EOM', 'W@MON', 'W@TUE', 'W@WED', 'W@THU', diff --git a/pandas/tests/tseries/test_holiday.py b/pandas/tests/tseries/test_holiday.py index 25ae367617874..c87f580582335 100644 --- a/pandas/tests/tseries/test_holiday.py +++ b/pandas/tests/tseries/test_holiday.py @@ -1,3 +1,5 @@ +import pytest + from datetime import datetime import pandas.util.testing as tm from pandas import compat @@ -384,7 +386,7 @@ class TestHolidayConflictingArguments(tm.TestCase): # GH 10217 def test_both_offset_observance_raises(self): - with self.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): Holiday("Cyber Monday", month=11, day=1, offset=[DateOffset(weekday=SA(4))], observance=next_monday) diff --git a/pandas/tests/tseries/test_offsets.py b/pandas/tests/tseries/test_offsets.py index 64f978124f8e7..335a7f3513da9 100644 --- a/pandas/tests/tseries/test_offsets.py +++ b/pandas/tests/tseries/test_offsets.py @@ -590,7 +590,7 @@ def testRAdd(self): def testSub(self): off = self.offset2 - self.assertRaises(Exception, off.__sub__, self.d) + pytest.raises(Exception, off.__sub__, self.d) self.assertEqual(2 * off - off, off) self.assertEqual(self.d - self.offset2, self.d + BDay(-2)) @@ -713,7 +713,7 @@ def test_apply_large_n(self): self.assertEqual(rs, xp) def test_apply_corner(self): - self.assertRaises(TypeError, BDay().apply, BMonthEnd()) + pytest.raises(TypeError, BDay().apply, BMonthEnd()) def test_offsets_compare_equal(self): # root cause of #456 @@ -742,11 +742,11 @@ def setUp(self): def test_constructor_errors(self): from datetime import time as dt_time - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): BusinessHour(start=dt_time(11, 0, 5)) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): BusinessHour(start='AAA') - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): BusinessHour(start='14:00:05') def test_different_normalize_equals(self): @@ -802,7 +802,7 @@ def testRAdd(self): def testSub(self): off = self.offset2 - self.assertRaises(Exception, off.__sub__, self.d) + pytest.raises(Exception, off.__sub__, self.d) self.assertEqual(2 * off - off, off) self.assertEqual(self.d - self.offset2, self.d + self._offset(-3)) @@ -1446,11 +1446,11 @@ def setUp(self): def test_constructor_errors(self): from datetime import time as dt_time - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): CustomBusinessHour(start=dt_time(11, 0, 5)) - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): CustomBusinessHour(start='AAA') - with tm.assertRaises(ValueError): + with pytest.raises(ValueError): CustomBusinessHour(start='14:00:05') def test_different_normalize_equals(self): @@ -1502,7 +1502,7 @@ def testRAdd(self): def testSub(self): off = self.offset2 - self.assertRaises(Exception, off.__sub__, self.d) + pytest.raises(Exception, off.__sub__, self.d) self.assertEqual(2 * off - off, off) self.assertEqual(self.d - self.offset2, self.d - (2 * off - off)) @@ -1735,7 +1735,7 @@ def testRAdd(self): def testSub(self): off = self.offset2 - self.assertRaises(Exception, off.__sub__, self.d) + pytest.raises(Exception, off.__sub__, self.d) self.assertEqual(2 * off - off, off) self.assertEqual(self.d - self.offset2, self.d + CDay(-2)) @@ -1854,7 +1854,7 @@ def test_apply_large_n(self): self.assertEqual(rs, xp) def test_apply_corner(self): - self.assertRaises(Exception, CDay().apply, BMonthEnd()) + pytest.raises(Exception, CDay().apply, BMonthEnd()) def test_offsets_compare_equal(self): # root cause of #456 @@ -1947,7 +1947,7 @@ def testRAdd(self): def testSub(self): off = self.offset2 - self.assertRaises(Exception, off.__sub__, self.d) + pytest.raises(Exception, off.__sub__, self.d) self.assertEqual(2 * off - off, off) self.assertEqual(self.d - self.offset2, self.d + self._object(-2)) @@ -2225,7 +2225,7 @@ def test_repr(self): "<-2 * Weeks: weekday=0>") def test_corner(self): - self.assertRaises(ValueError, Week, weekday=7) + pytest.raises(ValueError, Week, weekday=7) assertRaisesRegexp(ValueError, "Day must be", Week, weekday=-1) def test_isAnchored(self): @@ -4031,8 +4031,8 @@ class TestBYearBegin(Base): _offset = BYearBegin def test_misspecified(self): - self.assertRaises(ValueError, BYearBegin, month=13) - self.assertRaises(ValueError, BYearEnd, month=13) + pytest.raises(ValueError, BYearBegin, month=13) + pytest.raises(ValueError, BYearEnd, month=13) def test_offset(self): tests = [] @@ -4077,7 +4077,7 @@ class TestYearBegin(Base): _offset = YearBegin def test_misspecified(self): - self.assertRaises(ValueError, YearBegin, month=13) + pytest.raises(ValueError, YearBegin, month=13) def test_offset(self): tests = [] @@ -4169,8 +4169,8 @@ def test_onOffset(self): class TestBYearEndLagged(Base): def test_bad_month_fail(self): - self.assertRaises(Exception, BYearEnd, month=13) - self.assertRaises(Exception, BYearEnd, month=0) + pytest.raises(Exception, BYearEnd, month=13) + pytest.raises(Exception, BYearEnd, month=0) def test_offset(self): tests = [] @@ -4258,7 +4258,7 @@ class TestYearEnd(Base): _offset = YearEnd def test_misspecified(self): - self.assertRaises(ValueError, YearEnd, month=13) + pytest.raises(ValueError, YearEnd, month=13) def test_offset(self): tests = [] @@ -4622,9 +4622,9 @@ def test_parse_time_quarter_w_dash(self): self.assertEqual(parsed_dash, parsed) self.assertEqual(reso_dash, reso) - self.assertRaises(DateParseError, parse_time_string, "-2Q1992") - self.assertRaises(DateParseError, parse_time_string, "2-Q1992") - self.assertRaises(DateParseError, parse_time_string, "4-4Q1992") + pytest.raises(DateParseError, parse_time_string, "-2Q1992") + pytest.raises(DateParseError, parse_time_string, "2-Q1992") + pytest.raises(DateParseError, parse_time_string, "4-4Q1992") def test_get_standard_freq(): diff --git a/pandas/tests/tseries/test_timezones.py b/pandas/tests/tseries/test_timezones.py index f99ef2898d0f9..c9ac4f36e7769 100644 --- a/pandas/tests/tseries/test_timezones.py +++ b/pandas/tests/tseries/test_timezones.py @@ -105,8 +105,8 @@ def test_localize_utc_conversion(self): # DST ambiguity, this should fail rng = date_range('3/11/2012', '3/12/2012', freq='30T') # Is this really how it should fail?? - self.assertRaises(NonExistentTimeError, rng.tz_localize, - self.tzstr('US/Eastern')) + pytest.raises(NonExistentTimeError, rng.tz_localize, + self.tzstr('US/Eastern')) def test_localize_utc_conversion_explicit(self): # Localizing to time zone should: @@ -121,8 +121,8 @@ def test_localize_utc_conversion_explicit(self): # DST ambiguity, this should fail rng = date_range('3/11/2012', '3/12/2012', freq='30T') # Is this really how it should fail?? - self.assertRaises(NonExistentTimeError, rng.tz_localize, - self.tz('US/Eastern')) + pytest.raises(NonExistentTimeError, rng.tz_localize, + self.tz('US/Eastern')) def test_timestamp_tz_localize(self): stamp = Timestamp('3/11/2012 04:00') @@ -255,13 +255,13 @@ def test_tz_localize_dti(self): dti = DatetimeIndex(start='11/6/2011 1:59', end='11/6/2011 2:00', freq='L') - self.assertRaises(pytz.AmbiguousTimeError, dti.tz_localize, - self.tzstr('US/Eastern')) + pytest.raises(pytz.AmbiguousTimeError, dti.tz_localize, + self.tzstr('US/Eastern')) dti = DatetimeIndex(start='3/13/2011 1:59', end='3/13/2011 2:00', freq='L') - self.assertRaises(pytz.NonExistentTimeError, dti.tz_localize, - self.tzstr('US/Eastern')) + pytest.raises(pytz.NonExistentTimeError, dti.tz_localize, + self.tzstr('US/Eastern')) def test_tz_localize_empty_series(self): # #2248 @@ -436,9 +436,9 @@ def test_with_tz(self): dr = bdate_range(datetime(2005, 1, 1, tzinfo=pytz.utc), '1/1/2009', tz=pytz.utc) - self.assertRaises(Exception, bdate_range, - datetime(2005, 1, 1, tzinfo=pytz.utc), '1/1/2009', - tz=tz) + pytest.raises(Exception, bdate_range, + datetime(2005, 1, 1, tzinfo=pytz.utc), '1/1/2009', + tz=tz) def test_tz_localize(self): dr = bdate_range('1/1/2009', '1/1/2010') @@ -452,7 +452,7 @@ def test_with_tz_ambiguous_times(self): # March 13, 2011, spring forward, skip from 2 AM to 3 AM dr = date_range(datetime(2011, 3, 13, 1, 30), periods=3, freq=offsets.Hour()) - self.assertRaises(pytz.NonExistentTimeError, dr.tz_localize, tz) + pytest.raises(pytz.NonExistentTimeError, dr.tz_localize, tz) # after dst transition, it works dr = date_range(datetime(2011, 3, 13, 3, 30), periods=3, @@ -461,7 +461,7 @@ def test_with_tz_ambiguous_times(self): # November 6, 2011, fall back, repeat 2 AM hour dr = date_range(datetime(2011, 11, 6, 1, 30), periods=3, freq=offsets.Hour()) - self.assertRaises(pytz.AmbiguousTimeError, dr.tz_localize, tz) + pytest.raises(pytz.AmbiguousTimeError, dr.tz_localize, tz) # UTC is OK dr = date_range(datetime(2011, 3, 13), periods=48, @@ -473,7 +473,7 @@ def test_ambiguous_infer(self): tz = self.tz('US/Eastern') dr = date_range(datetime(2011, 11, 6, 0), periods=5, freq=offsets.Hour()) - self.assertRaises(pytz.AmbiguousTimeError, dr.tz_localize, tz) + pytest.raises(pytz.AmbiguousTimeError, dr.tz_localize, tz) # With repeated hours, we can infer the transition dr = date_range(datetime(2011, 11, 6, 0), periods=5, @@ -533,7 +533,7 @@ def test_ambiguous_flags(self): di = DatetimeIndex(times) # When the sizes are incompatible, make sure error is raised - self.assertRaises(Exception, di.tz_localize, tz, ambiguous=is_dst) + pytest.raises(Exception, di.tz_localize, tz, ambiguous=is_dst) # When sizes are compatible and there are repeats ('infer' won't work) is_dst = np.hstack((is_dst, is_dst)) @@ -556,7 +556,7 @@ def test_ambiguous_flags(self): def f(): date_range("2013-10-26 23:00", "2013-10-27 01:00", tz="Europe/London", freq="H") - self.assertRaises(pytz.AmbiguousTimeError, f) + pytest.raises(pytz.AmbiguousTimeError, f) times = date_range("2013-10-26 23:00", "2013-10-27 01:00", freq="H", tz=tz, ambiguous='infer') @@ -592,7 +592,7 @@ def test_ambiguous_bool(self): def f(): t.tz_localize('US/Central') - self.assertRaises(pytz.AmbiguousTimeError, f) + pytest.raises(pytz.AmbiguousTimeError, f) result = t.tz_localize('US/Central', ambiguous=True) self.assertEqual(result, expected0) @@ -606,7 +606,7 @@ def f(): def f(): s.dt.tz_localize('US/Central') - self.assertRaises(pytz.AmbiguousTimeError, f) + pytest.raises(pytz.AmbiguousTimeError, f) result = s.dt.tz_localize('US/Central', ambiguous=True) assert_series_equal(result, expected0) @@ -626,10 +626,10 @@ def test_nonexistent_raise_coerce(self): times = ['2015-03-08 01:00', '2015-03-08 02:00', '2015-03-08 03:00'] index = DatetimeIndex(times) tz = 'US/Eastern' - self.assertRaises(NonExistentTimeError, - index.tz_localize, tz=tz) - self.assertRaises(NonExistentTimeError, - index.tz_localize, tz=tz, errors='raise') + pytest.raises(NonExistentTimeError, + index.tz_localize, tz=tz) + pytest.raises(NonExistentTimeError, + index.tz_localize, tz=tz, errors='raise') result = index.tz_localize(tz=tz, errors='coerce') test_times = ['2015-03-08 01:00-05:00', 'NaT', '2015-03-08 03:00-04:00'] @@ -659,8 +659,8 @@ def test_infer_tz(self): assert (tools._infer_tzinfo(start, end) is utc) end = self.localize(eastern, _end) - self.assertRaises(Exception, tools._infer_tzinfo, start, end) - self.assertRaises(Exception, tools._infer_tzinfo, end, start) + pytest.raises(Exception, tools._infer_tzinfo, start, end) + pytest.raises(Exception, tools._infer_tzinfo, end, start) def test_tz_string(self): result = date_range('1/1/2000', periods=10, @@ -1232,11 +1232,11 @@ def test_replace(self): # error def f(): dt.replace(foo=5) - self.assertRaises(TypeError, f) + pytest.raises(TypeError, f) def f(): dt.replace(hour=0.1) - self.assertRaises(ValueError, f) + pytest.raises(ValueError, f) # assert conversion to naive is the same as replacing tzinfo with None dt = Timestamp('2013-11-03 01:59:59.999999-0400', tz='US/Eastern') @@ -1306,7 +1306,7 @@ def test_tz_localize_roundtrip(self): tz=tz) tm.assert_index_equal(localized, expected) - with tm.assertRaises(TypeError): + with pytest.raises(TypeError): localized.tz_localize(tz) reset = localized.tz_localize(None) @@ -1410,8 +1410,8 @@ def test_join_aware(self): ts_utc = ts.tz_localize('utc') - self.assertRaises(Exception, ts.__add__, ts_utc) - self.assertRaises(Exception, ts_utc.__add__, ts) + pytest.raises(Exception, ts.__add__, ts_utc) + pytest.raises(Exception, ts_utc.__add__, ts) test1 = DataFrame(np.zeros((6, 3)), index=date_range("2012-11-15 00:00:00", periods=6, diff --git a/pandas/util/testing.py b/pandas/util/testing.py index c54def2b4ef5e..b4bbfff9cb611 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -2446,57 +2446,23 @@ def stdin_encoding(encoding=None): sys.stdin = _stdin -def assertRaises(_exception, _callable=None, *args, **kwargs): - """assertRaises that is usable as context manager or in a with statement - - Exceptions that don't match the given Exception type fall through:: - - >>> with assertRaises(ValueError): - ... raise TypeError("banana") - ... - Traceback (most recent call last): - ... - TypeError: banana - - If it raises the given Exception type, the test passes - >>> with assertRaises(KeyError): - ... dct = dict() - ... dct["apple"] - - If the expected error doesn't occur, it raises an error. - >>> with assertRaises(KeyError): - ... dct = {'apple':True} - ... dct["apple"] - Traceback (most recent call last): - ... - AssertionError: KeyError not raised. - - In addition to using it as a contextmanager, you can also use it as a - function, just like the normal assertRaises - - >>> assertRaises(TypeError, ",".join, [1, 3, 5]) +def assertRaisesRegexp(_exception, _regexp, _callable=None, *args, **kwargs): """ - manager = _AssertRaisesContextmanager(exception=_exception) - # don't return anything if used in function form - if _callable is not None: - with manager: - _callable(*args, **kwargs) - else: - return manager - + Check that the specified Exception is raised and that the error message + matches a given regular expression pattern. This may be a regular + expression object or a string containing a regular expression suitable + for use by `re.search()`. -def assertRaisesRegexp(_exception, _regexp, _callable=None, *args, **kwargs): - """ Port of assertRaisesRegexp from unittest in - Python 2.7 - used in with statement. + This is a port of the `assertRaisesRegexp` function from unittest in + Python 2.7. However, with our migration to `pytest`, please refrain + from using this. Instead, use the following paradigm: - Explanation from standard library: - Like assertRaises() but also tests that regexp matches on the - string representation of the raised exception. regexp may be a - regular expression object or a string containing a regular - expression suitable for use by re.search(). + with pytest.raises(_exception) as exc_info: + func(*args, **kwargs) + exc_info.matches(reg_exp) - You can pass either a regular expression - or a compiled regular expression object. + Examples + -------- >>> assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ', ... int, 'XYZ') >>> import re