如何在CS50P pset 5上有效地运行单元测试(测试 fuel.py)?

huangapple go评论67阅读模式
英文:

How can I run a unit test effectively on CS50P pset 5 (test fuel.py)

问题

以下是您要翻译的代码部分:

I fail to spot what is wrong on this code yet pytest runs succesfully but I get error messages when CS50 test my code.

I expect my code to raise ValuError, TypeError.Exceptions and be testable meet all requirements such as outputing the right percentage.

Here is My code of fuel.py

def main():
    while True:
        try:
            fuel = input("Fraction:").split('/')
            fraction = convert(fuel)
            if fraction is not None:
                print(fraction)

            percentage = gauge(fuel)
            if percentage is not None:
                print(percentage)
                break
        except ValueError:
            raise ValueError("ValueError")
        except ZeroDivisionError:
            raise ZeroDivisionError("Error")
        except TypeError:
            raise TypeError("ValueError")

def convert(fraction):

              fraction = fraction
              x = int(fraction[0])
              y = int(fraction[1])

              if y == 0:
                raise ZeroDivisionError("ZeroDivisionError")

              fraction = round((x/y)*100)
              if  fraction > 100:
                  raise ValueError("ValueError")

              else:
                  if fraction < 99 and fraction > 1:
                    return fraction
def gauge(percentage):
            fraction = percentage
            x = int(fraction[0])
            y = int(fraction[1])

            percentage = round((x/y)*100)
            if fraction[0] == fraction[1] or percentage >= 99 :
                return "F"
            if percentage <= 1:
                return "E"
            else:
             return str(percentage) + "%"


if __name__=="__main__":
   main()
My Test file is this one. below

import pytest
from fuel import convert, gauge

def test_convert():
   assert convert("3", "4") == "75%"

def test_convert():
    with pytest.raises(ZeroDivisionError):
        convert(["3", "0"])

def test_convert():
    with pytest.raises(ValueError):
        convert(["4", "3"])

def test_gauge():
    assert gauge("7", "7") == "F"

def test_gauge():
    assert gauge("1", "100") == "E"

请注意,您的测试函数存在一些问题,因为它们都有相同的名称(例如,test_convert和test_gauge)。您应该给它们不同的名称以便正确运行测试。
<details>
<summary>英文:</summary>
[enter image description here][1]I fail to spot what is wrong on this code yet pytest runs succesfully but I get error messages when CS50 test my code.
I expect my code to raise ValuError, TypeError.Exceptions and be testable meet all requirements such as outputing the right percentage.
[1]: https://i.stack.imgur.com/4SZo8.png
Here is My code of fuel.py

def main():
while True:
try:
fuel = input("Fraction:").split('/')
fraction = convert(fuel)
if fraction is not None:
print(fraction)

        percentage = gauge(fuel)
if percentage is not None:
print(percentage)
break
except ValueError:
raise ValueError(&quot;ValueError&quot;)
except ZeroDivisionError:
raise ZeroDivisionError(&quot;Error&quot;)
except TypeError:
raise TypeError(&quot;ValueError&quot;)

def convert(fraction):

          fraction = fraction
x = int(fraction[0])
y = int(fraction[1])
if y == 0:
raise ZeroDivisionError(&quot;ZeroDivisionError&quot;)
fraction = round((x/y)*100)
if  fraction &gt; 100:
raise ValueError(&quot;ValueError&quot;)
else:
if fraction &lt; 99 and fraction &gt; 1:
return fraction

def gauge(percentage):
fraction = percentage
x = int(fraction[0])
y = int(fraction[1])

        percentage = round((x/y)*100)
if fraction[0] == fraction[1] or percentage &gt;= 99 :
return &quot;F&quot;
if percentage &lt;= 1:
return &quot;E&quot;
else:
return str(percentage) + &quot;%&quot;

if name=="main":
main()


My Test file is this one. below

import pytest
from fuel import convert, gauge

def test_convert():
assert convert("3", "4") == "75%"

def test_convert():
with pytest.raises(ZeroDivisionError):
convert(["3", "0"])

def test_convert():
with pytest.raises(ValueError):
convert(["4", "3"])

def test_gauge():
assert gauge("7", "7") == "F"

def test_gauge():
assert gauge("1", "100") == "E"


However the instructions were In a file called fuel.py, reimplement Fuel Gauge from Problem Set 3, restructuring your code per the below, wherein:
convert expects a str in X/Y format as input, wherein each of X and Y is an integer, and returns that fraction as a percentage rounded to the nearest int between 0 and 100, inclusive. If X and/or Y is not an integer, or if X is greater than Y, then convert should raise a ValueError. If Y is 0, then convert should raise a ZeroDivisionError.
gauge expects an int and returns a str that is:
&quot;E&quot; if that int is less than or equal to 1,
&quot;F&quot; if that int is greater than or equal to 99,
and &quot;Z%&quot; otherwise, wherein Z is that same int.
</details>
# 答案1
**得分**: 1
好的,以下是翻译好的内容:
我查看了更新后的代码。问题太多了... 你是否使用pytest重新运行了`test_fuel.py`?我问这个问题是因为有很多错误需要通过测试来发现。在StackOverflow上提问的期望是你已经进行了自己的测试并且遇到了问题。当我测试时,我得到以下错误:
============================================= short test summary info ==============================================
FAILED test_fuel.py::test_gauge - TypeError: gauge()接受1个位置参数,但提供了2个
========================================== 1个失败,1个通过,共耗时0.08秒 ============================================
请注意,它说的是"1个失败,1个通过",而不是"1个失败,4个通过"。当我仔细查看时,我发现你有3个版本的`test_convert()`和2个版本的`test_gauge()`。这是一个问题,因为只保留每个函数的最后一个版本。我为每个函数名称添加了一个编号并重新运行了测试。当我这样做时,出现了几个错误:
============================================= short test summary info ==============================================
FAILED test_fuel.py::test_convert1 - TypeError: convert()接受1个位置参数,但提供了2个
FAILED test_fuel.py::test_gauge1 - TypeError: gauge()接受1个位置参数,但提供了2个
FAILED test_fuel.py::test_gauge2 - TypeError: gauge()接受1个位置参数,但提供了2个
========================================== 3个失败,2个通过,共耗时0.10秒 ============================================
所以,接下来我修复了函数的输入,使它们都是包含2个项的1个列表。然后发现另一个错误:
============================================= short test summary info ==============================================
FAILED test_fuel.py::test_convert1 - AssertionError: 断言失败,预期是75,但得到的是'75%'
========================================== 1个失败,4个通过,共耗时0.08秒 ============================================
这是因为你的`convert()`函数返回一个整数,而你的测试函数检查一个字符串。所以,我修复了这个错误,并添加了另一个测试函数来检查`gauge(["3", "4"])`的返回值是否为`'75%'`。当我这样做时,所有6个pytest **终于** 通过了。这是好消息。
坏消息是,它仍然无法通过check50。为什么呢?因为你的两个函数都不符合规范。重新阅读一下,你会发现以下要求:
- `convert` 需要一个输入为`X/Y`格式的字符串,其中`X`和`Y`都是整数
- `gauge` 需要一个整数,并返回一个字符串
你将输入作为字符串列表发送给`convert()`,而不是`X/Y`字符串分数。你还将字符串列表作为输入发送给`gauge()`...而不是从`convert()`返回的整数。你需要在`fuel.py`中修复这些函数,然后修改`test_fuel.py`以匹配新的输入。一旦你修复了这个问题,你将非常接近了。check50将在你的`test_fuel.py`中找到另一个错误,我会让你自己找到并修复它。
<details>
<summary>英文:</summary>
OK, I looked at the updated code. So many problems...Did you re-run `test_fuel.py` with pytest? I ask because there are a LOT of errors that testing will uncover. The expectation when posting a question on StackOverflow is that you have done your own testing and are stuck. When I test, I get the following error:
============================================= short test summary info ==============================================
FAILED test_fuel.py::test_gauge - TypeError: gauge() takes 1 positional argument but 2 were given
=========================================== 1 failed, 1 passed in 0.08s ============================================
Note that it says `1 failed, 1 passed`, not `1 failed, 4 passed`. When I looked closer, I realized you have 3 versions of `test_convert()` and 2 versions of `test_gauge()`. That&#39;s a problem because only the last version of each function is kept. I added a number to each function name and reran. When I do, I get several errors:  
============================================= short test summary info ==============================================
FAILED test_fuel.py::test_convert1 - TypeError: convert() takes 1 positional argument but 2 were given
FAILED test_fuel.py::test_gauge1 - TypeError: gauge() takes 1 positional argument but 2 were given
FAILED test_fuel.py::test_gauge2 - TypeError: gauge() takes 1 positional argument but 2 were given
=========================================== 3 failed, 2 passed in 0.10s ============================================
So, next I fixed the function inputs so all of them are 1 list with 2 items. Then another error is discovered:
============================================= short test summary info ==============================================
FAILED test_fuel.py::test_convert1 - AssertionError: assert 75 == &#39;75%&#39;
=========================================== 1 failed, 4 passed in 0.08s ============================================
This occurs because your `convert()` function returns an integer, and your test function checks for a string. So, I fixed that error and added another test function to check for a return of `&#39;75%&#39;` from `gauge([&quot;3&quot;, &quot;4&quot;]). When I do, all 6 pytests **FINALLY** pass. That&#39;s the good news.  
The bad news? It still doesn&#39;t pass check50. Why? Because both of your functions don&#39;t follow the specification. Re-read and you will find these requirements:
- `convert` expects a `str` in `X/Y` format as input, wherein each of `X` and `Y`
is an integer
- `gauge` expects an `int` and returns a `str` 
You send the input as a list of strings to `convert()`, not as a `X/Y` string fraction. You also send the input list of strings to `gauge()`...not the integer returned from `convert()`. You need to fix these functions in `fuel.py`, then modify `test_fuel.py` to match the new inputs. Once you fix that, you will be pretty close. check50 will find 1 more error in your `test_fuel.py`. I will let you find and fix that on your own.
</details>

huangapple
  • 本文由 发表于 2023年5月29日 18:49:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76356690.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定