diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 9f3ded88b5e7d..8905560aa2108 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -120,6 +120,10 @@ if [[ -z "$CHECK" || "$CHECK" == "patterns" ]]; then invgrep -r -E --include '*.py' 'pytest\.warns' pandas/tests/ RET=$(($RET + $?)) ; echo $MSG "DONE" + MSG='Check for pytest raises without context' ; echo $MSG + invgrep -r -E --include '*.py' "[[:space:]] pytest.raises" pandas/tests/ + RET=$(($RET + $?)) ; echo $MSG "DONE" + # Check for the following code in testing: `np.testing` and `np.array_equal` MSG='Check for invalid testing' ; echo $MSG invgrep -r -E --include '*.py' --exclude testing.py '(numpy|np)(\.testing|\.array_equal)' pandas/tests/ diff --git a/pandas/tests/arrays/sparse/test_libsparse.py b/pandas/tests/arrays/sparse/test_libsparse.py index 2cbe7d9ea084c..c1c72f823c8b6 100644 --- a/pandas/tests/arrays/sparse/test_libsparse.py +++ b/pandas/tests/arrays/sparse/test_libsparse.py @@ -157,7 +157,7 @@ def _check_case(xloc, xlen, yloc, ylen, eloc, elen): elen = [3, 2, 3, 2] _check_case(xloc, xlen, yloc, ylen, eloc, elen) - def test_intindex_make_union(self): + def test_int_index_make_union(self): a = IntIndex(5, np.array([0, 3, 4], dtype=np.int32)) b = IntIndex(5, np.array([0, 2], dtype=np.int32)) res = a.make_union(b) @@ -184,7 +184,9 @@ 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 pytest.raises(ValueError): + + msg = "Indices must reference same underlying length" + with pytest.raises(ValueError, match=msg): a.make_union(b) @@ -197,7 +199,9 @@ def _check_correct(a, b, expected): assert (result.equals(expected)) def _check_length_exc(a, longer): - pytest.raises(Exception, a.intersect, longer) + msg = "Indices must reference same underlying length" + with pytest.raises(Exception, match=msg): + a.intersect(longer) def _check_case(xloc, xlen, yloc, ylen, eloc, elen): xindex = BlockIndex(TEST_LENGTH, xloc, xlen) diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index 62905ddd3d398..40a6305bbb42f 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -339,8 +339,8 @@ def check_pow(self, lhs, arith1, rhs): if (is_scalar(lhs) and is_scalar(rhs) and _is_py3_complex_incompat(result, expected)): - pytest.raises(AssertionError, tm.assert_numpy_array_equal, - result, expected) + with pytest.raises(AssertionError): + tm.assert_numpy_array_equal(result, expected) else: tm.assert_almost_equal(result, expected) diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py index c96e5232ecf41..d4baf9413772b 100644 --- a/pandas/tests/frame/test_nonunique_indexes.py +++ b/pandas/tests/frame/test_nonunique_indexes.py @@ -416,9 +416,12 @@ def test_columns_with_dups(self): [[1, 2, 1., 2., 3., 'foo', 'bar']], columns=list('ABCDEFG')) assert_frame_equal(df, expected) - # this is an error because we cannot disambiguate the dup columns - pytest.raises(Exception, lambda x: DataFrame( - [[1, 2, 'foo', 'bar']], columns=['a', 'a', 'a', 'a'])) + df = DataFrame([[1, 2, 'foo', 'bar']], columns=['a', 'a', 'a', 'a']) + df.columns = ['a', 'a.1', 'a.2', 'a.3'] + str(df) + expected = DataFrame([[1, 2, 'foo', 'bar']], + columns=['a', 'a.1', 'a.2', 'a.3']) + assert_frame_equal(df, expected) # dups across blocks df_float = DataFrame(np.random.randn(10, 3), dtype='float64') diff --git a/pandas/tests/indexes/interval/test_interval_new.py b/pandas/tests/indexes/interval/test_interval_new.py index fcffa29f7eadb..e65628e1dd975 100644 --- a/pandas/tests/indexes/interval/test_interval_new.py +++ b/pandas/tests/indexes/interval/test_interval_new.py @@ -49,7 +49,8 @@ def test_get_loc_scalar(self, closed, scalar): if scalar in correct[closed].keys(): assert idx.get_loc(scalar) == correct[closed][scalar] else: - pytest.raises(KeyError, idx.get_loc, scalar) + with pytest.raises(KeyError, match=str(scalar)): + idx.get_loc(scalar) def test_slice_locs_with_interval(self): @@ -89,13 +90,19 @@ def test_slice_locs_with_interval(self): # unsorted duplicates index = IntervalIndex.from_tuples([(0, 2), (2, 4), (0, 2)]) - pytest.raises(KeyError, index.slice_locs( - start=Interval(0, 2), end=Interval(2, 4))) - pytest.raises(KeyError, index.slice_locs(start=Interval(0, 2))) + with pytest.raises(KeyError): + index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) + + with pytest.raises(KeyError): + index.slice_locs(start=Interval(0, 2)) + assert index.slice_locs(end=Interval(2, 4)) == (0, 2) - pytest.raises(KeyError, index.slice_locs(end=Interval(0, 2))) - pytest.raises(KeyError, index.slice_locs( - start=Interval(2, 4), end=Interval(0, 2))) + + with pytest.raises(KeyError): + index.slice_locs(end=Interval(0, 2)) + + with pytest.raises(KeyError): + index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) # another unsorted duplicates index = IntervalIndex.from_tuples([(0, 2), (0, 2), (2, 4), (1, 3)]) diff --git a/pandas/tests/indexing/multiindex/test_partial.py b/pandas/tests/indexing/multiindex/test_partial.py index 473463def2b87..a295abf0ec2a9 100644 --- a/pandas/tests/indexing/multiindex/test_partial.py +++ b/pandas/tests/indexing/multiindex/test_partial.py @@ -147,8 +147,10 @@ def test_partial_ix_missing( # assert (self.ymd.loc[2000]['A'] == 0).all() # Pretty sure the second (and maybe even the first) is already wrong. - pytest.raises(Exception, ymd.loc.__getitem__, (2000, 6)) - pytest.raises(Exception, ymd.loc.__getitem__, (2000, 6), 0) + with pytest.raises(Exception): + ymd.loc[(2000, 6)] + with pytest.raises(Exception): + ymd.loc[(2000, 6), 0] # --------------------------------------------------------------------- diff --git a/pandas/tests/indexing/test_floats.py b/pandas/tests/indexing/test_floats.py index e29ac8a3b197e..f59151d3eb360 100644 --- a/pandas/tests/indexing/test_floats.py +++ b/pandas/tests/indexing/test_floats.py @@ -137,9 +137,9 @@ def test_scalar_non_numeric(self): # for idxr in [lambda x: x.ix, # lambda x: x]: # s2 = s.copy() - # def f(): + # + # with pytest.raises(TypeError): # idxr(s2)[3.0] = 0 - # pytest.raises(TypeError, f) pass else: diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index 42641d2c35c39..b0bceaba3829c 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -156,7 +156,8 @@ class TestHDFStore(Base): def test_format_kwarg_in_constructor(self): # GH 13291 with ensure_clean_path(self.path) as path: - pytest.raises(ValueError, HDFStore, path, format='table') + with pytest.raises(ValueError): + HDFStore(path, format="table") def test_context(self): path = create_tempfile(self.path) @@ -286,22 +287,25 @@ def test_api(self): assert_frame_equal(store.select('df'), df) with ensure_clean_path(self.path) as path: - - # invalid + # Invalid. df = tm.makeDataFrame() - pytest.raises(ValueError, df.to_hdf, path, - 'df', append=True, format='f') - pytest.raises(ValueError, df.to_hdf, path, - 'df', append=True, format='fixed') - pytest.raises(TypeError, df.to_hdf, path, - 'df', append=True, format='foo') - pytest.raises(TypeError, df.to_hdf, path, - 'df', append=False, format='bar') + with pytest.raises(ValueError): + df.to_hdf(path, "df", append=True, format="f") + + with pytest.raises(ValueError): + df.to_hdf(path, "df", append=True, format="fixed") + + with pytest.raises(TypeError): + df.to_hdf(path, "df", append=True, format="foo") + + with pytest.raises(TypeError): + df.to_hdf(path, "df", append=False, format="bar") # File path doesn't exist path = "" - pytest.raises(FileNotFoundError, read_hdf, path, 'df') + with pytest.raises(FileNotFoundError): + read_hdf(path, "df") def test_api_default_format(self): @@ -313,7 +317,8 @@ def test_api_default_format(self): _maybe_remove(store, 'df') store.put('df', df) assert not store.get_storer('df').is_table - pytest.raises(ValueError, store.append, 'df2', df) + with pytest.raises(ValueError): + store.append("df2", df) pd.set_option('io.hdf.default_format', 'table') _maybe_remove(store, 'df') @@ -333,7 +338,8 @@ def test_api_default_format(self): df.to_hdf(path, 'df') with HDFStore(path) as store: assert not store.get_storer('df').is_table - pytest.raises(ValueError, df.to_hdf, path, 'df2', append=True) + with pytest.raises(ValueError): + df.to_hdf(path, "df2", append=True) pd.set_option('io.hdf.default_format', 'table') df.to_hdf(path, 'df3') @@ -465,7 +471,8 @@ 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 - pytest.raises(Exception, store.select, 'df2') + with pytest.raises(Exception): + store.select("df2") def test_mode(self): @@ -477,7 +484,8 @@ def check(mode): # constructor if mode in ['r', 'r+']: - pytest.raises(IOError, HDFStore, path, mode=mode) + with pytest.raises(IOError): + HDFStore(path, mode=mode) else: store = HDFStore(path, mode=mode) @@ -488,10 +496,9 @@ def check(mode): # context if mode in ['r', 'r+']: - def f(): + with pytest.raises(IOError): with HDFStore(path, mode=mode) as store: # noqa pass - pytest.raises(IOError, f) else: with HDFStore(path, mode=mode) as store: assert store._handle.mode == mode @@ -500,16 +507,16 @@ def f(): # conv write if mode in ['r', 'r+']: - pytest.raises(IOError, df.to_hdf, - path, 'df', mode=mode) + with 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']: - pytest.raises(ValueError, read_hdf, - path, 'df', mode=mode) + with pytest.raises(ValueError): + read_hdf(path, "df", mode=mode) else: result = read_hdf(path, 'df', mode=mode) assert_frame_equal(result, df) @@ -536,7 +543,9 @@ def test_reopen_handle(self): store['a'] = tm.makeTimeSeries() # invalid mode change - pytest.raises(PossibleDataLossError, store.open, 'w') + with pytest.raises(PossibleDataLossError): + store.open("w") + store.close() assert not store.is_open @@ -613,7 +622,8 @@ def test_get(self): right = store['/a'] tm.assert_series_equal(left, right) - pytest.raises(KeyError, store.get, 'b') + with pytest.raises(KeyError): + store.get("b") @pytest.mark.parametrize('where, expected', [ ('/', { @@ -685,10 +695,9 @@ def test_getattr(self): tm.assert_frame_equal(result, df) # errors - pytest.raises(AttributeError, getattr, store, 'd') - - for x in ['mode', 'path', 'handle', 'complib']: - pytest.raises(AttributeError, getattr, store, x) + for x in ["d", "mode", "path", "handle", "complib"]: + with pytest.raises(AttributeError): + getattr(store, x) # not stores for x in ['mode', 'path', 'handle', 'complib']: @@ -708,17 +717,18 @@ def test_put(self): store.put('c', df[:10], format='table') # not OK, not a table - pytest.raises( - ValueError, store.put, 'b', df[10:], append=True) + with 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') - # pytest.raises(ValueError, store.put, 'f', df[10:], - # append=True) + _maybe_remove(store, 'f') + with pytest.raises(ValueError): + store.put("f", df[10:], append=True) # can't put to a table (use append instead) - pytest.raises(ValueError, store.put, 'c', df[10:], append=True) + with pytest.raises(ValueError): + store.put("c", df[10:], append=True) # overwrite table store.put('c', df[:10], format='table', append=False) @@ -760,8 +770,8 @@ def test_put_compression(self): tm.assert_frame_equal(store['c'], df) # can't compress if format='fixed' - pytest.raises(ValueError, store.put, 'b', df, - format='fixed', complib='zlib') + with pytest.raises(ValueError): + store.put("b", df, format="fixed", complib="zlib") @td.skip_if_windows_python_3 def test_put_compression_blosc(self): @@ -770,8 +780,8 @@ def test_put_compression_blosc(self): with ensure_clean_store(self.path) as store: # can't compress if format='fixed' - pytest.raises(ValueError, store.put, 'b', df, - format='fixed', complib='blosc') + with 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) @@ -1285,11 +1295,13 @@ def test_append_with_different_block_ordering(self): # store additional fields in different blocks df['int16_2'] = Series([1] * len(df), dtype='int16') - pytest.raises(ValueError, store.append, 'df', df) + with pytest.raises(ValueError): + store.append('df', df) # store multile additional fields in different blocks df['float_3'] = Series([1.] * len(df), dtype='float64') - pytest.raises(ValueError, store.append, 'df', df) + with pytest.raises(ValueError): + store.append('df', df) def test_append_with_strings(self): @@ -1323,7 +1335,8 @@ def check_col(key, name, size): store.append('df_new', df) df_new = DataFrame( [[124, 'abcdefqhij'], [346, 'abcdefghijklmnopqrtsuvwxyz']]) - pytest.raises(ValueError, store.append, 'df_new', df_new) + with pytest.raises(ValueError): + store.append('df_new', df_new) # min_itemsize on Series index (GH 11412) df = tm.makeMixedDataFrame().set_index('C') @@ -1402,8 +1415,8 @@ def check_col(key, name, size): df = DataFrame(['foo', 'foo', 'foo', 'barh', 'barh', 'barh'], columns=['A']) _maybe_remove(store, 'df') - pytest.raises(ValueError, store.append, 'df', - df, min_itemsize={'foo': 20, 'foobar': 20}) + with pytest.raises(ValueError): + store.append('df', df, min_itemsize={'foo': 20, 'foobar': 20}) def test_append_with_empty_string(self): @@ -1629,7 +1642,8 @@ def col(t, column): # try to index a non-table _maybe_remove(store, 'f2') store.put('f2', df) - pytest.raises(TypeError, store.create_table_index, 'f2') + with pytest.raises(TypeError): + store.create_table_index('f2') def test_append_hierarchical(self): index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'], @@ -1680,10 +1694,10 @@ def test_column_multiindex(self): check_index_type=True, check_column_type=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) + with pytest.raises(ValueError): + store.put('df2', df, format='table', data_columns=['A']) + with 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: @@ -1746,13 +1760,15 @@ def make_index(names=None): _maybe_remove(store, 'df') df = DataFrame(np.zeros((12, 2)), columns=[ 'a', 'b'], index=make_index(['date', 'a', 't'])) - pytest.raises(ValueError, store.append, 'df', df) + with 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'])) - pytest.raises(ValueError, store.append, 'df', df) + with pytest.raises(ValueError): + store.append('df', df) # fully names _maybe_remove(store, 'df') @@ -1811,9 +1827,10 @@ def test_pass_spec_to_storer(self): with ensure_clean_store(self.path) as store: store.put('df', df) - pytest.raises(TypeError, store.select, 'df', columns=['A']) - pytest.raises(TypeError, store.select, - 'df', where=[('columns=A')]) + with pytest.raises(TypeError): + store.select('df', columns=['A']) + with pytest.raises(TypeError): + store.select('df', where=[('columns=A')]) @xfail_non_writeable def test_append_misc(self): @@ -1851,7 +1868,8 @@ def check(obj, comparator): # 0 len df_empty = DataFrame(columns=list('ABC')) store.append('df', df_empty) - pytest.raises(KeyError, store.select, 'df') + with pytest.raises(KeyError): + store.select('df') # repeated append of 0/non-zero frames df = DataFrame(np.random.rand(10, 3), columns=list('ABC')) @@ -1875,12 +1893,14 @@ def test_append_raise(self): df = tm.makeDataFrame() df['invalid'] = [['a']] * len(df) assert df.dtypes['invalid'] == np.object_ - pytest.raises(TypeError, store.append, 'df', df) + with pytest.raises(TypeError): + store.append('df', df) # multiple invalid columns df['invalid2'] = [['a']] * len(df) df['invalid3'] = [['a']] * len(df) - pytest.raises(TypeError, store.append, 'df', df) + with pytest.raises(TypeError): + store.append('df', df) # datetime with embedded nans as object df = tm.makeDataFrame() @@ -1889,21 +1909,24 @@ def test_append_raise(self): s[0:5] = np.nan df['invalid'] = s assert df.dtypes['invalid'] == np.object_ - pytest.raises(TypeError, store.append, 'df', df) + with pytest.raises(TypeError): + store.append('df', df) # directly ndarray - pytest.raises(TypeError, store.append, 'df', np.arange(10)) + with pytest.raises(TypeError): + store.append('df', np.arange(10)) # series directly - pytest.raises(TypeError, store.append, - 'df', Series(np.arange(10))) + with pytest.raises(TypeError): + store.append('df', Series(np.arange(10))) # appending an incompatible table df = tm.makeDataFrame() store.append('df', df) df['foo'] = 'foo' - pytest.raises(ValueError, store.append, 'df', df) + with pytest.raises(ValueError): + store.append('df', df) def test_table_index_incompatible_dtypes(self): df1 = DataFrame({'a': [1, 2, 3]}) @@ -1912,8 +1935,8 @@ def test_table_index_incompatible_dtypes(self): with ensure_clean_store(self.path) as store: store.put('frame', df1, format='table') - pytest.raises(TypeError, store.put, 'frame', df2, - format='table', append=True) + with pytest.raises(TypeError): + store.put('frame', df2, format='table', append=True) def test_table_values_dtypes_roundtrip(self): @@ -1927,7 +1950,8 @@ def test_table_values_dtypes_roundtrip(self): assert_series_equal(df2.dtypes, store['df_i8'].dtypes) # incompatible dtype - pytest.raises(ValueError, store.append, 'df_i8', df1) + with pytest.raises(ValueError): + store.append('df_i8', df1) # check creation/storage/retrieval of float32 (a bit hacky to # actually create them thought) @@ -1989,8 +2013,8 @@ def test_unimplemented_dtypes_table_columns(self): for n, f in dtypes: df = tm.makeDataFrame() df[n] = f - pytest.raises( - TypeError, store.append, 'df1_%s' % n, df) + with pytest.raises(TypeError): + store.append('df1_%s' % n, df) # frame df = tm.makeDataFrame() @@ -2001,7 +2025,8 @@ 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...... - pytest.raises(TypeError, store.append, 'df_unimplemented', df) + with pytest.raises(TypeError): + store.append('df_unimplemented', df) @xfail_non_writeable @pytest.mark.skipif( @@ -2102,7 +2127,8 @@ def test_remove(self): assert len(store) == 0 # nonexistence - pytest.raises(KeyError, store.remove, 'a_nonexistent_store') + with pytest.raises(KeyError): + store.remove('a_nonexistent_store') # pathing store['a'] = ts @@ -2136,12 +2162,15 @@ def test_invalid_terms(self): store.put('df', df, format='table') # some invalid terms - pytest.raises(TypeError, Term) + with pytest.raises(TypeError): + Term() # more invalid - pytest.raises( - ValueError, store.select, 'df', 'df.index[3]') - pytest.raises(SyntaxError, store.select, 'df', 'index>') + with pytest.raises(ValueError): + store.select('df', 'df.index[3]') + + with pytest.raises(SyntaxError): + store.select('df', 'index>') # from the docs with ensure_clean_path(self.path) as path: @@ -2160,8 +2189,8 @@ def test_invalid_terms(self): 'ABCD'), index=date_range('20130101', periods=10)) dfq.to_hdf(path, 'dfq', format='table') - pytest.raises(ValueError, read_hdf, path, - 'dfq', where="A>0 or C>0") + with pytest.raises(ValueError): + read_hdf(path, 'dfq', where="A>0 or C>0") def test_same_name_scoping(self): @@ -2812,10 +2841,12 @@ def test_select_iterator(self): df = tm.makeTimeDataFrame(500) df.to_hdf(path, 'df_non_table') - pytest.raises(TypeError, read_hdf, path, - 'df_non_table', chunksize=100) - pytest.raises(TypeError, read_hdf, path, - 'df_non_table', iterator=True) + + with pytest.raises(TypeError): + read_hdf(path, 'df_non_table', chunksize=100) + + with pytest.raises(TypeError): + read_hdf(path, 'df_non_table', iterator=True) with ensure_clean_path(self.path) as path: @@ -3146,13 +3177,13 @@ def test_frame_select(self): # invalid terms df = tm.makeTimeDataFrame() store.append('df_time', df) - pytest.raises( - ValueError, store.select, 'df_time', "index>0") + with pytest.raises(ValueError): + store.select('df_time', "index>0") # can't select if not written as table # store['frame'] = df - # pytest.raises(ValueError, store.select, - # 'frame', [crit1, crit2]) + # with pytest.raises(ValueError): + # store.select('frame', [crit1, crit2]) def test_frame_select_complex(self): # select via complex criteria @@ -3190,8 +3221,8 @@ def test_frame_select_complex(self): tm.assert_frame_equal(result, expected) # invert not implemented in numexpr :( - pytest.raises(NotImplementedError, - store.select, 'df', '~(string="bar")') + with pytest.raises(NotImplementedError): + store.select('df', '~(string="bar")') # invert ok for filters result = store.select('df', "~(columns=['A','B'])") @@ -3279,12 +3310,12 @@ def test_invalid_filtering(self): store.put('df', df, format='table') # not implemented - pytest.raises(NotImplementedError, store.select, - 'df', "columns=['A'] | columns=['B']") + with pytest.raises(NotImplementedError): + store.select('df', "columns=['A'] | columns=['B']") # in theory we could deal with this - pytest.raises(NotImplementedError, store.select, - 'df', "columns=['A','B'] & columns=['C']") + with pytest.raises(NotImplementedError): + store.select('df', "columns=['A','B'] & columns=['C']") def test_string_select(self): # GH 2973 @@ -3349,11 +3380,11 @@ def test_read_column(self): store.append('df', df) # error - pytest.raises(KeyError, store.select_column, 'df', 'foo') + with pytest.raises(KeyError): + store.select_column('df', 'foo') - def f(): + with pytest.raises(Exception): store.select_column('df', 'index', where=['index>5']) - pytest.raises(Exception, f) # valid result = store.select_column('df', 'index') @@ -3361,8 +3392,8 @@ def f(): assert isinstance(result, Series) # not a data indexable column - pytest.raises( - ValueError, store.select_column, 'df', 'values_block_0') + with pytest.raises(ValueError): + store.select_column('df', 'values_block_0') # a data column df2 = df.copy() @@ -3471,14 +3502,17 @@ def test_coordinates(self): tm.assert_frame_equal(result, expected) # invalid - 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) + with pytest.raises(ValueError): + store.select('df', where=np.arange(len(df), dtype='float64')) + + with pytest.raises(ValueError): + store.select('df', where=np.arange(len(df) + 1)) + + with pytest.raises(ValueError): + store.select('df', where=np.arange(len(df)), start=5) + + with pytest.raises(ValueError): + store.select('df', where=np.arange(len(df)), start=5, stop=10) # selection with filter selection = date_range('20000101', periods=500) @@ -3514,13 +3548,16 @@ def test_append_to_multiple(self): with ensure_clean_store(self.path) as store: # exceptions - 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') + with pytest.raises(ValueError): + store.append_to_multiple( + {'df1': ['A', 'B'], 'df2': None}, df, selector='df3') + + with pytest.raises(ValueError): + store.append_to_multiple( + {'df1': None, 'df2': None}, df, selector='df3') + + with pytest.raises(ValueError): + store.append_to_multiple('df1', df, 'df1') # regular operation store.append_to_multiple( @@ -3579,25 +3616,33 @@ def test_select_as_multiple(self): with ensure_clean_store(self.path) as store: # no tables stored - pytest.raises(Exception, store.select_as_multiple, - None, where=['A>0', 'B>0'], selector='df1') + with 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 - 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') + with pytest.raises(Exception): + store.select_as_multiple(None, where=['A>0', 'B>0'], + selector='df1') + + with pytest.raises(Exception): + store.select_as_multiple([None], where=['A>0', 'B>0'], + selector='df1') + + with pytest.raises(KeyError): + store.select_as_multiple( + ['df1', 'df3'], where=['A>0', 'B>0'], selector='df1') + + with pytest.raises(KeyError): + store.select_as_multiple( + ['df3'], where=['A>0', 'B>0'], selector='df1') + + with 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']) @@ -3622,11 +3667,11 @@ def test_select_as_multiple(self): expected = expected[5:] tm.assert_frame_equal(result, expected) - # test excpection for diff rows + # test exception for diff rows store.append('df3', tm.makeTimeDataFrame(nper=50)) - pytest.raises(ValueError, store.select_as_multiple, - ['df1', 'df3'], where=['A>0', 'B>0'], - selector='df1') + with pytest.raises(ValueError): + store.select_as_multiple( + ['df1', 'df3'], where=['A>0', 'B>0'], selector='df1') @pytest.mark.skipif( LooseVersion(tables.__version__) < LooseVersion('3.1.0'), @@ -3863,11 +3908,10 @@ def test_multiple_open_close(self): # multiples store1 = HDFStore(path) - def f(): + with pytest.raises(ValueError): HDFStore(path) - pytest.raises(ValueError, f) - store1.close() + store1.close() else: # multiples @@ -3927,17 +3971,38 @@ def f(): store = HDFStore(path) store.close() - 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(AttributeError, 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') + with pytest.raises(ClosedFileError): + store.keys() + + with pytest.raises(ClosedFileError): + 'df' in store + + with pytest.raises(ClosedFileError): + len(store) + + with pytest.raises(ClosedFileError): + store['df'] + + with pytest.raises(AttributeError): + store.df + + with pytest.raises(ClosedFileError): + store.select('df') + + with pytest.raises(ClosedFileError): + store.get('df') + + with pytest.raises(ClosedFileError): + store.append('df2', df) + + with pytest.raises(ClosedFileError): + store.put('df3', df) + + with pytest.raises(ClosedFileError): + store.get_storer('df2') + + with pytest.raises(ClosedFileError): + store.remove('df2') with pytest.raises(ClosedFileError, match='file is not open'): store.select('df') @@ -4133,12 +4198,13 @@ def test_store_datetime_mixed(self): self._check_roundtrip(df, tm.assert_frame_equal) # def test_cant_write_multiindex_table(self): - # # for now, #1848 - # df = DataFrame(np.random.randn(10, 4), - # index=[np.arange(5).repeat(2), - # np.tile(np.arange(2), 5)]) - - # pytest.raises(Exception, store.put, 'foo', df, format='table') + # # for now, #1848 + # df = DataFrame(np.random.randn(10, 4), + # index=[np.arange(5).repeat(2), + # np.tile(np.arange(2), 5)]) + # + # with 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)) @@ -4321,8 +4387,8 @@ def test_duplicate_column_name(self): df = DataFrame(columns=["a", "a"], data=[[0, 0]]) with ensure_clean_path(self.path) as path: - pytest.raises(ValueError, df.to_hdf, - path, 'df', format='fixed') + with pytest.raises(ValueError): + df.to_hdf(path, 'df', format='fixed') df.to_hdf(path, 'df', format='table') other = read_hdf(path, 'df') @@ -4448,14 +4514,19 @@ def test_read_hdf_errors(self): columns=list('ABCDE')) with ensure_clean_path(self.path) as path: - pytest.raises(IOError, read_hdf, path, 'key') + with pytest.raises(IOError): + read_hdf(path, 'key') + df.to_hdf(path, 'df') store = HDFStore(path, mode='r') store.close() - pytest.raises(IOError, read_hdf, store, 'df') + + with pytest.raises(IOError): + read_hdf(store, 'df') def test_read_hdf_generic_buffer_errors(self): - pytest.raises(NotImplementedError, read_hdf, BytesIO(b''), 'df') + with pytest.raises(NotImplementedError): + read_hdf(BytesIO(b''), 'df') def test_invalid_complib(self): df = DataFrame(np.random.rand(4, 5), @@ -4478,7 +4549,9 @@ def test_read_nokey(self): reread = read_hdf(path) assert_frame_equal(df, reread) df.to_hdf(path, 'df2', mode='a') - pytest.raises(ValueError, read_hdf, path) + + with pytest.raises(ValueError): + read_hdf(path) def test_read_nokey_table(self): # GH13231 @@ -4490,13 +4563,17 @@ def test_read_nokey_table(self): reread = read_hdf(path) assert_frame_equal(df, reread) df.to_hdf(path, 'df2', mode='a', format='table') - pytest.raises(ValueError, read_hdf, path) + + with 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() - pytest.raises(ValueError, read_hdf, path) + + with pytest.raises(ValueError): + read_hdf(path) @td.skip_if_no('pathlib') def test_read_from_pathlib_path(self): @@ -4755,15 +4832,16 @@ def test_complex_indexing_error(self): 'C': complex128}, index=list('abcd')) with ensure_clean_store(self.path) as store: - pytest.raises(TypeError, store.append, - 'df', df, data_columns=['C']) + with 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: - pytest.raises(TypeError, s.to_hdf, path, 'obj', format='t') + with 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) @@ -4837,7 +4915,8 @@ def test_append_with_timezones_dateutil(self): tz=gettz('US/Eastern')), B=Timestamp('20130102', tz=gettz('EET'))), index=range(5)) - pytest.raises(ValueError, store.append, 'df_tz', df) + with pytest.raises(ValueError): + store.append('df_tz', df) # this is ok _maybe_remove(store, 'df_tz') @@ -4851,7 +4930,8 @@ def test_append_with_timezones_dateutil(self): tz=gettz('US/Eastern')), B=Timestamp('20130102', tz=gettz('CET'))), index=range(5)) - pytest.raises(ValueError, store.append, 'df_tz', df) + with pytest.raises(ValueError): + store.append('df_tz', df) # as index with ensure_clean_store(self.path) as store: @@ -4904,7 +4984,8 @@ def test_append_with_timezones_pytz(self): df = DataFrame(dict(A=Timestamp('20130102', tz='US/Eastern'), B=Timestamp('20130102', tz='EET')), index=range(5)) - pytest.raises(ValueError, store.append, 'df_tz', df) + with pytest.raises(ValueError): + store.append('df_tz', df) # this is ok _maybe_remove(store, 'df_tz') @@ -4917,7 +4998,8 @@ def test_append_with_timezones_pytz(self): df = DataFrame(dict(A=Timestamp('20130102', tz='US/Eastern'), B=Timestamp('20130102', tz='CET')), index=range(5)) - pytest.raises(ValueError, store.append, 'df_tz', df) + with pytest.raises(ValueError): + store.append('df_tz', df) # as index with ensure_clean_store(self.path) as store: diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 2f9733a7ad7ec..9b846f1408175 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -26,7 +26,7 @@ from pandas.util.testing import assert_series_equal -class TestSeriesConstructors(): +class TestSeriesConstructors(object): def test_invalid_dtype(self): # GH15520 @@ -1118,7 +1118,8 @@ def test_constructor_dtype_timedelta64(self): # these are frequency conversion astypes # for t in ['s', 'D', 'us', 'ms']: - # pytest.raises(TypeError, td.astype, 'm8[%s]' % t) + # with pytest.raises(TypeError): + # td.astype('m8[%s]' % t) # valid astype td.astype('int64')