Python 使用pytest生成异常
我已经阅读了有关使用pytest创建异常的文档,但不确定如何在代码中定义异常。这意味着OutOfRange错误没有定义。感谢您的帮助 my_roman_module.py:Python 使用pytest生成异常,python,pytest,Python,Pytest,我已经阅读了有关使用pytest创建异常的文档,但不确定如何在代码中定义异常。这意味着OutOfRange错误没有定义。感谢您的帮助 my_roman_module.py: def to_roman(n): '''converts integers/arabic numerals to Roman numerals''' if not (0<n<4000): raise OutOfRangeError('number out of range (mus
def to_roman(n):
'''converts integers/arabic numerals to Roman numerals'''
if not (0<n<4000):
raise OutOfRangeError('number out of range (must be between 1-3999)')
result = ''
for numeral, integer in roman_numerals:
while n >= integer:
result += numeral
n -= integer
return result
import pytest
from my_roman_module import to_roman
def test_not_in_range():
'''to_roman should fail with large input'''
with pytest.raises(OutOfRangeError):
to_roman(4000)
pytest不会创建异常。如果必须定义自定义异常,那么子类
exception
like
Class OutOfRangeError(Exception):
pass
然后,如果出现
OutOfRangeError
异常,请记住在测试模块.py中导入OutOfRangeError
。这就是您要查找的吗?可能是