Skip to content

Commit 5c853fc

Browse files
committed
ENH/CLN: Give AssertionErrors and nose.SkipTest raises a message
1 parent 1f00335 commit 5c853fc

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

47 files changed

+414
-268
lines changed

pandas/core/panel.py

+26-10
Original file line numberDiff line numberDiff line change
@@ -528,9 +528,14 @@ def get_value(self, *args):
528528
-------
529529
value : scalar value
530530
"""
531+
nargs = len(args)
532+
nreq = self._AXIS_LEN
533+
531534
# require an arg for each axis
532-
if not ((len(args) == self._AXIS_LEN)):
533-
raise AssertionError()
535+
if nargs != nreq:
536+
raise TypeError('There must be an argument for each axis, you gave'
537+
' {0} args, but {1} are required'.format(nargs,
538+
nreq))
534539

535540
# hm, two layers to the onion
536541
frame = self._get_item_cache(args[0])
@@ -554,8 +559,13 @@ def set_value(self, *args):
554559
otherwise a new object
555560
"""
556561
# require an arg for each axis and the value
557-
if not ((len(args) == self._AXIS_LEN + 1)):
558-
raise AssertionError()
562+
nargs = len(args)
563+
nreq = self._AXIS_LEN + 1
564+
565+
if nargs != nreq:
566+
raise TypeError('There must be an argument for each axis plus the '
567+
'value provided, you gave {0} args, but {1} are '
568+
'required'.format(nargs, nreq))
559569

560570
try:
561571
frame = self._get_item_cache(args[0])
@@ -592,8 +602,10 @@ def __setitem__(self, key, value):
592602
**self._construct_axes_dict_for_slice(self._AXIS_ORDERS[1:]))
593603
mat = value.values
594604
elif isinstance(value, np.ndarray):
595-
if not ((value.shape == shape[1:])):
596-
raise AssertionError()
605+
if value.shape != shape[1:]:
606+
raise ValueError('shape of value must be {0}, shape of given '
607+
'object was {1}'.format(shape[1:],
608+
value.shape))
597609
mat = np.asarray(value)
598610
elif np.isscalar(value):
599611
dtype, value = _infer_dtype_from_scalar(value)
@@ -1144,8 +1156,9 @@ def _extract_axes(self, data, axes, **kwargs):
11441156
@staticmethod
11451157
def _extract_axes_for_slice(self, axes):
11461158
""" return the slice dictionary for these axes """
1147-
return dict([(self._AXIS_SLICEMAP[i], a) for i, a
1148-
in zip(self._AXIS_ORDERS[self._AXIS_LEN - len(axes):], axes)])
1159+
return dict([(self._AXIS_SLICEMAP[i], a)
1160+
for i, a in zip(self._AXIS_ORDERS[self._AXIS_LEN -
1161+
len(axes):], axes)])
11491162

11501163
@staticmethod
11511164
def _prep_ndarray(self, values, copy=True):
@@ -1157,8 +1170,11 @@ def _prep_ndarray(self, values, copy=True):
11571170
else:
11581171
if copy:
11591172
values = values.copy()
1160-
if not ((values.ndim == self._AXIS_LEN)):
1161-
raise AssertionError()
1173+
if values.ndim != self._AXIS_LEN:
1174+
raise ValueError("The number of dimensions required is {0}, "
1175+
"but the number of dimensions of the "
1176+
"ndarray given was {1}".format(self._AXIS_LEN,
1177+
values.ndim))
11621178
return values
11631179

11641180
@staticmethod

pandas/core/series.py

+11-7
Original file line numberDiff line numberDiff line change
@@ -1299,9 +1299,6 @@ def __unicode__(self):
12991299
dtype=True)
13001300
else:
13011301
result = u('Series([], dtype: %s)') % self.dtype
1302-
1303-
if not (isinstance(result, compat.text_type)):
1304-
raise AssertionError()
13051302
return result
13061303

13071304
def _tidy_repr(self, max_vals=20):
@@ -1377,7 +1374,9 @@ def to_string(self, buf=None, na_rep='NaN', float_format=None,
13771374

13781375
# catch contract violations
13791376
if not isinstance(the_repr, compat.text_type):
1380-
raise AssertionError("expected unicode string")
1377+
raise AssertionError("result must be of type unicode, type"
1378+
" of result is {0!r}"
1379+
"".format(the_repr.__class__.__name__))
13811380

13821381
if buf is None:
13831382
return the_repr
@@ -1397,11 +1396,16 @@ def _get_repr(
13971396
"""
13981397

13991398
formatter = fmt.SeriesFormatter(self, name=name, header=print_header,
1400-
length=length, dtype=dtype, na_rep=na_rep,
1399+
length=length, dtype=dtype,
1400+
na_rep=na_rep,
14011401
float_format=float_format)
14021402
result = formatter.to_string()
1403-
if not (isinstance(result, compat.text_type)):
1404-
raise AssertionError()
1403+
1404+
# TODO: following check prob. not neces.
1405+
if not isinstance(result, compat.text_type):
1406+
raise AssertionError("result must be of type unicode, type"
1407+
" of result is {0!r}"
1408+
"".format(result.__class__.__name__))
14051409
return result
14061410

14071411
def __iter__(self):

pandas/io/date_converters.py

+11-7
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
"""This module is designed for community supported date conversion functions"""
2-
from pandas.compat import range
2+
from pandas.compat import range, map
33
import numpy as np
44
import pandas.lib as lib
55

@@ -47,12 +47,16 @@ def _maybe_cast(arr):
4747

4848

4949
def _check_columns(cols):
50-
if not ((len(cols) > 0)):
51-
raise AssertionError()
50+
if not len(cols):
51+
raise AssertionError("There must be at least 1 column")
5252

53-
N = len(cols[0])
54-
for c in cols[1:]:
55-
if not ((len(c) == N)):
56-
raise AssertionError()
53+
head, tail = cols[0], cols[1:]
54+
55+
N = len(head)
56+
57+
for i, n in enumerate(map(len, tail)):
58+
if n != N:
59+
raise AssertionError('All columns must have the same length: {0}; '
60+
'column {1} has length {2}'.format(N, i, n))
5761

5862
return N

pandas/io/parsers.py

+20-11
Original file line numberDiff line numberDiff line change
@@ -552,8 +552,10 @@ def _clean_options(self, options, engine):
552552

553553
# type conversion-related
554554
if converters is not None:
555-
if not (isinstance(converters, dict)):
556-
raise AssertionError()
555+
if not isinstance(converters, dict):
556+
raise TypeError('Type converters must be a dict or'
557+
' subclass, input was '
558+
'a {0!r}'.format(type(converters).__name__))
557559
else:
558560
converters = {}
559561

@@ -631,6 +633,7 @@ def get_chunk(self, size=None):
631633
size = self.chunksize
632634
return self.read(nrows=size)
633635

636+
634637
def _is_index_col(col):
635638
return col is not None and col is not False
636639

@@ -1174,6 +1177,7 @@ def TextParser(*args, **kwds):
11741177
kwds['engine'] = 'python'
11751178
return TextFileReader(*args, **kwds)
11761179

1180+
11771181
# delimiter=None, dialect=None, names=None, header=0,
11781182
# index_col=None,
11791183
# na_values=None,
@@ -1653,8 +1657,8 @@ def _rows_to_cols(self, content):
16531657
if self._implicit_index:
16541658
col_len += len(self.index_col)
16551659

1656-
if not ((self.skip_footer >= 0)):
1657-
raise AssertionError()
1660+
if self.skip_footer < 0:
1661+
raise ValueError('skip footer cannot be negative')
16581662

16591663
if col_len != zip_len and self.index_col is not False:
16601664
i = 0
@@ -1883,6 +1887,7 @@ def _clean_na_values(na_values, keep_default_na=True):
18831887

18841888
return na_values, na_fvalues
18851889

1890+
18861891
def _clean_index_names(columns, index_col):
18871892
if not _is_index_col(index_col):
18881893
return None, columns, index_col
@@ -1941,6 +1946,7 @@ def _floatify_na_values(na_values):
19411946
pass
19421947
return result
19431948

1949+
19441950
def _stringify_na_values(na_values):
19451951
""" return a stringified and numeric for these values """
19461952
result = []
@@ -1965,6 +1971,7 @@ def _stringify_na_values(na_values):
19651971
pass
19661972
return set(result)
19671973

1974+
19681975
def _get_na_values(col, na_values, na_fvalues):
19691976
if isinstance(na_values, dict):
19701977
if col in na_values:
@@ -2014,15 +2021,17 @@ def __init__(self, f, colspecs, filler, thousands=None, encoding=None):
20142021
encoding = get_option('display.encoding')
20152022
self.encoding = encoding
20162023

2017-
if not ( isinstance(colspecs, (tuple, list))):
2018-
raise AssertionError()
2024+
if not isinstance(colspecs, (tuple, list)):
2025+
raise TypeError("column specifications must be a list or tuple, "
2026+
"input was a %r" % type(colspecs).__name__)
20192027

20202028
for colspec in colspecs:
2021-
if not ( isinstance(colspec, (tuple, list)) and
2022-
len(colspec) == 2 and
2023-
isinstance(colspec[0], int) and
2024-
isinstance(colspec[1], int) ):
2025-
raise AssertionError()
2029+
if not (isinstance(colspec, (tuple, list)) and
2030+
len(colspec) == 2 and
2031+
isinstance(colspec[0], int) and
2032+
isinstance(colspec[1], int)):
2033+
raise TypeError('Each column specification must be '
2034+
'2 element tuple or list of integers')
20262035

20272036
def next(self):
20282037
line = next(self.f)

pandas/io/tests/test_data.py

+10-12
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,13 @@
1616
from numpy.testing import assert_array_equal
1717

1818

19+
def _skip_if_no_lxml():
20+
try:
21+
import lxml
22+
except ImportError:
23+
raise nose.SkipTest("no lxml")
24+
25+
1926
def assert_n_failed_equals_n_null_columns(wngs, obj, cls=SymbolWarning):
2027
all_nan_cols = pd.Series(dict((k, pd.isnull(v).all()) for k, v in
2128
compat.iteritems(obj)))
@@ -88,10 +95,7 @@ def test_get_multi2(self):
8895
class TestYahoo(unittest.TestCase):
8996
@classmethod
9097
def setUpClass(cls):
91-
try:
92-
import lxml
93-
except ImportError:
94-
raise nose.SkipTest
98+
_skip_if_no_lxml()
9599

96100
@network
97101
def test_yahoo(self):
@@ -210,10 +214,7 @@ def test_get_date_ret_index(self):
210214
class TestYahooOptions(unittest.TestCase):
211215
@classmethod
212216
def setUpClass(cls):
213-
try:
214-
import lxml
215-
except ImportError:
216-
raise nose.SkipTest
217+
_skip_if_no_lxml()
217218

218219
# aapl has monthlies
219220
cls.aapl = web.Options('aapl', 'yahoo')
@@ -272,10 +273,7 @@ def test_get_put_data(self):
272273
class TestOptionsWarnings(unittest.TestCase):
273274
@classmethod
274275
def setUpClass(cls):
275-
try:
276-
import lxml
277-
except ImportError:
278-
raise nose.SkipTest
276+
_skip_if_no_lxml()
279277

280278
with assert_produces_warning(FutureWarning):
281279
cls.aapl = web.Options('aapl')

pandas/io/tests/test_ga.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from pandas.io.auth import AuthenticationConfigError, reset_token_store
1515
from pandas.io import auth
1616
except ImportError:
17-
raise nose.SkipTest
17+
raise nose.SkipTest("need httplib2 and auth libs")
1818

1919
class TestGoogle(unittest.TestCase):
2020

@@ -68,7 +68,7 @@ def test_getdata(self):
6868
assert_frame_equal(df, df2)
6969

7070
except AuthenticationConfigError:
71-
raise nose.SkipTest
71+
raise nose.SkipTest("authentication error")
7272

7373
@slow
7474
@with_connectivity_check("http://www.google.com")
@@ -96,7 +96,7 @@ def test_iterator(self):
9696
assert (df2.index > df1.index).all()
9797

9898
except AuthenticationConfigError:
99-
raise nose.SkipTest
99+
raise nose.SkipTest("authentication error")
100100

101101
@slow
102102
@with_connectivity_check("http://www.google.com")
@@ -150,7 +150,8 @@ def test_segment(self):
150150
assert 'pageviewsPerVisit' in df
151151

152152
except AuthenticationConfigError:
153-
raise nose.SkipTest
153+
raise nose.SkipTest("authentication error")
154+
154155

155156
if __name__ == '__main__':
156157
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],

pandas/io/tests/test_json/test_pandas.py

+6-12
Original file line numberDiff line numberDiff line change
@@ -567,17 +567,11 @@ def test_round_trip_exception_(self):
567567
assert_frame_equal(result.reindex(index=df.index,columns=df.columns),df)
568568

569569
@network
570-
@slow
571570
def test_url(self):
572-
try:
573-
574-
url = 'https://api.github.com/repos/pydata/pandas/issues?per_page=5'
575-
result = read_json(url,convert_dates=True)
576-
for c in ['created_at','closed_at','updated_at']:
577-
self.assert_(result[c].dtype == 'datetime64[ns]')
578-
579-
url = 'http://search.twitter.com/search.json?q=pandas%20python'
580-
result = read_json(url)
571+
url = 'https://api.github.com/repos/pydata/pandas/issues?per_page=5'
572+
result = read_json(url,convert_dates=True)
573+
for c in ['created_at','closed_at','updated_at']:
574+
self.assert_(result[c].dtype == 'datetime64[ns]')
581575

582-
except URLError:
583-
raise nose.SkipTest
576+
url = 'http://search.twitter.com/search.json?q=pandas%20python'
577+
result = read_json(url)

pandas/io/tests/test_json/test_ujson.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
def _skip_if_python_ver(skip_major, skip_minor=None):
3030
major, minor = sys.version_info[:2]
3131
if major == skip_major and (skip_minor is None or minor == skip_minor):
32-
raise nose.SkipTest
32+
raise nose.SkipTest("skipping Python version %d.%d" % (major, minor))
3333

3434
json_unicode = (json.dumps if sys.version_info[0] >= 3
3535
else partial(json.dumps, encoding="utf-8"))
@@ -363,7 +363,8 @@ def test_nat(self):
363363
def test_npy_nat(self):
364364
from distutils.version import LooseVersion
365365
if LooseVersion(np.__version__) < '1.7.0':
366-
raise nose.SkipTest
366+
raise nose.SkipTest("numpy version < 1.7.0, is "
367+
"{0}".format(np.__version__))
367368

368369
input = np.datetime64('NaT')
369370
assert ujson.encode(input) == 'null', "Expected null"

0 commit comments

Comments
 (0)