如何 运行 Pytest On If Else 语句?

How to Run Pytest On If Else Statement?

我成功 运行 Pytest calculate_bmi 函数,但 运行 Pytest bmi_index 函数失败。我可以知道如何 运行 Pytest bmi_index 函数吗?

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 == 'You are obese.' 我认为这意味着没有要执行的测试,但我不确定如何执行。你能帮我吗?非常感谢。

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> 

打印与 return打印不同。函数 bmi_index 打印文本但不 return 任何东西(因此 None return 值)。您可以通过添加 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.'

The error was: AssertionError: assert None == 'You are obese.' I think it means there is no test to perform, but I'm not sure how.

不是这个意思。这意味着您断言两件事是平等的,但事实并非如此。 None不等于行

上的字符串'You are obese.'
assert bmi_index(31) == 'You are obese.'

那是因为函数调用 bmi_index(31) returns None 是隐式的,因为在内部你只打印结果而不 returning 任何东西。使该函数 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.'

如果您想在屏幕上看到这些消息,请在调用该函数后打印 return 值。

您也可以重定向标准输出来测试它。

from practice4 import calculate_bmi, bmi_index
import pytest
from pytest import approx
from contextlib import redirect_stdout
from io import StringIO


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."""
    stdout = StringIO()
    with redirect_stdout(stdout):
        bmi_index(31)
    assert stdout.getvalue() == 'You are obese.'


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

这比更改原始函数更好,因为您可以看到 print 添加了一个换行符。

AssertionError: assert 'You are obese.\n' == 'You are obese.'