如何在python3.6中使用pytest测试两个json文件

2024-04-26 04:00:56 发布

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

pytestpython3(3.6}+)测试以下案例的最佳方法是什么

json_data_one = {
   "id": 1,
   "status": True,
   "name": "Jhon"
}

json_data_two = {
   "id": 2,
   "status": False,
   "name": "Dave"
}
def foo(json_data_one, json_data_two):
    # not the best way to show this
    # but i want to loop through each json data then
    # show the result based on `status` is either `True` or `False`
    if json_data_one["status"] == True:
        return json_data_one
    elif json_data_two["status"] == False:
        return json_data_two

@pytest.mark.parametrize("status, name", [(True, "John"), (False, "dave")])
def test_foo(status, name):
    assert foo(status) == name

以上步骤会产生错误

status = True, name = 'John'

    @pytest.mark.parametrize("status, name", [(True, "John"), (False, "dave")])
    def test_foo(status, name):
>       assert foo(status) == name
E    TypeError: foo() missing 1 required positional argument: 'json_data_two'

test_start.py:46: TypeError
___________________________________________________________________________________________ test_foo[False-dave] ___________________________________________________________________________________________

status = False, name = 'dave'

    @pytest.mark.parametrize("status, name", [(True, "John"), (False, "dave")])
    def test_foo(status, name):
>       assert foo(status) == name
E    TypeError: foo() missing 1 required positional argument: 'json_data_two'

test_start.py:46: TypeError
========================================================================================= short test summary info ==========================================================================================
FAILED test_start.py::test_foo[True-John] - TypeError: foo() missing 1 required positional argument: 'json_data_two'
FAILED test_start.py::test_foo[False-dave] - TypeError: foo() missing 1 required positional argument: 'json_data_two'

我对如何实现它有点迷茫,但我想完成的是检查每个json数据,然后ifstatus == True返回"name" == "John",但是ifstatus == False返回"name" == "dave"

我相信parametrize可以使用,但我很难弄清楚

多谢各位


Tags: nametestjsonfalsetruedatafoopytest
1条回答
网友
1楼 · 发布于 2024-04-26 04:00:56

首先,您的实际功能可能如下所示:

def foo(json_data):
    if json_data["status"]:
        return json_data["name"]
    elif:
        return "Nope"

我不知道你到底想做什么,但函数的原样是没有意义的。当然,你必须替换你的实际功能

然后,您的测试可以如下所示:

@pytest.mark.parametrize("data, result", [(json_data_one, "John"), 
                                          (json_data_two, "Nope")])
def test_foo(data, result):
    assert foo(data) == result

再说一次,你的实际结果肯定是另一回事,但我不明白你想做什么,所以你必须适应这个

相关问题 更多 >