Skip to content
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

STY: use pytest.raises context manager (tests/test_*) #25452

Merged
merged 4 commits into from
Feb 28, 2019
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
25 changes: 18 additions & 7 deletions pandas/tests/test_algos.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

from pandas._libs import (
algos as libalgos, groupby as libgroupby, hashtable as ht)
from pandas.compat import lrange, range
from pandas.compat import PY2, lrange, range
from pandas.compat.numpy import np_array_datetime64_compat
import pandas.util._test_decorators as td

Expand Down Expand Up @@ -224,11 +224,16 @@ def test_factorize_tuple_list(self, data, expected_label, expected_level):
dtype=object)
tm.assert_numpy_array_equal(result[1], expected_level_array)

@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
def test_complex_sorting(self):
# gh 12666 - check no segfault
x17 = np.array([complex(i) for i in range(17)], dtype=object)

pytest.raises(TypeError, algos.factorize, x17[::-1], sort=True)
msg = ("'<' not supported between instances of 'complex' and"
r" 'complex'|"
r"unorderable types: complex\(\) > complex\(\)")
with pytest.raises(TypeError, match=msg):
algos.factorize(x17[::-1], sort=True)

def test_float64_factorize(self, writable):
data = np.array([1.0, 1e8, 1.0, 1e-8, 1e8, 1.0], dtype=np.float64)
Expand Down Expand Up @@ -589,9 +594,14 @@ class TestIsin(object):

def test_invalid(self):

pytest.raises(TypeError, lambda: algos.isin(1, 1))
pytest.raises(TypeError, lambda: algos.isin(1, [1]))
pytest.raises(TypeError, lambda: algos.isin([1], 1))
msg = (r"only list-like objects are allowed to be passed to isin\(\),"
r" you passed a \[int\]")
with pytest.raises(TypeError, match=msg):
algos.isin(1, 1)
with pytest.raises(TypeError, match=msg):
algos.isin(1, [1])
with pytest.raises(TypeError, match=msg):
algos.isin([1], 1)

def test_basic(self):

Expand Down Expand Up @@ -819,8 +829,9 @@ def test_value_counts_dtypes(self):
result = algos.value_counts(Series([1, 1., '1'])) # object
assert len(result) == 2

pytest.raises(TypeError, lambda s: algos.value_counts(s, bins=1),
['1', 1])
msg = "bins argument only works with numeric data"
with pytest.raises(TypeError, match=msg):
algos.value_counts(['1', 1], bins=1)

def test_value_counts_nat(self):
td = Series([np.timedelta64(10000), pd.NaT], dtype='timedelta64[ns]')
Expand Down
104 changes: 69 additions & 35 deletions pandas/tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@

import pytest

from pandas.compat import PY2

import pandas as pd
from pandas.core.config import OptionError


class TestConfig(object):
Expand Down Expand Up @@ -48,26 +51,35 @@ def test_is_one_of_factory(self):

v(12)
v(None)
pytest.raises(ValueError, v, 1.1)
msg = r"Value must be one of None\|12"
with pytest.raises(ValueError, match=msg):
v(1.1)

def test_register_option(self):
self.cf.register_option('a', 1, 'doc')

# can't register an already registered option
pytest.raises(KeyError, self.cf.register_option, 'a', 1, 'doc')
msg = "Option 'a' has already been registered"
with pytest.raises(OptionError, match=msg):
self.cf.register_option('a', 1, 'doc')

# can't register an already registered option
pytest.raises(KeyError, self.cf.register_option, 'a.b.c.d1', 1,
'doc')
pytest.raises(KeyError, self.cf.register_option, 'a.b.c.d2', 1,
'doc')
msg = "Path prefix to option 'a' is already an option"
with pytest.raises(OptionError, match=msg):
self.cf.register_option('a.b.c.d1', 1, 'doc')
with pytest.raises(OptionError, match=msg):
self.cf.register_option('a.b.c.d2', 1, 'doc')

# no python keywords
pytest.raises(ValueError, self.cf.register_option, 'for', 0)
pytest.raises(ValueError, self.cf.register_option, 'a.for.b', 0)
msg = "for is a python keyword"
with pytest.raises(ValueError, match=msg):
self.cf.register_option('for', 0)
with pytest.raises(ValueError, match=msg):
self.cf.register_option('a.for.b', 0)
# must be valid identifier (ensure attribute access works)
pytest.raises(ValueError, self.cf.register_option,
'Oh my Goddess!', 0)
msg = "oh my goddess! is not a valid identifier"
with pytest.raises(ValueError, match=msg):
self.cf.register_option('Oh my Goddess!', 0)

# we can register options several levels deep
# without predefining the intermediate steps
Expand All @@ -90,7 +102,9 @@ def test_describe_option(self):
self.cf.register_option('l', "foo")

# non-existent keys raise KeyError
pytest.raises(KeyError, self.cf.describe_option, 'no.such.key')
msg = r"No such keys\(s\)"
with pytest.raises(OptionError, match=msg):
self.cf.describe_option('no.such.key')

# we can get the description for any key we registered
assert 'doc' in self.cf.describe_option('a', _print_desc=False)
Expand Down Expand Up @@ -122,7 +136,9 @@ def test_case_insensitive(self):
assert self.cf.get_option('kAnBaN') == 2

# gets of non-existent keys fail
pytest.raises(KeyError, self.cf.get_option, 'no_such_option')
msg = r"No such keys\(s\): 'no_such_option'"
with pytest.raises(OptionError, match=msg):
self.cf.get_option('no_such_option')
self.cf.deprecate_option('KanBan')

assert self.cf._is_deprecated('kAnBaN')
Expand All @@ -138,7 +154,9 @@ def test_get_option(self):
assert self.cf.get_option('b.b') is None

# gets of non-existent keys fail
pytest.raises(KeyError, self.cf.get_option, 'no_such_option')
msg = r"No such keys\(s\): 'no_such_option'"
with pytest.raises(OptionError, match=msg):
self.cf.get_option('no_such_option')

def test_set_option(self):
self.cf.register_option('a', 1, 'doc')
Expand All @@ -157,16 +175,24 @@ def test_set_option(self):
assert self.cf.get_option('b.c') == 'wurld'
assert self.cf.get_option('b.b') == 1.1

pytest.raises(KeyError, self.cf.set_option, 'no.such.key', None)
msg = r"No such keys\(s\): 'no.such.key'"
with pytest.raises(OptionError, match=msg):
self.cf.set_option('no.such.key', None)

def test_set_option_empty_args(self):
pytest.raises(ValueError, self.cf.set_option)
msg = "Must provide an even number of non-keyword arguments"
with pytest.raises(ValueError, match=msg):
self.cf.set_option()

def test_set_option_uneven_args(self):
pytest.raises(ValueError, self.cf.set_option, 'a.b', 2, 'b.c')
msg = "Must provide an even number of non-keyword arguments"
with pytest.raises(ValueError, match=msg):
self.cf.set_option('a.b', 2, 'b.c')

def test_set_option_invalid_single_argument_type(self):
pytest.raises(ValueError, self.cf.set_option, 2)
msg = "Must provide an even number of non-keyword arguments"
with pytest.raises(ValueError, match=msg):
self.cf.set_option(2)

def test_set_option_multiple(self):
self.cf.register_option('a', 1, 'doc')
Expand All @@ -183,27 +209,36 @@ def test_set_option_multiple(self):
assert self.cf.get_option('b.c') is None
assert self.cf.get_option('b.b') == 10.0

@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
def test_validation(self):
self.cf.register_option('a', 1, 'doc', validator=self.cf.is_int)
self.cf.register_option('b.c', 'hullo', 'doc2',
validator=self.cf.is_text)
pytest.raises(ValueError, self.cf.register_option, 'a.b.c.d2',
'NO', 'doc', validator=self.cf.is_int)
msg = "Value must have type '<class 'int'>'"
with pytest.raises(ValueError, match=msg):
self.cf.register_option(
'a.b.c.d2', 'NO', 'doc', validator=self.cf.is_int)

self.cf.set_option('a', 2) # int is_int
self.cf.set_option('b.c', 'wurld') # str is_str

pytest.raises(
ValueError, self.cf.set_option, 'a', None) # None not is_int
pytest.raises(ValueError, self.cf.set_option, 'a', 'ab')
pytest.raises(ValueError, self.cf.set_option, 'b.c', 1)
# None not is_int
with pytest.raises(ValueError, match=msg):
self.cf.set_option('a', None)
with pytest.raises(ValueError, match=msg):
self.cf.set_option('a', 'ab')

msg = r"Value must be an instance of <class 'str'>\|<class 'bytes'>"
with pytest.raises(ValueError, match=msg):
self.cf.set_option('b.c', 1)

validator = self.cf.is_one_of_factory([None, self.cf.is_callable])
self.cf.register_option('b', lambda: None, 'doc',
validator=validator)
self.cf.set_option('b', '%.1f'.format) # Formatter is callable
self.cf.set_option('b', None) # Formatter is none (default)
pytest.raises(ValueError, self.cf.set_option, 'b', '%.1f')
with pytest.raises(ValueError, match="Value must be a callable"):
self.cf.set_option('b', '%.1f')

def test_reset_option(self):
self.cf.register_option('a', 1, 'doc', validator=self.cf.is_int)
Expand Down Expand Up @@ -267,8 +302,9 @@ def test_deprecate_option(self):
assert 'eprecated' in str(w[-1]) # we get the default message
assert 'nifty_ver' in str(w[-1]) # with the removal_ver quoted

pytest.raises(
KeyError, self.cf.deprecate_option, 'a') # can't depr. twice
msg = "Option 'a' has already been defined as deprecated"
with pytest.raises(OptionError, match=msg):
self.cf.deprecate_option('a')

self.cf.deprecate_option('b.c', 'zounds!')
with warnings.catch_warnings(record=True) as w:
Expand Down Expand Up @@ -374,12 +410,6 @@ def eq(val):
def test_attribute_access(self):
holder = []

def f():
options.b = 1

def f2():
options.display = 1

def f3(key):
holder.append(True)

Expand All @@ -397,8 +427,11 @@ def f3(key):
self.cf.reset_option("a")
assert options.a == self.cf.get_option("a", 0)

pytest.raises(KeyError, f)
pytest.raises(KeyError, f2)
msg = "You can only set the value of existing options"
with pytest.raises(OptionError, match=msg):
options.b = 1
with pytest.raises(OptionError, match=msg):
options.display = 1

# make sure callback kicks when using this form of setting
options.c = 1
Expand Down Expand Up @@ -429,5 +462,6 @@ def test_option_context_scope(self):
def test_dictwrapper_getattr(self):
options = self.cf.options
# GH 19789
pytest.raises(self.cf.OptionError, getattr, options, 'bananas')
with pytest.raises(OptionError, match="No such option"):
options.bananas
assert not hasattr(options, 'bananas')
10 changes: 7 additions & 3 deletions pandas/tests/test_multilevel.py
Original file line number Diff line number Diff line change
Expand Up @@ -886,8 +886,11 @@ def test_count(self):
tm.assert_series_equal(result, expect, check_names=False)
assert result.index.name == 'a'

pytest.raises(KeyError, series.count, 'x')
pytest.raises(KeyError, frame.count, level='x')
msg = "Level x not found"
with pytest.raises(KeyError, match=msg):
series.count('x')
with pytest.raises(KeyError, match=msg):
frame.count(level='x')

@pytest.mark.parametrize('op', AGG_FUNCTIONS)
@pytest.mark.parametrize('level', [0, 1])
Expand Down Expand Up @@ -1119,7 +1122,8 @@ def test_level_with_tuples(self):
tm.assert_series_equal(result, expected)
tm.assert_series_equal(result2, expected)

pytest.raises(KeyError, series.__getitem__, (('foo', 'bar', 0), 2))
with pytest.raises(KeyError, match=r"^\(\('foo', 'bar', 0\), 2\)$"):
series[('foo', 'bar', 0), 2]

result = frame.loc[('foo', 'bar', 0)]
result2 = frame.xs(('foo', 'bar', 0))
Expand Down
18 changes: 14 additions & 4 deletions pandas/tests/test_nanops.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import numpy as np
import pytest

from pandas.compat import PY2
from pandas.compat.numpy import _np_version_under1p13
import pandas.util._test_decorators as td

Expand Down Expand Up @@ -728,6 +729,7 @@ def test_numeric_values(self):
# Test complex
assert nanops._ensure_numeric(1 + 2j) == 1 + 2j

@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
def test_ndarray(self):
# Test numeric ndarray
values = np.array([1, 2, 3])
Expand All @@ -743,17 +745,25 @@ def test_ndarray(self):

# Test non-convertible string ndarray
s_values = np.array(['foo', 'bar', 'baz'], dtype=object)
pytest.raises(ValueError, lambda: nanops._ensure_numeric(s_values))
msg = r"could not convert string to float: '(foo|baz)'"
with pytest.raises(ValueError, match=msg):
nanops._ensure_numeric(s_values)

def test_convertable_values(self):
assert np.allclose(nanops._ensure_numeric('1'), 1.0)
assert np.allclose(nanops._ensure_numeric('1.1'), 1.1)
assert np.allclose(nanops._ensure_numeric('1+1j'), 1 + 1j)

def test_non_convertable_values(self):
pytest.raises(TypeError, lambda: nanops._ensure_numeric('foo'))
pytest.raises(TypeError, lambda: nanops._ensure_numeric({}))
pytest.raises(TypeError, lambda: nanops._ensure_numeric([]))
msg = "Could not convert foo to numeric"
with pytest.raises(TypeError, match=msg):
nanops._ensure_numeric('foo')
msg = "Could not convert {} to numeric"
with pytest.raises(TypeError, match=msg):
nanops._ensure_numeric({})
msg = r"Could not convert \[\] to numeric"
with pytest.raises(TypeError, match=msg):
nanops._ensure_numeric([])


class TestNanvarFixedValues(object):
Expand Down
12 changes: 10 additions & 2 deletions pandas/tests/test_sorting.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from numpy import nan
import pytest

from pandas.compat import PY2

from pandas import DataFrame, MultiIndex, Series, compat, concat, merge
from pandas.core import common as com
from pandas.core.sorting import (
Expand Down Expand Up @@ -403,15 +405,21 @@ def test_mixed_integer_from_list(self):
expected = np.array([0, 0, 1, 'a', 'b', 'b'], dtype=object)
tm.assert_numpy_array_equal(result, expected)

@pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
def test_unsortable(self):
# GH 13714
arr = np.array([1, 2, datetime.now(), 0, 3], dtype=object)
msg = ("'<' not supported between instances of 'datetime.datetime'"
r" and 'int'|"
r"unorderable types: int\(\) > datetime.datetime\(\)")
if compat.PY2:
# RuntimeWarning: tp_compare didn't return -1 or -2 for exception
with warnings.catch_warnings():
pytest.raises(TypeError, safe_sort, arr)
with pytest.raises(TypeError, match=msg):
safe_sort(arr)
else:
pytest.raises(TypeError, safe_sort, arr)
with pytest.raises(TypeError, match=msg):
safe_sort(arr)

def test_exceptions(self):
with pytest.raises(TypeError,
Expand Down
Loading