代码之家  ›  专栏  ›  技术社区  ›  mikanim

对pytest破例

  •  -1
  • mikanim  · 技术社区  · 6 年前

    我已经阅读了有关使用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
    

    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 回复  |  直到 6 年前
        1
  •  0
  •   Mohit Solanki MatúÅ¡ Bartko    6 年前

    pytest不创建异常。如果必须定义自定义异常,那么子类 Exception 喜欢

    Class OutOfRangeError(Exception):
        pass
    

    OutOfRangeError 超出范围错误 在你的 test_my_roman_module.py 也。