Skip to content

Commit c544677

Browse files
committed
CLN/TST: cleanup exception message testing by replacing with assertRaisesRegexp
1 parent fd87e4f commit c544677

File tree

2 files changed

+29
-51
lines changed

2 files changed

+29
-51
lines changed

pandas/tests/test_frame.py

+21-38
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,12 @@
2525
from pandas import date_range
2626
import pandas as pd
2727
from pandas.io.parsers import read_csv
28+
from pandas.parser import CParserError
2829

2930
from pandas.util.testing import (assert_almost_equal,
3031
assert_series_equal,
3132
assert_frame_equal,
33+
assertRaisesRegexp,
3234
makeCustomDataframe as mkdf,
3335
ensure_clean)
3436
from pandas.util import py3compat
@@ -2208,60 +2210,45 @@ def test_constructor_dict(self):
22082210
def test_constructor_error_msgs(self):
22092211

22102212
# mix dict and array, wrong size
2211-
try:
2213+
def testit():
22122214
DataFrame({'A': {'a': 'a', 'b': 'b'},
22132215
'B': ['a', 'b', 'c']})
2214-
except (Exception), detail:
2215-
self.assert_(type(detail) == ValueError)
2216-
self.assert_("Mixing dicts with non-Series may lead to ambiguous ordering." in str(detail))
2216+
assertRaisesRegexp(ValueError, "Mixing dicts with non-Series may lead to ambiguous ordering.", testit)
22172217

22182218
# wrong size ndarray, GH 3105
2219-
try:
2219+
def testit():
22202220
DataFrame(np.arange(12).reshape((4, 3)), columns=['foo', 'bar', 'baz'],
22212221
index=date_range('2000-01-01', periods=3))
2222-
except (Exception), detail:
2223-
self.assert_(type(detail) == ValueError)
2224-
self.assert_(str(detail).startswith("Shape of passed values is (3, 4), indices imply (3, 3)"))
2222+
assertRaisesRegexp(ValueError, "Shape of passed values is \(3, 4\), indices imply \(3, 3\)", testit)
22252223

22262224
# higher dim raise exception
2227-
try:
2225+
def testit():
22282226
DataFrame(np.zeros((3, 3, 3)), columns=['A', 'B', 'C'], index=[1])
2229-
except (Exception), detail:
2230-
self.assert_(type(detail) == ValueError)
2231-
self.assert_("Must pass 2-d input" in str(detail))
2227+
assertRaisesRegexp(ValueError, "Must pass 2-d input", testit)
22322228

22332229
# wrong size axis labels
2234-
try:
2230+
def testit():
22352231
DataFrame(np.random.rand(2,3), columns=['A', 'B', 'C'], index=[1])
2236-
except (Exception), detail:
2237-
self.assert_(type(detail) == ValueError)
2238-
self.assert_(str(detail).startswith("Shape of passed values is (3, 2), indices imply (3, 1)"))
2232+
assertRaisesRegexp(ValueError, "Shape of passed values is \(3, 2\), indices imply \(3, 1\)", testit)
22392233

2240-
try:
2234+
def testit():
22412235
DataFrame(np.random.rand(2,3), columns=['A', 'B'], index=[1, 2])
2242-
except (Exception), detail:
2243-
self.assert_(type(detail) == ValueError)
2244-
self.assert_(str(detail).startswith("Shape of passed values is (3, 2), indices imply (2, 2)"))
2236+
assertRaisesRegexp(ValueError, "Shape of passed values is \(3, 2\), indices imply \(2, 2\)", testit)
22452237

2246-
try:
2238+
def testit():
22472239
DataFrame({'a': False, 'b': True})
2248-
except (Exception), detail:
2249-
msg = 'If using all scalar values, you must must pass an index'
2250-
self.assert_(type(detail) == ValueError)
2251-
self.assert_(msg in str(detail))
2240+
assertRaisesRegexp(ValueError, 'If using all scalar values, you must must pass an index', testit)
22522241

22532242
def test_insert_error_msmgs(self):
22542243

22552244
# GH 4107, more descriptive error message
22562245
df = DataFrame(np.random.randint(0,2,(4,4)),
22572246
columns=['a', 'b', 'c', 'd'])
22582247

2259-
try:
2248+
def testit():
22602249
df['gr'] = df.groupby(['b', 'c']).count()
2261-
except (Exception), detail:
2262-
msg = 'incompatible index of inserted column with frame index'
2263-
self.assert_(type(detail) == TypeError)
2264-
self.assert_(msg in str(detail))
2250+
2251+
assertRaisesRegexp(TypeError, 'incompatible index of inserted column with frame index', testit)
22652252

22662253
def test_constructor_subclass_dict(self):
22672254
# Test for passing dict subclass to constructor
@@ -5133,17 +5120,13 @@ def _make_frame(names=None):
51335120
df.to_csv(path,tupleize_cols=False)
51345121

51355122
# catch invalid headers
5136-
try:
5123+
def testit():
51375124
read_csv(path,tupleize_cols=False,header=range(3),index_col=0)
5138-
except (Exception), detail:
5139-
if not str(detail).startswith('Passed header=[0,1,2] are too many rows for this multi_index of columns'):
5140-
raise AssertionError("failure in read_csv header=range(3)")
5125+
assertRaisesRegexp(CParserError, 'Passed header=\[0,1,2\] are too many rows for this multi_index of columns', testit)
51415126

5142-
try:
5127+
def testit():
51435128
read_csv(path,tupleize_cols=False,header=range(7),index_col=0)
5144-
except (Exception), detail:
5145-
if not str(detail).startswith('Passed header=[0,1,2,3,4,5,6], len of 7, but only 6 lines in file'):
5146-
raise AssertionError("failure in read_csv header=range(7)")
5129+
assertRaisesRegexp(CParserError, 'Passed header=\[0,1,2,3,4,5,6\], len of 7, but only 6 lines in file', testit)
51475130

51485131
for i in [3,4,5,6,7]:
51495132
self.assertRaises(Exception, read_csv, path, tupleize_cols=False, header=range(i), index_col=0)

pandas/tests/test_panel.py

+8-13
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
assert_series_equal,
2121
assert_almost_equal,
2222
ensure_clean,
23+
assertRaisesRegexp,
2324
makeCustomDataframe as mkdf
2425
)
2526
import pandas.core.panel as panelm
@@ -959,23 +960,17 @@ def test_from_dict_mixed_orient(self):
959960

960961
def test_constructor_error_msgs(self):
961962

962-
try:
963+
def testit():
963964
Panel(np.random.randn(3,4,5), range(4), range(5), range(5))
964-
except (Exception), detail:
965-
self.assert_(type(detail) == ValueError)
966-
self.assert_(str(detail).startswith("Shape of passed values is (3, 4, 5), indices imply (4, 5, 5)"))
965+
assertRaisesRegexp(ValueError, "Shape of passed values is \(3, 4, 5\), indices imply \(4, 5, 5\)", testit)
967966

968-
try:
967+
def testit():
969968
Panel(np.random.randn(3,4,5), range(5), range(4), range(5))
970-
except (Exception), detail:
971-
self.assert_(type(detail) == ValueError)
972-
self.assert_(str(detail).startswith("Shape of passed values is (3, 4, 5), indices imply (5, 4, 5)"))
969+
assertRaisesRegexp(ValueError, "Shape of passed values is \(3, 4, 5\), indices imply \(5, 4, 5\)", testit)
973970

974-
try:
971+
def testit():
975972
Panel(np.random.randn(3,4,5), range(5), range(5), range(4))
976-
except (Exception), detail:
977-
self.assert_(type(detail) == ValueError)
978-
self.assert_(str(detail).startswith("Shape of passed values is (3, 4, 5), indices imply (5, 5, 4)"))
973+
assertRaisesRegexp(ValueError, "Shape of passed values is \(3, 4, 5\), indices imply \(5, 5, 4\)", testit)
979974

980975
def test_conform(self):
981976
df = self.panel['ItemA'][:-5].filter(items=['A', 'B'])
@@ -1385,7 +1380,7 @@ def test_to_excel(self):
13851380
reader = ExcelFile(path)
13861381
except ImportError:
13871382
raise nose.SkipTest
1388-
1383+
13891384
for item, df in self.panel.iterkv():
13901385
recdf = reader.parse(str(item), index_col=0)
13911386
assert_frame_equal(df, recdf)

0 commit comments

Comments
 (0)