首页 > 解决方案 > 如何在python3.6中用pytest测试两个json文件

问题描述

pytest使用python3(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 数据,然后如果status == True返回"name" == "John",但如果status == False返回"name" == "dave"

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

谢谢你。

标签: pythonpython-3.xunit-testingtestingpytest

解决方案


首先,您的实际函数应该看起来像这样:

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

同样,您的实际结果肯定是另一回事,但我不明白您要做什么,所以您必须适应这一点。


推荐阅读