2012-11-02 23:04:57 +08:00
|
|
|
import pytest
|
|
|
|
|
|
|
|
class TestRaises:
|
|
|
|
def test_raises(self):
|
|
|
|
source = "int('qwe')"
|
|
|
|
excinfo = pytest.raises(ValueError, source)
|
|
|
|
code = excinfo.traceback[-1].frame.code
|
|
|
|
s = str(code.fullsource)
|
|
|
|
assert s == source
|
|
|
|
|
|
|
|
def test_raises_exec(self):
|
|
|
|
pytest.raises(ValueError, "a,x = []")
|
|
|
|
|
|
|
|
def test_raises_syntax_error(self):
|
|
|
|
pytest.raises(SyntaxError, "qwe qwe qwe")
|
|
|
|
|
|
|
|
def test_raises_function(self):
|
|
|
|
pytest.raises(ValueError, int, 'hello')
|
|
|
|
|
|
|
|
def test_raises_callable_no_exception(self):
|
|
|
|
class A:
|
|
|
|
def __call__(self):
|
|
|
|
pass
|
|
|
|
try:
|
|
|
|
pytest.raises(ValueError, A())
|
|
|
|
except pytest.raises.Exception:
|
|
|
|
pass
|
|
|
|
|
|
|
|
def test_raises_flip_builtin_AssertionError(self):
|
|
|
|
# we replace AssertionError on python level
|
|
|
|
# however c code might still raise the builtin one
|
2013-10-12 21:39:22 +08:00
|
|
|
from _pytest.assertion.util import BuiltinAssertionError # noqa
|
2012-11-02 23:04:57 +08:00
|
|
|
pytest.raises(AssertionError,"""
|
|
|
|
raise BuiltinAssertionError
|
|
|
|
""")
|
|
|
|
|
|
|
|
def test_raises_as_contextmanager(self, testdir):
|
|
|
|
testdir.makepyfile("""
|
|
|
|
from __future__ import with_statement
|
|
|
|
import py, 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
|
|
|
|
print (excinfo)
|
|
|
|
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
|
|
|
|
""")
|
|
|
|
result = testdir.runpytest()
|
|
|
|
result.stdout.fnmatch_lines([
|
|
|
|
'*3 passed*',
|
|
|
|
])
|
|
|
|
|
2014-04-15 06:09:10 +08:00
|
|
|
def test_noclass(self):
|
|
|
|
with pytest.raises(TypeError):
|
|
|
|
pytest.raises('wrong', lambda: None)
|
|
|
|
|
|
|
|
def test_tuple(self):
|
|
|
|
with pytest.raises((KeyError, ValueError)):
|
|
|
|
raise KeyError('oops')
|
2016-02-03 17:01:03 +08:00
|
|
|
|
|
|
|
def test_no_raise_message(self):
|
|
|
|
try:
|
|
|
|
pytest.raises(ValueError, int, '0')
|
|
|
|
except pytest.raises.Exception as e:
|
|
|
|
assert e.msg == "DID NOT RAISE {0}".format(repr(ValueError))
|