test_ok2/testing/python/raises.py

274 lines
9.4 KiB
Python
Raw Normal View History

import re
import sys
import pytest
from _pytest.outcomes import Failed
2019-06-03 06:32:00 +08:00
class TestRaises:
def test_check_callable(self) -> None:
with pytest.raises(TypeError, match=r".* must be callable"):
pytest.raises(RuntimeError, "int('qwe')") # type: ignore[call-overload] # noqa: F821
def test_raises(self):
excinfo = pytest.raises(ValueError, int, "qwe")
assert "invalid literal" in str(excinfo.value)
def test_raises_function(self):
excinfo = pytest.raises(ValueError, int, "hello")
assert "invalid literal" in str(excinfo.value)
def test_raises_callable_no_exception(self) -> None:
2019-06-03 06:32:00 +08:00
class A:
def __call__(self):
pass
2018-05-23 22:48:46 +08:00
try:
pytest.raises(ValueError, A())
except pytest.fail.Exception:
pass
def test_raises_falsey_type_error(self) -> None:
with pytest.raises(TypeError):
with pytest.raises(AssertionError, match=0): # type: ignore[call-overload] # noqa: F821
raise AssertionError("ohai")
def test_raises_repr_inflight(self):
"""Ensure repr() on an exception info inside a pytest.raises with block works (#4386)"""
class E(Exception):
pass
with pytest.raises(E) as excinfo:
# 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)
raise E()
def test_raises_as_contextmanager(self, testdir):
2018-05-23 22:48:46 +08:00
testdir.makepyfile(
"""
2018-07-08 23:35:53 +08:00
import pytest
import _pytest._code
def test_simple():
with pytest.raises(ZeroDivisionError) as excinfo:
assert isinstance(excinfo, _pytest._code.ExceptionInfo)
1/0
2018-11-22 16:15:14 +08:00
print(excinfo)
assert excinfo.type == ZeroDivisionError
assert isinstance(excinfo.value, ZeroDivisionError)
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
"""
)
result = testdir.runpytest()
2018-05-23 22:48:46 +08:00
result.stdout.fnmatch_lines(["*3 passed*"])
def test_does_not_raise(self, testdir):
testdir.makepyfile(
"""
from contextlib import contextmanager
import pytest
@contextmanager
def does_not_raise():
yield
@pytest.mark.parametrize('example_input,expectation', [
(3, does_not_raise()),
(2, does_not_raise()),
(1, does_not_raise()),
(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
"""
)
result = testdir.runpytest()
result.stdout.fnmatch_lines(["*4 passed*"])
def test_does_not_raise_does_raise(self, testdir):
testdir.makepyfile(
"""
from contextlib import contextmanager
import pytest
@contextmanager
def does_not_raise():
yield
@pytest.mark.parametrize('example_input,expectation', [
(0, does_not_raise()),
(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
"""
)
result = testdir.runpytest()
result.stdout.fnmatch_lines(["*2 failed*"])
def test_noclass(self) -> None:
with pytest.raises(TypeError):
pytest.raises("wrong", lambda: None) # type: ignore[call-overload] # noqa: F821
def test_invalid_arguments_to_raises(self) -> None:
2018-05-23 22:48:46 +08:00
with pytest.raises(TypeError, match="unknown"):
with pytest.raises(TypeError, unknown="bogus"): # type: ignore[call-overload] # noqa: F821
raise ValueError()
def test_tuple(self):
with pytest.raises((KeyError, ValueError)):
2018-05-23 22:48:46 +08:00
raise KeyError("oops")
def test_no_raise_message(self) -> None:
try:
2018-05-23 22:48:46 +08:00
pytest.raises(ValueError, int, "0")
except pytest.fail.Exception as e:
2018-05-18 05:31:16 +08:00
assert e.msg == "DID NOT RAISE {}".format(repr(ValueError))
else:
assert False, "Expected pytest.raises.Exception"
2016-06-17 01:15:32 +08:00
try:
with pytest.raises(ValueError):
pass
except pytest.fail.Exception as e:
2018-05-18 05:31:16 +08:00
assert e.msg == "DID NOT RAISE {}".format(repr(ValueError))
else:
assert False, "Expected pytest.raises.Exception"
2016-06-17 01:15:32 +08:00
@pytest.mark.parametrize("method", ["function", "function_match", "with"])
def test_raises_cyclic_reference(self, method):
"""
Ensure pytest.raises does not leave a reference cycle (#1965).
"""
import gc
2019-06-03 06:32:00 +08:00
class T:
def __call__(self):
# Early versions of Python 3.5 have some bug causing the
# __call__ frame to still refer to t even after everything
# is done. This makes the test pass for them.
2020-01-13 03:35:20 +08:00
if sys.version_info < (3, 5, 2):
del self
raise ValueError
t = T()
refcount = len(gc.get_referrers(t))
2018-05-23 22:48:46 +08:00
if method == "function":
pytest.raises(ValueError, t)
elif method == "function_match":
pytest.raises(ValueError, t).match("^$")
else:
with pytest.raises(ValueError):
t()
# ensure both forms of pytest.raises don't leave exceptions in sys.exc_info()
assert sys.exc_info() == (None, None, None)
assert refcount == len(gc.get_referrers(t))
def test_raises_match(self) -> None:
msg = r"with base \d+"
with pytest.raises(ValueError, match=msg):
2018-05-23 22:48:46 +08:00
int("asdf")
msg = "with base 10"
with pytest.raises(ValueError, match=msg):
2018-05-23 22:48:46 +08:00
int("asdf")
msg = "with base 16"
expr = "Pattern {!r} does not match \"invalid literal for int() with base 10: 'asdf'\"".format(
2018-05-23 22:48:46 +08:00
msg
)
with pytest.raises(AssertionError, match=re.escape(expr)):
with pytest.raises(ValueError, match=msg):
2018-05-23 22:48:46 +08:00
int("asdf", base=10)
# "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):
raise ValueError("match={}".format(match))
pytest.raises(ValueError, tfunc, match="asdf").match("match=asdf")
pytest.raises(ValueError, tfunc, match="").match("match=")
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
assert msg == 'Pattern "\'foo" does not match "\'bar"'
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(
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)
def test_raises_with_raising_dunder_class(self) -> None:
"""Test current behavior with regard to exceptions via __class__ (#4284)."""
class CrappyClass(Exception):
# Type ignored because it's bypassed intentionally.
@property # type: ignore
def __class__(self):
assert False, "via __class__"
with pytest.raises(AssertionError) as excinfo:
with pytest.raises(CrappyClass()): # type: ignore[call-overload] # noqa: F821
pass
assert "via __class__" in excinfo.value.args[0]
def test_raises_context_manager_with_kwargs(self):
with pytest.raises(TypeError) as excinfo:
with pytest.raises(Exception, foo="bar"): # type: ignore[call-overload] # noqa: F821
pass
assert "Unexpected keyword arguments" in str(excinfo.value)