gpt4 book ai didi

python - 如何在 If else 语句上运行 Pytest?

转载 作者:行者123 更新时间:2023-12-03 08:07:30 26 4
gpt4 key购买 nike

我成功运行了calculate_bmi函数的Pytest,但未能运行bmi_index函数的Pytest。我可以知道如何为 bmi_index 函数运行 Pytest 吗?

def main():
weight = float(input('Enter weight (kg): '))
height = float(input('Enter height (cm): '))

bmi = calculate_bmi(weight, height)
bmi_index(bmi)

def calculate_bmi(weight, height):
bmi = round(10000 * weight / (height ** 2))
return bmi

def bmi_index(bmi):
if bmi <= 18.5:
print('You are underweight.')
elif bmi <= 24.9:
print('You are normal weight.')
elif bmi <= 29.9:
print('You are overweight.')
else:
print('You are obese.')

if __name__ == "__main__":
main()

我已尝试以下操作,但测试失败(对于 test_bmi_index)。错误是:AssertionError:assert None == '你很肥胖。'我认为这意味着没有要执行的测试,但我不确定如何执行。你能帮我吗?非常感谢。

from practice4 import calculate_bmi, bmi_index
import pytest
from pytest import approx


def test_calculate_bmi():
"""Verify that the calculate bmi function works correctly."""
assert calculate_bmi(47, 154) == approx(20)
assert calculate_bmi(-95, 175) == approx(-31)
assert calculate_bmi(4.5, 1.54) == approx(18975)

def test_bmi_index():
"""Verify that the bmi_index function works correctly."""
assert bmi_index(31) == 'You are obese.'


pytest.main(["-v", "--tb=line", "-rN", __file__])

========================= test session starts ==========================
platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 -- C:\Users\iamsp\AppData\Local\Programs\Python\Python39\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\iamsp\Documents\Intro To Python Development
collected 2 items

test_practice4.py::test_calculate_bmi PASSED [ 50%]
test_practice4.py::test_bmi_index FAILED [100%]

=============================== FAILURES ===============================
c:\Users\iamsp\Documents\Intro To Python Development\test_practice4.py:14: AssertionError: assert None == 'You are obese.'
===================== 1 failed, 1 passed in 0.06s ======================
PS C:\Users\iamsp\Documents\Intro To Python Development>

最佳答案

打印与返回不同。函数 bmi_index 打印文本,但不返回任何内容(因此返回值 None)。您可以通过添加 return 语句来解决此问题:

def bmi_index(bmi):
if bmi <= 18.5:
return 'You are underweight.'
elif bmi <= 24.9:
return 'You are normal weight.'
elif bmi <= 29.9:
return 'You are overweight.'
else:
return 'You are obese.'

或者,如果您愿意的话:

def bmi_index(bmi):
if bmi <= 18.5:
print('You are underweight.')
return 'You are underweight.'
elif bmi <= 24.9:
print('You are normal weight.')
return 'You are normal weight.'
elif bmi <= 29.9:
print('You are overweight.')
return 'You are overweight.'
else:
print('You are obese.')
return 'You are obese.'

关于python - 如何在 If else 语句上运行 Pytest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71719228/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com