Python 使用Pytest测试条件语句

Python 使用Pytest测试条件语句,python,pytest,Python,Pytest,当我运行测试时,它显示只有一个测试通过。如何测试_函数,使其显示所有测试均已通过 请注意,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:

当我运行测试时,它显示只有一个测试通过。如何测试_函数,使其显示所有测试均已通过

请注意,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

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

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

导入pytest
def eval():
如果a==2:
返回8
elif a==3:
返回4
其他:
返回42
@pytest.mark.parametize(
“预期输入值”[(2,8)、(3,4)、(4,42)]
)
def测试评估(输入值,预期值):
全球a
a=输入值
assert eval()==应为

应该可以帮你解决问题。

请看一看并尝试重新格式化你的帖子。代码段很难以您发布的方式读取。如果函数不接受参数,则无法对其进行参数化。
a=
值实际上是如何设置的?我更正了它。现在可以看到代码了吗?a是在调用函数后设置的。
a
如果是
eval()
中的本地函数,则无法由另一个函数设置。这是一个全球性的吗?谢谢@AKX。无法向上投票,因为我的投票数不足15。如果
a
是局部变量,测试脚本的代码将如何更改。如果我使用
a
作为局部变量,它只通过1个案例测试。当局部变量未被执行时,您不能从函数外部修改它。最好将其作为参数传递,
def eval(a):