首页 > 解决方案 > 使用 Pytest 测试条件语句

问题描述

当我运行测试时,它显示只有 1 个测试通过。如何使用 test_function 使其显示所有测试均已通过。

请注意, eval() 函数不带任何参数。

import pytest

def eval():
    a=1  #got this value after calling some function (this can be 1,2,3 or any value)
    if a ==2:
        return 8
    elif a == 3:
        return 4
    else:
        return 42

@pytest.mark.parametrize("expected", [
        (8),
        (4),
        (42),
    ])
def test_eval(expected):
    assert eval() == expected

标签: pythonpytest

解决方案


好的,在评论中澄清之后,这a是一个全球性的......如果不是这样会更好。:)

但如果你不能改变它的签名,

import pytest


def eval():
    if a == 2:
        return 8
    elif a == 3:
        return 4
    else:
        return 42


@pytest.mark.parametrize(
    "input_value, expected", [(2, 8), (3, 4), (4, 42)]
)
def test_eval(input_value, expected):
    global a
    a = input_value
    assert eval() == expected

应该为您解决问题。


推荐阅读