2020-02-23 06:32:55 +08:00
|
|
|
import re
|
2016-11-09 07:34:45 +08:00
|
|
|
import sys
|
|
|
|
|
2018-10-25 15:01:29 +08:00
|
|
|
import pytest
|
|
|
|
from _pytest.outcomes import Failed
|
2020-12-10 13:47:58 +08:00
|
|
|
from _pytest.pytester import Pytester
|
2018-10-25 15:01:29 +08:00
|
|
|
|
2012-11-02 23:04:57 +08:00
|
|
|
|
2019-06-03 06:32:00 +08:00
|
|
|
class TestRaises:
|
2020-05-01 19:40:17 +08:00
|
|
|
def test_check_callable(self) -> None:
|
2019-06-30 22:40:24 +08:00
|
|
|
with pytest.raises(TypeError, match=r".* must be callable"):
|
2020-07-10 14:44:14 +08:00
|
|
|
pytest.raises(RuntimeError, "int('qwe')") # type: ignore[call-overload]
|
2019-06-30 22:40:24 +08:00
|
|
|
|
2012-11-02 23:04:57 +08:00
|
|
|
def test_raises(self):
|
2019-06-30 22:40:24 +08:00
|
|
|
excinfo = pytest.raises(ValueError, int, "qwe")
|
|
|
|
assert "invalid literal" in str(excinfo.value)
|
2012-11-02 23:04:57 +08:00
|
|
|
|
|
|
|
def test_raises_function(self):
|
2019-06-30 22:40:24 +08:00
|
|
|
excinfo = pytest.raises(ValueError, int, "hello")
|
|
|
|
assert "invalid literal" in str(excinfo.value)
|
2012-11-02 23:04:57 +08:00
|
|
|
|
2020-05-01 19:40:17 +08:00
|
|
|
def test_raises_callable_no_exception(self) -> None:
|
2019-06-03 06:32:00 +08:00
|
|
|
class A:
|
2012-11-02 23:04:57 +08:00
|
|
|
def __call__(self):
|
|
|
|
pass
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2012-11-02 23:04:57 +08:00
|
|
|
try:
|
|
|
|
pytest.raises(ValueError, A())
|
2020-05-01 19:40:17 +08:00
|
|
|
except pytest.fail.Exception:
|
2012-11-02 23:04:57 +08:00
|
|
|
pass
|
|
|
|
|
2020-05-01 19:40:17 +08:00
|
|
|
def test_raises_falsey_type_error(self) -> None:
|
2018-12-13 06:58:48 +08:00
|
|
|
with pytest.raises(TypeError):
|
2020-07-10 14:44:14 +08:00
|
|
|
with pytest.raises(AssertionError, match=0): # type: ignore[call-overload]
|
2018-12-13 06:58:48 +08:00
|
|
|
raise AssertionError("ohai")
|
|
|
|
|
2018-11-23 03:43:58 +08:00
|
|
|
def test_raises_repr_inflight(self):
|
2018-11-23 06:24:46 +08:00
|
|
|
"""Ensure repr() on an exception info inside a pytest.raises with block works (#4386)"""
|
|
|
|
|
|
|
|
class E(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
with pytest.raises(E) as excinfo:
|
2018-11-23 03:43:58 +08:00
|
|
|
# this test prints the inflight uninitialized object
|
|
|
|
# using repr and str as well as pprint to demonstrate
|
|
|
|
# it works
|
|
|
|
print(str(excinfo))
|
|
|
|
print(repr(excinfo))
|
|
|
|
import pprint
|
|
|
|
|
|
|
|
pprint.pprint(excinfo)
|
2018-11-23 06:24:46 +08:00
|
|
|
raise E()
|
2018-11-23 03:43:58 +08:00
|
|
|
|
2020-12-10 13:47:58 +08:00
|
|
|
def test_raises_as_contextmanager(self, pytester: Pytester) -> None:
|
|
|
|
pytester.makepyfile(
|
2018-05-23 22:48:46 +08:00
|
|
|
"""
|
2018-07-08 23:35:53 +08:00
|
|
|
import pytest
|
2015-11-27 22:43:01 +08:00
|
|
|
import _pytest._code
|
2012-11-02 23:04:57 +08:00
|
|
|
|
|
|
|
def test_simple():
|
|
|
|
with pytest.raises(ZeroDivisionError) as excinfo:
|
2015-11-27 22:43:01 +08:00
|
|
|
assert isinstance(excinfo, _pytest._code.ExceptionInfo)
|
2012-11-02 23:04:57 +08:00
|
|
|
1/0
|
2018-11-22 16:15:14 +08:00
|
|
|
print(excinfo)
|
2012-11-02 23:04:57 +08:00
|
|
|
assert excinfo.type == ZeroDivisionError
|
2015-06-19 08:04:47 +08:00
|
|
|
assert isinstance(excinfo.value, ZeroDivisionError)
|
2012-11-02 23:04:57 +08:00
|
|
|
|
|
|
|
def test_noraise():
|
|
|
|
with pytest.raises(pytest.raises.Exception):
|
|
|
|
with pytest.raises(ValueError):
|
|
|
|
int()
|
|
|
|
|
|
|
|
def test_raise_wrong_exception_passes_by():
|
|
|
|
with pytest.raises(ZeroDivisionError):
|
|
|
|
with pytest.raises(ValueError):
|
|
|
|
1/0
|
2018-05-23 22:48:46 +08:00
|
|
|
"""
|
|
|
|
)
|
2020-12-10 13:47:58 +08:00
|
|
|
result = pytester.runpytest()
|
2018-05-23 22:48:46 +08:00
|
|
|
result.stdout.fnmatch_lines(["*3 passed*"])
|
2012-11-02 23:04:57 +08:00
|
|
|
|
2020-12-10 13:47:58 +08:00
|
|
|
def test_does_not_raise(self, pytester: Pytester) -> None:
|
|
|
|
pytester.makepyfile(
|
2019-01-25 05:53:14 +08:00
|
|
|
"""
|
2019-01-28 00:10:11 +08:00
|
|
|
from contextlib import contextmanager
|
2019-01-25 05:53:14 +08:00
|
|
|
import pytest
|
|
|
|
|
2019-01-28 00:10:11 +08:00
|
|
|
@contextmanager
|
|
|
|
def does_not_raise():
|
|
|
|
yield
|
|
|
|
|
2019-01-25 05:53:14 +08:00
|
|
|
@pytest.mark.parametrize('example_input,expectation', [
|
2019-01-28 00:10:11 +08:00
|
|
|
(3, does_not_raise()),
|
|
|
|
(2, does_not_raise()),
|
|
|
|
(1, does_not_raise()),
|
2019-01-25 05:53:14 +08:00
|
|
|
(0, pytest.raises(ZeroDivisionError)),
|
|
|
|
])
|
|
|
|
def test_division(example_input, expectation):
|
|
|
|
'''Test how much I know division.'''
|
|
|
|
with expectation:
|
|
|
|
assert (6 / example_input) is not None
|
|
|
|
"""
|
|
|
|
)
|
2020-12-10 13:47:58 +08:00
|
|
|
result = pytester.runpytest()
|
2019-01-25 05:53:14 +08:00
|
|
|
result.stdout.fnmatch_lines(["*4 passed*"])
|
|
|
|
|
2020-12-10 13:47:58 +08:00
|
|
|
def test_does_not_raise_does_raise(self, pytester: Pytester) -> None:
|
|
|
|
pytester.makepyfile(
|
2019-01-25 05:53:14 +08:00
|
|
|
"""
|
2019-01-28 00:10:11 +08:00
|
|
|
from contextlib import contextmanager
|
2019-01-25 05:53:14 +08:00
|
|
|
import pytest
|
|
|
|
|
2019-01-28 00:10:11 +08:00
|
|
|
@contextmanager
|
|
|
|
def does_not_raise():
|
|
|
|
yield
|
|
|
|
|
2019-01-25 05:53:14 +08:00
|
|
|
@pytest.mark.parametrize('example_input,expectation', [
|
2019-01-28 00:10:11 +08:00
|
|
|
(0, does_not_raise()),
|
2019-01-25 05:53:14 +08:00
|
|
|
(1, pytest.raises(ZeroDivisionError)),
|
|
|
|
])
|
|
|
|
def test_division(example_input, expectation):
|
|
|
|
'''Test how much I know division.'''
|
|
|
|
with expectation:
|
|
|
|
assert (6 / example_input) is not None
|
|
|
|
"""
|
|
|
|
)
|
2020-12-10 13:47:58 +08:00
|
|
|
result = pytester.runpytest()
|
2019-01-25 05:53:14 +08:00
|
|
|
result.stdout.fnmatch_lines(["*2 failed*"])
|
|
|
|
|
2020-05-01 19:40:17 +08:00
|
|
|
def test_noclass(self) -> None:
|
2014-04-15 06:09:10 +08:00
|
|
|
with pytest.raises(TypeError):
|
2020-07-10 14:44:14 +08:00
|
|
|
pytest.raises("wrong", lambda: None) # type: ignore[call-overload]
|
2014-04-15 06:09:10 +08:00
|
|
|
|
2020-05-01 19:40:17 +08:00
|
|
|
def test_invalid_arguments_to_raises(self) -> None:
|
2018-05-23 22:48:46 +08:00
|
|
|
with pytest.raises(TypeError, match="unknown"):
|
2020-07-10 14:44:14 +08:00
|
|
|
with pytest.raises(TypeError, unknown="bogus"): # type: ignore[call-overload]
|
2018-03-28 10:57:15 +08:00
|
|
|
raise ValueError()
|
|
|
|
|
2014-04-15 06:09:10 +08:00
|
|
|
def test_tuple(self):
|
|
|
|
with pytest.raises((KeyError, ValueError)):
|
2018-05-23 22:48:46 +08:00
|
|
|
raise KeyError("oops")
|
2016-02-03 17:01:03 +08:00
|
|
|
|
2020-05-01 19:40:17 +08:00
|
|
|
def test_no_raise_message(self) -> None:
|
2016-02-03 17:01:03 +08:00
|
|
|
try:
|
2018-05-23 22:48:46 +08:00
|
|
|
pytest.raises(ValueError, int, "0")
|
2020-05-01 19:40:17 +08:00
|
|
|
except pytest.fail.Exception as e:
|
2021-04-14 17:49:09 +08:00
|
|
|
assert e.msg == f"DID NOT RAISE {repr(ValueError)}"
|
2016-06-20 02:24:47 +08:00
|
|
|
else:
|
|
|
|
assert False, "Expected pytest.raises.Exception"
|
|
|
|
|
2016-06-17 01:15:32 +08:00
|
|
|
try:
|
|
|
|
with pytest.raises(ValueError):
|
|
|
|
pass
|
2020-05-01 19:40:17 +08:00
|
|
|
except pytest.fail.Exception as e:
|
2021-04-14 17:49:09 +08:00
|
|
|
assert e.msg == f"DID NOT RAISE {repr(ValueError)}"
|
2016-06-20 02:24:47 +08:00
|
|
|
else:
|
|
|
|
assert False, "Expected pytest.raises.Exception"
|
2016-06-17 01:15:32 +08:00
|
|
|
|
2020-02-23 06:32:55 +08:00
|
|
|
@pytest.mark.parametrize("method", ["function", "function_match", "with"])
|
2016-11-09 07:34:45 +08:00
|
|
|
def test_raises_cyclic_reference(self, method):
|
2020-07-18 17:35:13 +08:00
|
|
|
"""Ensure pytest.raises does not leave a reference cycle (#1965)."""
|
2019-08-20 16:43:29 +08:00
|
|
|
import gc
|
2016-10-18 07:22:53 +08:00
|
|
|
|
2019-06-03 06:32:00 +08:00
|
|
|
class T:
|
2016-10-18 07:22:53 +08:00
|
|
|
def __call__(self):
|
|
|
|
raise ValueError
|
|
|
|
|
|
|
|
t = T()
|
2019-08-20 16:43:29 +08:00
|
|
|
refcount = len(gc.get_referrers(t))
|
2019-08-20 16:19:25 +08:00
|
|
|
|
2018-05-23 22:48:46 +08:00
|
|
|
if method == "function":
|
2016-10-18 07:22:53 +08:00
|
|
|
pytest.raises(ValueError, t)
|
2020-02-23 06:32:55 +08:00
|
|
|
elif method == "function_match":
|
|
|
|
pytest.raises(ValueError, t).match("^$")
|
2016-10-18 07:22:53 +08:00
|
|
|
else:
|
|
|
|
with pytest.raises(ValueError):
|
|
|
|
t()
|
|
|
|
|
2016-11-09 07:34:45 +08:00
|
|
|
# ensure both forms of pytest.raises don't leave exceptions in sys.exc_info()
|
|
|
|
assert sys.exc_info() == (None, None, None)
|
|
|
|
|
2019-08-20 16:43:29 +08:00
|
|
|
assert refcount == len(gc.get_referrers(t))
|
2016-11-09 07:34:45 +08:00
|
|
|
|
2020-02-23 06:32:55 +08:00
|
|
|
def test_raises_match(self) -> None:
|
2017-02-01 20:37:13 +08:00
|
|
|
msg = r"with base \d+"
|
|
|
|
with pytest.raises(ValueError, match=msg):
|
2018-05-23 22:48:46 +08:00
|
|
|
int("asdf")
|
2017-02-01 20:37:13 +08:00
|
|
|
|
|
|
|
msg = "with base 10"
|
|
|
|
with pytest.raises(ValueError, match=msg):
|
2018-05-23 22:48:46 +08:00
|
|
|
int("asdf")
|
2017-02-01 20:37:13 +08:00
|
|
|
|
|
|
|
msg = "with base 16"
|
2020-07-16 03:26:47 +08:00
|
|
|
expr = "Regex pattern {!r} does not match \"invalid literal for int() with base 10: 'asdf'\".".format(
|
2018-05-23 22:48:46 +08:00
|
|
|
msg
|
|
|
|
)
|
2020-02-23 06:32:55 +08:00
|
|
|
with pytest.raises(AssertionError, match=re.escape(expr)):
|
2017-02-01 20:37:13 +08:00
|
|
|
with pytest.raises(ValueError, match=msg):
|
2018-05-23 22:48:46 +08:00
|
|
|
int("asdf", base=10)
|
2018-02-15 19:11:56 +08:00
|
|
|
|
2020-02-23 06:32:55 +08:00
|
|
|
# "match" without context manager.
|
|
|
|
pytest.raises(ValueError, int, "asdf").match("invalid literal")
|
|
|
|
with pytest.raises(AssertionError) as excinfo:
|
|
|
|
pytest.raises(ValueError, int, "asdf").match(msg)
|
|
|
|
assert str(excinfo.value) == expr
|
|
|
|
|
|
|
|
pytest.raises(TypeError, int, match="invalid")
|
|
|
|
|
|
|
|
def tfunc(match):
|
2020-10-03 04:16:22 +08:00
|
|
|
raise ValueError(f"match={match}")
|
2020-02-23 06:32:55 +08:00
|
|
|
|
|
|
|
pytest.raises(ValueError, tfunc, match="asdf").match("match=asdf")
|
|
|
|
pytest.raises(ValueError, tfunc, match="").match("match=")
|
|
|
|
|
2019-07-04 20:55:26 +08:00
|
|
|
def test_match_failure_string_quoting(self):
|
|
|
|
with pytest.raises(AssertionError) as excinfo:
|
|
|
|
with pytest.raises(AssertionError, match="'foo"):
|
|
|
|
raise AssertionError("'bar")
|
2019-11-17 01:53:29 +08:00
|
|
|
(msg,) = excinfo.value.args
|
2020-07-16 03:26:47 +08:00
|
|
|
assert msg == 'Regex pattern "\'foo" does not match "\'bar".'
|
|
|
|
|
|
|
|
def test_match_failure_exact_string_message(self):
|
|
|
|
message = "Oh here is a message with (42) numbers in parameters"
|
|
|
|
with pytest.raises(AssertionError) as excinfo:
|
|
|
|
with pytest.raises(AssertionError, match=message):
|
|
|
|
raise AssertionError(message)
|
|
|
|
(msg,) = excinfo.value.args
|
|
|
|
assert msg == (
|
|
|
|
"Regex pattern 'Oh here is a message with (42) numbers in "
|
|
|
|
"parameters' does not match 'Oh here is a message with (42) "
|
|
|
|
"numbers in parameters'. Did you mean to `re.escape()` the regex?"
|
|
|
|
)
|
2019-07-04 20:55:26 +08:00
|
|
|
|
2018-02-15 19:11:56 +08:00
|
|
|
def test_raises_match_wrong_type(self):
|
|
|
|
"""Raising an exception with the wrong type and match= given.
|
|
|
|
|
|
|
|
pytest should throw the unexpected exception - the pattern match is not
|
|
|
|
really relevant if we got a different exception.
|
|
|
|
"""
|
|
|
|
with pytest.raises(ValueError):
|
2018-05-23 22:48:46 +08:00
|
|
|
with pytest.raises(IndexError, match="nomatch"):
|
|
|
|
int("asdf")
|
2018-04-06 20:16:12 +08:00
|
|
|
|
|
|
|
def test_raises_exception_looks_iterable(self):
|
2019-06-07 00:13:02 +08:00
|
|
|
class Meta(type):
|
2018-04-06 20:16:12 +08:00
|
|
|
def __getitem__(self, item):
|
2018-05-23 22:48:46 +08:00
|
|
|
return 1 / 0
|
2018-04-06 20:16:12 +08:00
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return 1
|
|
|
|
|
2019-06-03 06:32:00 +08:00
|
|
|
class ClassLooksIterableException(Exception, metaclass=Meta):
|
2018-04-06 20:16:12 +08:00
|
|
|
pass
|
|
|
|
|
2018-05-23 22:48:46 +08:00
|
|
|
with pytest.raises(
|
2018-12-10 13:26:23 +08:00
|
|
|
Failed,
|
|
|
|
match=r"DID NOT RAISE <class 'raises(\..*)*ClassLooksIterableException'>",
|
2018-05-23 22:48:46 +08:00
|
|
|
):
|
2018-04-06 20:16:12 +08:00
|
|
|
pytest.raises(ClassLooksIterableException, lambda: None)
|
2018-11-01 07:54:48 +08:00
|
|
|
|
2020-05-01 19:40:17 +08:00
|
|
|
def test_raises_with_raising_dunder_class(self) -> None:
|
2018-11-01 07:54:48 +08:00
|
|
|
"""Test current behavior with regard to exceptions via __class__ (#4284)."""
|
|
|
|
|
|
|
|
class CrappyClass(Exception):
|
2019-07-08 15:04:19 +08:00
|
|
|
# Type ignored because it's bypassed intentionally.
|
|
|
|
@property # type: ignore
|
2018-11-01 07:54:48 +08:00
|
|
|
def __class__(self):
|
|
|
|
assert False, "via __class__"
|
|
|
|
|
2019-05-28 07:31:52 +08:00
|
|
|
with pytest.raises(AssertionError) as excinfo:
|
2020-07-10 14:44:14 +08:00
|
|
|
with pytest.raises(CrappyClass()): # type: ignore[call-overload]
|
2019-05-28 07:31:52 +08:00
|
|
|
pass
|
|
|
|
assert "via __class__" in excinfo.value.args[0]
|
2019-07-14 16:39:30 +08:00
|
|
|
|
|
|
|
def test_raises_context_manager_with_kwargs(self):
|
|
|
|
with pytest.raises(TypeError) as excinfo:
|
2020-07-10 14:44:14 +08:00
|
|
|
with pytest.raises(Exception, foo="bar"): # type: ignore[call-overload]
|
2019-07-14 16:39:30 +08:00
|
|
|
pass
|
|
|
|
assert "Unexpected keyword arguments" in str(excinfo.value)
|
2020-07-30 22:05:32 +08:00
|
|
|
|
|
|
|
def test_expected_exception_is_not_a_baseexception(self) -> None:
|
|
|
|
with pytest.raises(TypeError) as excinfo:
|
|
|
|
with pytest.raises("hello"): # type: ignore[call-overload]
|
|
|
|
pass # pragma: no cover
|
|
|
|
assert "must be a BaseException type, not str" in str(excinfo.value)
|
|
|
|
|
|
|
|
class NotAnException:
|
|
|
|
pass
|
|
|
|
|
|
|
|
with pytest.raises(TypeError) as excinfo:
|
|
|
|
with pytest.raises(NotAnException): # type: ignore[type-var]
|
|
|
|
pass # pragma: no cover
|
|
|
|
assert "must be a BaseException type, not NotAnException" in str(excinfo.value)
|
|
|
|
|
|
|
|
with pytest.raises(TypeError) as excinfo:
|
|
|
|
with pytest.raises(("hello", NotAnException)): # type: ignore[arg-type]
|
|
|
|
pass # pragma: no cover
|
|
|
|
assert "must be a BaseException type, not str" in str(excinfo.value)
|