Skip to content

CLN/TST: cleanup exception message testing by replacing with assertRaisesRegexp #4114

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 3, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 21 additions & 38 deletions pandas/tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,12 @@
from pandas import date_range
import pandas as pd
from pandas.io.parsers import read_csv
from pandas.parser import CParserError

from pandas.util.testing import (assert_almost_equal,
assert_series_equal,
assert_frame_equal,
assertRaisesRegexp,
makeCustomDataframe as mkdf,
ensure_clean)
from pandas.util import py3compat
Expand Down Expand Up @@ -2208,60 +2210,45 @@ def test_constructor_dict(self):
def test_constructor_error_msgs(self):

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

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

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

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

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

try:
def testit():
DataFrame({'a': False, 'b': True})
except (Exception), detail:
msg = 'If using all scalar values, you must must pass an index'
self.assert_(type(detail) == ValueError)
self.assert_(msg in str(detail))
assertRaisesRegexp(ValueError, 'If using all scalar values, you must must pass an index', testit)

def test_insert_error_msmgs(self):

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

try:
def testit():
df['gr'] = df.groupby(['b', 'c']).count()
except (Exception), detail:
msg = 'incompatible index of inserted column with frame index'
self.assert_(type(detail) == TypeError)
self.assert_(msg in str(detail))

assertRaisesRegexp(TypeError, 'incompatible index of inserted column with frame index', testit)

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

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

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

for i in [3,4,5,6,7]:
self.assertRaises(Exception, read_csv, path, tupleize_cols=False, header=range(i), index_col=0)
Expand Down
21 changes: 8 additions & 13 deletions pandas/tests/test_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
assert_series_equal,
assert_almost_equal,
ensure_clean,
assertRaisesRegexp,
makeCustomDataframe as mkdf
)
import pandas.core.panel as panelm
Expand Down Expand Up @@ -959,23 +960,17 @@ def test_from_dict_mixed_orient(self):

def test_constructor_error_msgs(self):

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

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

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

def test_conform(self):
df = self.panel['ItemA'][:-5].filter(items=['A', 'B'])
Expand Down Expand Up @@ -1385,7 +1380,7 @@ def test_to_excel(self):
reader = ExcelFile(path)
except ImportError:
raise nose.SkipTest

for item, df in self.panel.iterkv():
recdf = reader.parse(str(item), index_col=0)
assert_frame_equal(df, recdf)
Expand Down