周长函数的简单检验?

2024-09-27 00:19:31 发布

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

我以前从未使用过PyTest,现在对它感到很困惑。我只想为我的圆周函数写一个基本的测试。任何帮助都将不胜感激

import math

def getCircumference():
    radius = int(input("Please enter a radius size: "))
    circumference = 2 * math.pi * radius
    print("The circumference of the circle is", circumference)

Tags: 函数importinputsizepytestdefpimath
1条回答
网友
1楼 · 发布于 2024-09-27 00:19:31

单元测试的目的是测试函数的有效功能。这最好通过检查函数是否为已知输入返回正确的结果来实现。您的函数不接受任何输入,也不返回任何结果,因此测试要比应该的复杂得多。它在其他情况下也不太有用

我对getCircumference函数的期望是:

  • 被命名为get\ U圆周(因为PEP 8)
  • 接受一个参数:radius
  • 返回圆周(它的名字意味着它返回一个圆周)

因此:

def get_circumference(radius):
    return 2 * math.pi * radius

然后,测试将执行以下操作:

def test_get_circumference():
    # using pytest.approx to avoid problems related to floating point precision
    assert get_circumference(7) == pytest.approx(43.982297150257104)
    assert get_circumference(3.678) == pytest.approx(23.109555559806516)

另一方面,如果您真的想按原样测试函数,您应该创建一个更复杂的测试,它将覆盖sys.stdin(为了伪造用户输入)和sys.stdout(为了验证输出)

相关问题 更多 >

    热门问题