Skip to content

Commit 3bbcacf

Browse files
simonjayhawkinsjreback
authored andcommitted
STY: use pytest.raises context manager (frame) (#25516)
1 parent 1c9de69 commit 3bbcacf

19 files changed

+284
-126
lines changed

Diff for: pandas/tests/frame/test_alter_axes.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -633,7 +633,8 @@ def test_rename(self, float_frame):
633633
tm.assert_index_equal(renamed.index, Index(['BAR', 'FOO']))
634634

635635
# have to pass something
636-
pytest.raises(TypeError, float_frame.rename)
636+
with pytest.raises(TypeError, match="must pass an index to rename"):
637+
float_frame.rename()
637638

638639
# partial columns
639640
renamed = float_frame.rename(columns={'C': 'foo', 'D': 'bar'})

Diff for: pandas/tests/frame/test_analytics.py

+18-7
Original file line numberDiff line numberDiff line change
@@ -898,6 +898,7 @@ def test_var_std(self, datetime_frame):
898898
result = nanops.nanvar(arr, axis=0)
899899
assert not (result < 0).any()
900900

901+
@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
901902
@pytest.mark.parametrize(
902903
"meth", ['sem', 'var', 'std'])
903904
def test_numeric_only_flag(self, meth):
@@ -919,10 +920,12 @@ def test_numeric_only_flag(self, meth):
919920
tm.assert_series_equal(expected, result)
920921

921922
# df1 has all numbers, df2 has a letter inside
922-
pytest.raises(TypeError, lambda: getattr(df1, meth)(
923-
axis=1, numeric_only=False))
924-
pytest.raises(TypeError, lambda: getattr(df2, meth)(
925-
axis=1, numeric_only=False))
923+
msg = r"unsupported operand type\(s\) for -: 'float' and 'str'"
924+
with pytest.raises(TypeError, match=msg):
925+
getattr(df1, meth)(axis=1, numeric_only=False)
926+
msg = "could not convert string to float: 'a'"
927+
with pytest.raises(TypeError, match=msg):
928+
getattr(df2, meth)(axis=1, numeric_only=False)
926929

927930
def test_sem(self, datetime_frame):
928931
result = datetime_frame.sem(ddof=4)
@@ -1369,6 +1372,7 @@ def test_pct_change(self):
13691372
# ----------------------------------------------------------------------
13701373
# Index of max / min
13711374

1375+
@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
13721376
def test_idxmin(self, float_frame, int_frame):
13731377
frame = float_frame
13741378
frame.loc[5:10] = np.nan
@@ -1381,8 +1385,11 @@ def test_idxmin(self, float_frame, int_frame):
13811385
skipna=skipna)
13821386
tm.assert_series_equal(result, expected)
13831387

1384-
pytest.raises(ValueError, frame.idxmin, axis=2)
1388+
msg = "No axis named 2 for object type <class 'type'>"
1389+
with pytest.raises(ValueError, match=msg):
1390+
frame.idxmin(axis=2)
13851391

1392+
@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
13861393
def test_idxmax(self, float_frame, int_frame):
13871394
frame = float_frame
13881395
frame.loc[5:10] = np.nan
@@ -1395,7 +1402,9 @@ def test_idxmax(self, float_frame, int_frame):
13951402
skipna=skipna)
13961403
tm.assert_series_equal(result, expected)
13971404

1398-
pytest.raises(ValueError, frame.idxmax, axis=2)
1405+
msg = "No axis named 2 for object type <class 'type'>"
1406+
with pytest.raises(ValueError, match=msg):
1407+
frame.idxmax(axis=2)
13991408

14001409
# ----------------------------------------------------------------------
14011410
# Logical reductions
@@ -1881,7 +1890,9 @@ def test_round_issue(self):
18811890
tm.assert_index_equal(rounded.index, dfs.index)
18821891

18831892
decimals = pd.Series([1, 0, 2], index=['A', 'B', 'A'])
1884-
pytest.raises(ValueError, df.round, decimals)
1893+
msg = "Index of decimals must be unique"
1894+
with pytest.raises(ValueError, match=msg):
1895+
df.round(decimals)
18851896

18861897
def test_built_in_round(self):
18871898
if not compat.PY3:

Diff for: pandas/tests/frame/test_api.py

+14-5
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import numpy as np
1010
import pytest
1111

12-
from pandas.compat import long, lrange, range
12+
from pandas.compat import PY2, long, lrange, range
1313

1414
import pandas as pd
1515
from pandas import (
@@ -146,8 +146,12 @@ def test_not_hashable(self):
146146
empty_frame = DataFrame()
147147

148148
df = self.klass([1])
149-
pytest.raises(TypeError, hash, df)
150-
pytest.raises(TypeError, hash, empty_frame)
149+
msg = ("'(Sparse)?DataFrame' objects are mutable, thus they cannot be"
150+
" hashed")
151+
with pytest.raises(TypeError, match=msg):
152+
hash(df)
153+
with pytest.raises(TypeError, match=msg):
154+
hash(empty_frame)
151155

152156
def test_new_empty_index(self):
153157
df1 = self.klass(np.random.randn(0, 3))
@@ -171,7 +175,9 @@ def test_get_agg_axis(self, float_frame):
171175
idx = float_frame._get_agg_axis(1)
172176
assert idx is float_frame.index
173177

174-
pytest.raises(ValueError, float_frame._get_agg_axis, 2)
178+
msg = r"Axis must be 0 or 1 \(got 2\)"
179+
with pytest.raises(ValueError, match=msg):
180+
float_frame._get_agg_axis(2)
175181

176182
def test_nonzero(self, float_frame, float_string_frame):
177183
empty_frame = DataFrame()
@@ -354,12 +360,15 @@ def test_transpose(self, float_frame):
354360
for col, s in compat.iteritems(mixed_T):
355361
assert s.dtype == np.object_
356362

363+
@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
357364
def test_swapaxes(self):
358365
df = self.klass(np.random.randn(10, 5))
359366
self._assert_frame_equal(df.T, df.swapaxes(0, 1))
360367
self._assert_frame_equal(df.T, df.swapaxes(1, 0))
361368
self._assert_frame_equal(df, df.swapaxes(0, 0))
362-
pytest.raises(ValueError, df.swapaxes, 2, 5)
369+
msg = "No axis named 2 for object type <class 'type'>"
370+
with pytest.raises(ValueError, match=msg):
371+
df.swapaxes(2, 5)
363372

364373
def test_axis_aliases(self, float_frame):
365374
f = float_frame

Diff for: pandas/tests/frame/test_axis_select_reindex.py

+30-13
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import numpy as np
88
import pytest
99

10-
from pandas.compat import lrange, lzip, u
10+
from pandas.compat import PY2, lrange, lzip, u
1111
from pandas.errors import PerformanceWarning
1212

1313
import pandas as pd
@@ -38,8 +38,11 @@ def test_drop_names(self):
3838
assert obj.columns.name == 'second'
3939
assert list(df.columns) == ['d', 'e', 'f']
4040

41-
pytest.raises(KeyError, df.drop, ['g'])
42-
pytest.raises(KeyError, df.drop, ['g'], 1)
41+
msg = r"\['g'\] not found in axis"
42+
with pytest.raises(KeyError, match=msg):
43+
df.drop(['g'])
44+
with pytest.raises(KeyError, match=msg):
45+
df.drop(['g'], 1)
4346

4447
# errors = 'ignore'
4548
dropped = df.drop(['g'], errors='ignore')
@@ -84,10 +87,14 @@ def test_drop(self):
8487
assert_frame_equal(simple.drop(
8588
[0, 3], axis='index'), simple.loc[[1, 2], :])
8689

87-
pytest.raises(KeyError, simple.drop, 5)
88-
pytest.raises(KeyError, simple.drop, 'C', 1)
89-
pytest.raises(KeyError, simple.drop, [1, 5])
90-
pytest.raises(KeyError, simple.drop, ['A', 'C'], 1)
90+
with pytest.raises(KeyError, match=r"\[5\] not found in axis"):
91+
simple.drop(5)
92+
with pytest.raises(KeyError, match=r"\['C'\] not found in axis"):
93+
simple.drop('C', 1)
94+
with pytest.raises(KeyError, match=r"\[5\] not found in axis"):
95+
simple.drop([1, 5])
96+
with pytest.raises(KeyError, match=r"\['C'\] not found in axis"):
97+
simple.drop(['A', 'C'], 1)
9198

9299
# errors = 'ignore'
93100
assert_frame_equal(simple.drop(5, errors='ignore'), simple)
@@ -444,7 +451,9 @@ def test_reindex_dups(self):
444451
assert_frame_equal(result, expected)
445452

446453
# reindex fails
447-
pytest.raises(ValueError, df.reindex, index=list(range(len(df))))
454+
msg = "cannot reindex from a duplicate axis"
455+
with pytest.raises(ValueError, match=msg):
456+
df.reindex(index=list(range(len(df))))
448457

449458
def test_reindex_axis_style(self):
450459
# https://github.com/pandas-dev/pandas/issues/12392
@@ -963,10 +972,15 @@ def test_take(self):
963972
assert_frame_equal(result, expected, check_names=False)
964973

965974
# illegal indices
966-
pytest.raises(IndexError, df.take, [3, 1, 2, 30], axis=0)
967-
pytest.raises(IndexError, df.take, [3, 1, 2, -31], axis=0)
968-
pytest.raises(IndexError, df.take, [3, 1, 2, 5], axis=1)
969-
pytest.raises(IndexError, df.take, [3, 1, 2, -5], axis=1)
975+
msg = "indices are out-of-bounds"
976+
with pytest.raises(IndexError, match=msg):
977+
df.take([3, 1, 2, 30], axis=0)
978+
with pytest.raises(IndexError, match=msg):
979+
df.take([3, 1, 2, -31], axis=0)
980+
with pytest.raises(IndexError, match=msg):
981+
df.take([3, 1, 2, 5], axis=1)
982+
with pytest.raises(IndexError, match=msg):
983+
df.take([3, 1, 2, -5], axis=1)
970984

971985
# mixed-dtype
972986
order = [4, 1, 2, 0, 3]
@@ -1037,6 +1051,7 @@ def test_reindex_corner(self):
10371051
smaller = self.intframe.reindex(columns=['A', 'B', 'E'])
10381052
assert smaller['E'].dtype == np.float64
10391053

1054+
@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
10401055
def test_reindex_axis(self):
10411056
cols = ['A', 'B', 'E']
10421057
with tm.assert_produces_warning(FutureWarning) as m:
@@ -1052,7 +1067,9 @@ def test_reindex_axis(self):
10521067
reindexed2 = self.intframe.reindex(index=rows)
10531068
assert_frame_equal(reindexed1, reindexed2)
10541069

1055-
pytest.raises(ValueError, self.intframe.reindex_axis, rows, axis=2)
1070+
msg = "No axis named 2 for object type <class 'type'>"
1071+
with pytest.raises(ValueError, match=msg):
1072+
self.intframe.reindex_axis(rows, axis=2)
10561073

10571074
# no-op case
10581075
cols = self.frame.columns.copy()

Diff for: pandas/tests/frame/test_block_internals.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -274,10 +274,12 @@ def f(dtype):
274274
columns=["A", "B", "C"],
275275
dtype=dtype)
276276

277-
pytest.raises(NotImplementedError, f,
278-
[("A", "datetime64[h]"),
279-
("B", "str"),
280-
("C", "int32")])
277+
msg = ("compound dtypes are not implemented in the DataFrame"
278+
" constructor")
279+
with pytest.raises(NotImplementedError, match=msg):
280+
f([("A", "datetime64[h]"),
281+
("B", "str"),
282+
("C", "int32")])
281283

282284
# these work (though results may be unexpected)
283285
f('int64')

Diff for: pandas/tests/frame/test_constructors.py

+34-17
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
import pytest
1313

1414
from pandas.compat import (
15-
PY3, PY36, is_platform_little_endian, lmap, long, lrange, lzip, range, zip)
15+
PY2, PY3, PY36, is_platform_little_endian, lmap, long, lrange, lzip, range,
16+
zip)
1617

1718
from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
1819
from pandas.core.dtypes.common import is_integer_dtype
@@ -58,8 +59,9 @@ def test_constructor_cast_failure(self):
5859
df['foo'] = np.ones((4, 2)).tolist()
5960

6061
# this is not ok
61-
pytest.raises(ValueError, df.__setitem__, tuple(['test']),
62-
np.ones((4, 2)))
62+
msg = "Wrong number of items passed 2, placement implies 1"
63+
with pytest.raises(ValueError, match=msg):
64+
df['test'] = np.ones((4, 2))
6365

6466
# this is ok
6567
df['foo2'] = np.ones((4, 2)).tolist()
@@ -1259,7 +1261,9 @@ def test_constructor_Series_named(self):
12591261
expected = DataFrame({0: s})
12601262
tm.assert_frame_equal(df, expected)
12611263

1262-
pytest.raises(ValueError, DataFrame, s, columns=[1, 2])
1264+
msg = r"Shape of passed values is \(10, 1\), indices imply \(10, 2\)"
1265+
with pytest.raises(ValueError, match=msg):
1266+
DataFrame(s, columns=[1, 2])
12631267

12641268
# #2234
12651269
a = Series([], name='x')
@@ -1433,8 +1437,10 @@ def test_constructor_column_duplicates(self):
14331437

14341438
tm.assert_frame_equal(idf, edf)
14351439

1436-
pytest.raises(ValueError, DataFrame.from_dict,
1437-
OrderedDict([('b', 8), ('a', 5), ('a', 6)]))
1440+
msg = "If using all scalar values, you must pass an index"
1441+
with pytest.raises(ValueError, match=msg):
1442+
DataFrame.from_dict(
1443+
OrderedDict([('b', 8), ('a', 5), ('a', 6)]))
14381444

14391445
def test_constructor_empty_with_string_dtype(self):
14401446
# GH 9428
@@ -1465,8 +1471,11 @@ def test_constructor_single_value(self):
14651471
dtype=object),
14661472
index=[1, 2], columns=['a', 'c']))
14671473

1468-
pytest.raises(ValueError, DataFrame, 'a', [1, 2])
1469-
pytest.raises(ValueError, DataFrame, 'a', columns=['a', 'c'])
1474+
msg = "DataFrame constructor not properly called!"
1475+
with pytest.raises(ValueError, match=msg):
1476+
DataFrame('a', [1, 2])
1477+
with pytest.raises(ValueError, match=msg):
1478+
DataFrame('a', columns=['a', 'c'])
14701479

14711480
msg = 'incompatible data and dtype'
14721481
with pytest.raises(TypeError, match=msg):
@@ -1692,6 +1701,7 @@ def test_constructor_series_copy(self):
16921701

16931702
assert not (series['A'] == 5).all()
16941703

1704+
@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
16951705
def test_constructor_with_nas(self):
16961706
# GH 5016
16971707
# na's in indices
@@ -1704,9 +1714,11 @@ def check(df):
17041714

17051715
# No NaN found -> error
17061716
if len(indexer) == 0:
1707-
def f():
1717+
msg = ("cannot do label indexing on"
1718+
r" <class 'pandas\.core\.indexes\.range\.RangeIndex'>"
1719+
r" with these indexers \[nan\] of <class 'float'>")
1720+
with pytest.raises(TypeError, match=msg):
17081721
df.loc[:, np.nan]
1709-
pytest.raises(TypeError, f)
17101722
# single nan should result in Series
17111723
elif len(indexer) == 1:
17121724
tm.assert_series_equal(df.iloc[:, indexer[0]],
@@ -1782,13 +1794,15 @@ def test_constructor_categorical(self):
17821794
tm.assert_frame_equal(df, expected)
17831795

17841796
# invalid (shape)
1785-
pytest.raises(ValueError,
1786-
lambda: DataFrame([Categorical(list('abc')),
1787-
Categorical(list('abdefg'))]))
1797+
msg = r"Shape of passed values is \(6, 2\), indices imply \(3, 2\)"
1798+
with pytest.raises(ValueError, match=msg):
1799+
DataFrame([Categorical(list('abc')),
1800+
Categorical(list('abdefg'))])
17881801

17891802
# ndim > 1
1790-
pytest.raises(NotImplementedError,
1791-
lambda: Categorical(np.array([list('abcd')])))
1803+
msg = "> 1 ndim Categorical are not supported at this time"
1804+
with pytest.raises(NotImplementedError, match=msg):
1805+
Categorical(np.array([list('abcd')]))
17921806

17931807
def test_constructor_categorical_series(self):
17941808

@@ -2164,8 +2178,11 @@ def test_from_records_bad_index_column(self):
21642178
tm.assert_index_equal(df1.index, Index(df.C))
21652179

21662180
# should fail
2167-
pytest.raises(ValueError, DataFrame.from_records, df, index=[2])
2168-
pytest.raises(KeyError, DataFrame.from_records, df, index=2)
2181+
msg = r"Shape of passed values is \(10, 3\), indices imply \(1, 3\)"
2182+
with pytest.raises(ValueError, match=msg):
2183+
DataFrame.from_records(df, index=[2])
2184+
with pytest.raises(KeyError, match=r"^2$"):
2185+
DataFrame.from_records(df, index=2)
21692186

21702187
def test_from_records_non_tuple(self):
21712188
class Record(object):

Diff for: pandas/tests/frame/test_convert_to.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -75,11 +75,15 @@ def test_to_dict_index_not_unique_with_index_orient(self):
7575
# GH22801
7676
# Data loss when indexes are not unique. Raise ValueError.
7777
df = DataFrame({'a': [1, 2], 'b': [0.5, 0.75]}, index=['A', 'A'])
78-
pytest.raises(ValueError, df.to_dict, orient='index')
78+
msg = "DataFrame index must be unique for orient='index'"
79+
with pytest.raises(ValueError, match=msg):
80+
df.to_dict(orient='index')
7981

8082
def test_to_dict_invalid_orient(self):
8183
df = DataFrame({'A': [0, 1]})
82-
pytest.raises(ValueError, df.to_dict, orient='xinvalid')
84+
msg = "orient 'xinvalid' not understood"
85+
with pytest.raises(ValueError, match=msg):
86+
df.to_dict(orient='xinvalid')
8387

8488
def test_to_records_dt64(self):
8589
df = DataFrame([["one", "two", "three"],

0 commit comments

Comments
 (0)