CS50加油没有升起<class 'ZeroDivisionError'>

问题描述 投票:0回答:1

这个问题我真的很纠结。我不明白为什么我因为期望 ZeroDivisionError 而未能通过测试并继续得到 DID NOT RAISE 。在我的 Fuel.py 中,我已经测试过当分母为零时会引发 ZeroDivisionError 但仍然不起作用。

fuel.py代码:

def main():
    percentage = -1
    while percentage == -1:
        fraction = input('Fraction: ')
        percentage = convert(fraction)
    return_val = gauge(percentage)
    print(return_val)


def convert(fraction):
    try:
        #if / not in fraction, not enough values to unpack so ValueError
        numerator, denominator = fraction.split('/')
        numerator = int(numerator)
        denominator = int(denominator)
        percentage = round((numerator/denominator)*100)
        if percentage > 100:
            raise ValueError
        else:
            return percentage
    except ValueError:
        return -1
    except ZeroDivisionError:
        return -1



def gauge(percentage):
    if percentage <= 1:
        return 'E'
    elif percentage >= 99:
        return 'F'
    else:
        return f'{percentage}%'

if __name__ == "__main__":
    main()

test_fuel.py 代码:

from fuel import convert, gauge

import pytest

def test_gauge():
    assert gauge(1) == 'E'
    assert gauge(50) == '50%'
    assert gauge(99) == 'F'

def test_convert():
    assert convert('5/3') == -1
    assert convert('1/2') == 50
    with pytest.raises(ZeroDivisionError):
        convert('5/0')
    with pytest.raises(ValueError):
        convert('cat/dog') 
python unit-testing cs50
1个回答
0
投票

好吧,我已经弄清楚了,基本上 pytest.raises() 期望 Convert() 函数手动引发 ZeroDivisionError 而不是在函数中捕获 ZeroDivisionError

© www.soinside.com 2019 - 2024. All rights reserved.