对pytes破例

2024-09-29 23:19:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经阅读了有关使用pytest创建异常的文档,但不确定如何在代码中定义异常。意思是没有定义OutOfRangeError。感谢您的帮助

我的罗马模块.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

测试\u my \u roman \u 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)

Tags: toinpy定义pytestmydefnot

热门问题