Skip to content

Commit f13859d

Browse files
simonjayhawkinsjreback
authored andcommitted
STY: use pytest.raises context syntax (#24655)
* STY: use pytest.raises context syntax * fix CI failures * fix CI failures
1 parent fbd39d9 commit f13859d

File tree

8 files changed

+123
-75
lines changed

8 files changed

+123
-75
lines changed

pandas/tests/io/formats/test_format.py

+9-4
Original file line numberDiff line numberDiff line change
@@ -2720,7 +2720,12 @@ def test_format_percentiles():
27202720
expected = ['0%', '50%', '2.0%', '50%', '66.67%', '99.99%']
27212721
assert result == expected
27222722

2723-
pytest.raises(ValueError, fmt.format_percentiles, [0.1, np.nan, 0.5])
2724-
pytest.raises(ValueError, fmt.format_percentiles, [-0.001, 0.1, 0.5])
2725-
pytest.raises(ValueError, fmt.format_percentiles, [2, 0.1, 0.5])
2726-
pytest.raises(ValueError, fmt.format_percentiles, [0.1, 0.5, 'a'])
2723+
msg = r"percentiles should all be in the interval \[0,1\]"
2724+
with pytest.raises(ValueError, match=msg):
2725+
fmt.format_percentiles([0.1, np.nan, 0.5])
2726+
with pytest.raises(ValueError, match=msg):
2727+
fmt.format_percentiles([-0.001, 0.1, 0.5])
2728+
with pytest.raises(ValueError, match=msg):
2729+
fmt.format_percentiles([2, 0.1, 0.5])
2730+
with pytest.raises(ValueError, match=msg):
2731+
fmt.format_percentiles([0.1, 0.5, 'a'])

pandas/tests/io/json/test_normalize.py

+12-8
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,9 @@ def test_meta_name_conflict(self):
197197
'data': [{'foo': 'something', 'bar': 'else'},
198198
{'foo': 'something2', 'bar': 'else2'}]}]
199199

200-
with pytest.raises(ValueError):
200+
msg = (r"Conflicting metadata name (foo|bar),"
201+
" need distinguishing prefix")
202+
with pytest.raises(ValueError, match=msg):
201203
json_normalize(data, 'data', meta=['foo', 'bar'])
202204

203205
result = json_normalize(data, 'data', meta=['foo', 'bar'],
@@ -366,13 +368,15 @@ def test_json_normalize_errors(self):
366368

367369
assert j.fillna('').to_dict() == expected
368370

369-
pytest.raises(KeyError,
370-
json_normalize, data=i['Trades'],
371-
record_path=[['general', 'stocks']],
372-
meta=[['general', 'tradeid'],
373-
['general', 'trade_version']],
374-
errors='raise'
375-
)
371+
msg = ("Try running with errors='ignore' as key 'trade_version'"
372+
" is not always present")
373+
with pytest.raises(KeyError, match=msg):
374+
json_normalize(
375+
data=i['Trades'],
376+
record_path=[['general', 'stocks']],
377+
meta=[['general', 'tradeid'],
378+
['general', 'trade_version']],
379+
errors='raise')
376380

377381
def test_donot_drop_nonevalues(self):
378382
# GH21356

pandas/tests/io/json/test_pandas.py

+56-29
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,12 @@ def test_frame_non_unique_index(self):
101101
df = DataFrame([['a', 'b'], ['c', 'd']], index=[1, 1],
102102
columns=['x', 'y'])
103103

104-
pytest.raises(ValueError, df.to_json, orient='index')
105-
pytest.raises(ValueError, df.to_json, orient='columns')
104+
msg = "DataFrame index must be unique for orient='index'"
105+
with pytest.raises(ValueError, match=msg):
106+
df.to_json(orient='index')
107+
msg = "DataFrame index must be unique for orient='columns'"
108+
with pytest.raises(ValueError, match=msg):
109+
df.to_json(orient='columns')
106110

107111
assert_frame_equal(df, read_json(df.to_json(orient='split'),
108112
orient='split'))
@@ -116,9 +120,15 @@ def test_frame_non_unique_columns(self):
116120
df = DataFrame([['a', 'b'], ['c', 'd']], index=[1, 2],
117121
columns=['x', 'x'])
118122

119-
pytest.raises(ValueError, df.to_json, orient='index')
120-
pytest.raises(ValueError, df.to_json, orient='columns')
121-
pytest.raises(ValueError, df.to_json, orient='records')
123+
msg = "DataFrame columns must be unique for orient='index'"
124+
with pytest.raises(ValueError, match=msg):
125+
df.to_json(orient='index')
126+
msg = "DataFrame columns must be unique for orient='columns'"
127+
with pytest.raises(ValueError, match=msg):
128+
df.to_json(orient='columns')
129+
msg = "DataFrame columns must be unique for orient='records'"
130+
with pytest.raises(ValueError, match=msg):
131+
df.to_json(orient='records')
122132

123133
assert_frame_equal(df, read_json(df.to_json(orient='split'),
124134
orient='split', dtype=False))
@@ -156,13 +166,16 @@ def _check_orient(df, orient, dtype=None, numpy=False,
156166
# if we are not unique, then check that we are raising ValueError
157167
# for the appropriate orients
158168
if not df.index.is_unique and orient in ['index', 'columns']:
159-
pytest.raises(
160-
ValueError, lambda: df.to_json(orient=orient))
169+
msg = ("DataFrame index must be unique for orient='{}'"
170+
.format(orient))
171+
with pytest.raises(ValueError, match=msg):
172+
df.to_json(orient=orient)
161173
return
162174
if (not df.columns.is_unique and
163175
orient in ['index', 'columns', 'records']):
164-
pytest.raises(
165-
ValueError, lambda: df.to_json(orient=orient))
176+
# TODO: not executed. fix this.
177+
with pytest.raises(ValueError, match='ksjkajksfjksjfkjs'):
178+
df.to_json(orient=orient)
166179
return
167180

168181
dfjson = df.to_json(orient=orient)
@@ -326,21 +339,24 @@ def _check_all_orients(df, dtype=None, convert_axes=True,
326339
_check_orient(df.transpose().transpose(), "index", dtype=False)
327340

328341
def test_frame_from_json_bad_data(self):
329-
pytest.raises(ValueError, read_json, StringIO('{"key":b:a:d}'))
342+
with pytest.raises(ValueError, match='Expected object or value'):
343+
read_json(StringIO('{"key":b:a:d}'))
330344

331345
# too few indices
332346
json = StringIO('{"columns":["A","B"],'
333347
'"index":["2","3"],'
334348
'"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}')
335-
pytest.raises(ValueError, read_json, json,
336-
orient="split")
349+
msg = r"Shape of passed values is \(2, 3\), indices imply \(2, 2\)"
350+
with pytest.raises(ValueError, match=msg):
351+
read_json(json, orient="split")
337352

338353
# too many columns
339354
json = StringIO('{"columns":["A","B","C"],'
340355
'"index":["1","2","3"],'
341356
'"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}')
342-
pytest.raises(AssertionError, read_json, json,
343-
orient="split")
357+
msg = "3 columns passed, passed data had 2 columns"
358+
with pytest.raises(AssertionError, match=msg):
359+
read_json(json, orient="split")
344360

345361
# bad key
346362
json = StringIO('{"badkey":["A","B"],'
@@ -414,7 +430,9 @@ def test_frame_to_json_float_precision(self):
414430

415431
def test_frame_to_json_except(self):
416432
df = DataFrame([1, 2, 3])
417-
pytest.raises(ValueError, df.to_json, orient="garbage")
433+
msg = "Invalid value 'garbage' for option 'orient'"
434+
with pytest.raises(ValueError, match=msg):
435+
df.to_json(orient="garbage")
418436

419437
def test_frame_empty(self):
420438
df = DataFrame(columns=['jim', 'joe'])
@@ -540,7 +558,8 @@ def __str__(self):
540558

541559
# check if non-printable content throws appropriate Exception
542560
df_nonprintable = DataFrame({'A': [binthing]})
543-
with pytest.raises(OverflowError):
561+
msg = "Unsupported UTF-8 sequence length when encoding string"
562+
with pytest.raises(OverflowError, match=msg):
544563
df_nonprintable.to_json()
545564

546565
# the same with multiple columns threw segfaults
@@ -565,7 +584,9 @@ def test_label_overflow(self):
565584
def test_series_non_unique_index(self):
566585
s = Series(['a', 'b'], index=[1, 1])
567586

568-
pytest.raises(ValueError, s.to_json, orient='index')
587+
msg = "Series index must be unique for orient='index'"
588+
with pytest.raises(ValueError, match=msg):
589+
s.to_json(orient='index')
569590

570591
assert_series_equal(s, read_json(s.to_json(orient='split'),
571592
orient='split', typ='series'))
@@ -637,7 +658,9 @@ def _check_all_orients(series, dtype=None, check_index_type=True):
637658

638659
def test_series_to_json_except(self):
639660
s = Series([1, 2, 3])
640-
pytest.raises(ValueError, s.to_json, orient="garbage")
661+
msg = "Invalid value 'garbage' for option 'orient'"
662+
with pytest.raises(ValueError, match=msg):
663+
s.to_json(orient="garbage")
641664

642665
def test_series_from_json_precise_float(self):
643666
s = Series([4.56, 4.56, 4.56])
@@ -752,8 +775,9 @@ def test_w_date(date, date_unit=None):
752775
test_w_date('20130101 20:43:42.123456', date_unit='us')
753776
test_w_date('20130101 20:43:42.123456789', date_unit='ns')
754777

755-
pytest.raises(ValueError, df.to_json, date_format='iso',
756-
date_unit='foo')
778+
msg = "Invalid value 'foo' for option 'date_unit'"
779+
with pytest.raises(ValueError, match=msg):
780+
df.to_json(date_format='iso', date_unit='foo')
757781

758782
def test_date_format_series(self):
759783
def test_w_date(date, date_unit=None):
@@ -774,8 +798,9 @@ def test_w_date(date, date_unit=None):
774798
test_w_date('20130101 20:43:42.123456789', date_unit='ns')
775799

776800
ts = Series(Timestamp('20130101 20:43:42.123'), index=self.ts.index)
777-
pytest.raises(ValueError, ts.to_json, date_format='iso',
778-
date_unit='foo')
801+
msg = "Invalid value 'foo' for option 'date_unit'"
802+
with pytest.raises(ValueError, match=msg):
803+
ts.to_json(date_format='iso', date_unit='foo')
779804

780805
def test_date_unit(self):
781806
df = self.tsframe.copy()
@@ -940,14 +965,16 @@ def test_default_handler_numpy_unsupported_dtype(self):
940965
assert df.to_json(default_handler=str, orient="values") == expected
941966

942967
def test_default_handler_raises(self):
968+
msg = "raisin"
969+
943970
def my_handler_raises(obj):
944-
raise TypeError("raisin")
945-
pytest.raises(TypeError,
946-
DataFrame({'a': [1, 2, object()]}).to_json,
947-
default_handler=my_handler_raises)
948-
pytest.raises(TypeError,
949-
DataFrame({'a': [1, 2, complex(4, -5)]}).to_json,
950-
default_handler=my_handler_raises)
971+
raise TypeError(msg)
972+
with pytest.raises(TypeError, match=msg):
973+
DataFrame({'a': [1, 2, object()]}).to_json(
974+
default_handler=my_handler_raises)
975+
with pytest.raises(TypeError, match=msg):
976+
DataFrame({'a': [1, 2, complex(4, -5)]}).to_json(
977+
default_handler=my_handler_raises)
951978

952979
def test_categorical(self):
953980
# GH4377 df.to_json segfaults with non-ndarray blocks

pandas/tests/io/json/test_ujson.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -422,7 +422,9 @@ def test_datetime_units(self):
422422
roundtrip = ujson.decode(ujson.encode(val, date_unit='ns'))
423423
assert roundtrip == stamp.value
424424

425-
pytest.raises(ValueError, ujson.encode, val, date_unit='foo')
425+
msg = "Invalid value 'foo' for option 'date_unit'"
426+
with pytest.raises(ValueError, match=msg):
427+
ujson.encode(val, date_unit='foo')
426428

427429
def test_encode_to_utf8(self):
428430
unencoded = "\xe6\x97\xa5\xd1\x88"
@@ -695,7 +697,9 @@ def recursive_attr(self):
695697
def __str__(self):
696698
return str(self.val)
697699

698-
pytest.raises(OverflowError, ujson.encode, _TestObject("foo"))
700+
msg = "Maximum recursion level reached"
701+
with pytest.raises(OverflowError, match=msg):
702+
ujson.encode(_TestObject("foo"))
699703
assert '"foo"' == ujson.encode(_TestObject("foo"),
700704
default_handler=str)
701705

pandas/tests/io/msgpack/test_except.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -22,16 +22,16 @@ def test_raise_from_object_hook(self):
2222
def hook(_):
2323
raise DummyException()
2424

25-
pytest.raises(DummyException, unpackb, packb({}), object_hook=hook)
26-
pytest.raises(DummyException, unpackb, packb({'fizz': 'buzz'}),
27-
object_hook=hook)
28-
pytest.raises(DummyException, unpackb, packb({'fizz': 'buzz'}),
29-
object_pairs_hook=hook)
30-
pytest.raises(DummyException, unpackb,
31-
packb({'fizz': {'buzz': 'spam'}}), object_hook=hook)
32-
pytest.raises(DummyException, unpackb,
33-
packb({'fizz': {'buzz': 'spam'}}),
34-
object_pairs_hook=hook)
25+
with pytest.raises(DummyException):
26+
unpackb(packb({}), object_hook=hook)
27+
with pytest.raises(DummyException):
28+
unpackb(packb({'fizz': 'buzz'}), object_hook=hook)
29+
with pytest.raises(DummyException):
30+
unpackb(packb({'fizz': 'buzz'}), object_pairs_hook=hook)
31+
with pytest.raises(DummyException):
32+
unpackb(packb({'fizz': {'buzz': 'spam'}}), object_hook=hook)
33+
with pytest.raises(DummyException):
34+
unpackb(packb({'fizz': {'buzz': 'spam'}}), object_pairs_hook=hook)
3535

3636
def test_invalid_value(self):
3737
msg = "Unpack failed: error"

pandas/tests/io/msgpack/test_limits.py

+10-6
Original file line numberDiff line numberDiff line change
@@ -12,22 +12,26 @@ class TestLimits(object):
1212
def test_integer(self):
1313
x = -(2 ** 63)
1414
assert unpackb(packb(x)) == x
15-
pytest.raises((OverflowError, ValueError), packb, x - 1)
15+
msg = (r"((long |Python )?(int )?too (big|large) to convert"
16+
r"( to C (unsigned )?long))?")
17+
with pytest.raises((OverflowError, ValueError), match=msg):
18+
packb(x - 1)
1619
x = 2 ** 64 - 1
1720
assert unpackb(packb(x)) == x
18-
pytest.raises((OverflowError, ValueError), packb, x + 1)
21+
with pytest.raises((OverflowError, ValueError), match=msg):
22+
packb(x + 1)
1923

2024
def test_array_header(self):
2125
packer = Packer()
2226
packer.pack_array_header(2 ** 32 - 1)
23-
pytest.raises((OverflowError, ValueError),
24-
packer.pack_array_header, 2 ** 32)
27+
with pytest.raises((OverflowError, ValueError)):
28+
packer.pack_array_header(2 ** 32)
2529

2630
def test_map_header(self):
2731
packer = Packer()
2832
packer.pack_map_header(2 ** 32 - 1)
29-
pytest.raises((OverflowError, ValueError),
30-
packer.pack_array_header, 2 ** 32)
33+
with pytest.raises((OverflowError, ValueError)):
34+
packer.pack_array_header(2 ** 32)
3135

3236
def test_max_str_len(self):
3337
d = 'x' * 3

pandas/tests/io/msgpack/test_obj.py

+8-11
Original file line numberDiff line numberDiff line change
@@ -47,31 +47,28 @@ def test_decode_pairs_hook(self):
4747
assert unpacked[1] == prod_sum
4848

4949
def test_only_one_obj_hook(self):
50-
pytest.raises(TypeError, unpackb, b'', object_hook=lambda x: x,
51-
object_pairs_hook=lambda x: x)
50+
msg = "object_pairs_hook and object_hook are mutually exclusive"
51+
with pytest.raises(TypeError, match=msg):
52+
unpackb(b'', object_hook=lambda x: x,
53+
object_pairs_hook=lambda x: x)
5254

5355
def test_bad_hook(self):
54-
def f():
56+
msg = r"can't serialize \(1\+2j\)"
57+
with pytest.raises(TypeError, match=msg):
5558
packed = packb([3, 1 + 2j], default=lambda o: o)
5659
unpacked = unpackb(packed, use_list=1) # noqa
5760

58-
pytest.raises(TypeError, f)
59-
6061
def test_array_hook(self):
6162
packed = packb([1, 2, 3])
6263
unpacked = unpackb(packed, list_hook=self._arr_to_str, use_list=1)
6364
assert unpacked == '123'
6465

6566
def test_an_exception_in_objecthook1(self):
66-
def f():
67+
with pytest.raises(DecodeError, match='Ooops!'):
6768
packed = packb({1: {'__complex__': True, 'real': 1, 'imag': 2}})
6869
unpackb(packed, object_hook=self.bad_complex_decoder)
6970

70-
pytest.raises(DecodeError, f)
71-
7271
def test_an_exception_in_objecthook2(self):
73-
def f():
72+
with pytest.raises(DecodeError, match='Ooops!'):
7473
packed = packb({1: [{'__complex__': True, 'real': 1, 'imag': 2}]})
7574
unpackb(packed, list_hook=self.bad_complex_decoder, use_list=1)
76-
77-
pytest.raises(DecodeError, f)

pandas/tests/io/msgpack/test_pack.py

+12-5
Original file line numberDiff line numberDiff line change
@@ -67,12 +67,17 @@ def testIgnoreUnicodeErrors(self):
6767
assert re == "abcdef"
6868

6969
def testStrictUnicodeUnpack(self):
70-
pytest.raises(UnicodeDecodeError, unpackb, packb(b'abc\xeddef'),
71-
encoding='utf-8', use_list=1)
70+
msg = (r"'utf-*8' codec can't decode byte 0xed in position 3:"
71+
" invalid continuation byte")
72+
with pytest.raises(UnicodeDecodeError, match=msg):
73+
unpackb(packb(b'abc\xeddef'), encoding='utf-8', use_list=1)
7274

7375
def testStrictUnicodePack(self):
74-
pytest.raises(UnicodeEncodeError, packb, compat.u("abc\xeddef"),
75-
encoding='ascii', unicode_errors='strict')
76+
msg = (r"'ascii' codec can't encode character u*'\\xed' in position 3:"
77+
r" ordinal not in range\(128\)")
78+
with pytest.raises(UnicodeEncodeError, match=msg):
79+
packb(compat.u("abc\xeddef"), encoding='ascii',
80+
unicode_errors='strict')
7681

7782
def testIgnoreErrorsPack(self):
7883
re = unpackb(
@@ -82,7 +87,9 @@ def testIgnoreErrorsPack(self):
8287
assert re == compat.u("abcdef")
8388

8489
def testNoEncoding(self):
85-
pytest.raises(TypeError, packb, compat.u("abc"), encoding=None)
90+
msg = "Can't encode unicode string: no encoding is specified"
91+
with pytest.raises(TypeError, match=msg):
92+
packb(compat.u("abc"), encoding=None)
8693

8794
def testDecodeBinary(self):
8895
re = unpackb(packb("abc"), encoding=None, use_list=1)

0 commit comments

Comments
 (0)