pytest例外

时间:2018-08-29 07:41:59

标签: python pytest

我已经阅读了有关使用pytest创建异常的文档,但是不确定如何在代码中定义异常。据说没有定义OutOfRangeError。任何帮助表示赞赏。

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 (must be between 1-3999)')
result = ''
for numeral, integer in roman_numerals:
    while n >= integer: 
        result += numeral
        n -= integer
return result

test_my_roman_module.py:

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)

1 个答案:

答案 0 :(得分:0)

pytest不会创建异常。如果必须定义自定义异常,则子类Exception

Class OutOfRangeError(Exception):
    pass

然后您引发OutOfRangeError异常,请记住也将OutOfRangeError导入您的test_my_roman_module.py