assert和raise
def func():
try:
x = 1
y = 0
assert x + y == 0, 'x +y != 0, x + y is {}'.format(x + y)
except AssertionError as err:
# raise AssertionError('abc ')
# raise AssertionError
# raise
raise err
def func2(a, b):
try:
a + b
func()
except Exception as error:
print('error {} has occured'.format(error))
func2(2, 3)
# 调用func2 之后输出的如下:
# raise err 对应输出是error x +y != 0, x + y is 1 has occured
# raise 对应输出是error x +y != 0, x + y is 1 has occured
# raise AssertionError('abc')输出是error abc has occured
# raise AssertionError 输出是error has occured
raise AssertionError
会传递一个AssertionError的实例,而不是此时捕获的error
Python 中的assert
def func():
try:
x = 1
y = 0
assert x + y == 0, 'x +y != 0, x + y is {}'.format(x + y)
# 输出的是AssertionError: x +y != 0, x + y is 1
# assert x + y == 0
# 没有输出
except AssertionError as err:
print(err)
func()
# 如果是 assert condiction, message 的形式,只会打印出错误信息,不会输出条件表达式
# 如果是 assert condiction的形式,Python不会输出条件表达式
Pytest 中的assert 会Overwrite
Python 中的assert
def test():
try:
x = 1
y = 0
assert x + y == 0, 'x +y != 0, x + y is {}'.format(x + y)
# 输出的是x +y != 0, x + y is 1, assert 1 == 0
# assert x + y == 0
# 输出的是 assert 1 == 0
except AssertionError as err:
print(err)
# Pytest 不管是assert condiction, message 的形式还是assert condiction,都会输出条件表达式