如何处理在 pytest 中导入的 Json 中的空值

How to handle null from a Json which importing in pytest

我有一个 Json 对象存储在 data.py 文件中

data_1 = {"company" = "XYZ", "Name" : null, "Number"  = null}

我有另一个文件,我在其中编写了一个 pytest

import pytest

def test_1():
    input_ = X
    result = func_1(input_)
    from .data import data_1
    output = data_1
    assert result == output

func_1 输入 returns 与 data_1 相同的输出,但使用 None 而不是 null。 在 运行 之后,pytest 在 'from .data import data_1' 行中显示错误,如

NameError : name 'null' is not defined 

首先,您的 data.py 文件是无效的 python 代码,这会引发错误。 python 不知道 null,因此 python 认为它是一个变量名,但发现它未定义 => 错误。您可以通过尝试打印未定义的内容来对此进行测试。它给出了同样的错误:

print(variable_which_was_never_defined)
# Output:
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'variable_which_was_never_defined' is not defined

尽管 python 字典看起来很像 json,但它们不是 json 对象。

为了在测试中处理 json,我通常做的是将 json 声明为字符串,如下所示:

data_1 = """{"company": "XYZ", "Name": null, "Number": null}"""

然后你可以使用 json 包将其解析为字典并比较字典:

import pytest
import json

def test_1():
    input_ = X
    result = func_1(input_)
    from .data import data_1
    output = json.loads(data_1)
    assert result == output

或者如果 func_1 returns 一个 json 字符串,你可以直接比较字符串(注意你可以按原样使用你的代码,只需要修复 data.py 文件:

import pytest

def test_1():
    input_ = X
    result = func_1(input_)
    from .data import data_1
    output = data_1
    assert result == output