我正在try 验证JSON模式.为released Cerberus指定正确的数据类型date时,会抛出一个错误.

def test_validate_books_schema():
    schema = {
            "url" : {'type': 'string'},
            "name" : {'type': 'string'},
            "isbn" : {'type': 'string'},
            "authors" : {'type': ['string','list']},
            "numberOfPages" : {'type': 'integer'},
            "publisher" : {'type': 'string'},
            "country" : {'type': 'string'},
            "mediaType" : {'type': 'string'},
            "released" : {'type': 'date'},
            "characters" : {'type': ['string','list']},
            "povCharacters" : {'type': ['string','list']}            
        }

    response = requests.get("https://www.anapioficeandfire.com/api/books/1")
    
    v = Validator(schema)
    validate_response = v.validate(response.json())
    assert_that(validate_response, description=v.errors).is_true()
./tests/books/test_books.py::test_validate_books_schema Failed: [undefined]AssertionError: [{'released': ['must be of date type']}] Expected <True>, but was not.
def test_validate_books_schema():
        schema = {
                "url" : {'type': 'string'},
                "name" : {'type': 'string'},
                "isbn" : {'type': 'string'},
                "authors" : {'type': ['string','list']},
                "numberOfPages" : {'type': 'integer'},
                "publisher" : {'type': 'string'},
                "country" : {'type': 'string'},
                "mediaType" : {'type': 'string'},
                "released" : {'type': 'date'},
                "characters" : {'type': ['string','list']},
                "povCharacters" : {'type': ['string','list']}
            }
    
        response = requests.get("https://www.anapioficeandfire.com/api/books/1")
    
        v = Validator(schema)
        validate_response = v.validate(response.json())
>       assert_that(validate_response, description=v.errors).is_true()
E       AssertionError: [{'released': ['must be of date type']}] Expected <True>, but was not.

tests\books\test_books.py:42: AssertionError

documentation表示released的数据类型是Date.当我为released指定string时,它是有效的.

推荐答案

稍微更改代码,如下所示:

from cerberus import Validator
from assertpy import assert_that
from datetime import datetime
import requests

def date_hook(json_dict):
    for (key, value) in json_dict.items():
        try:
            json_dict[key] = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S")
        except:
            pass
    return json_dict

def test_validate_books_schema():
    schema = {
            "url" : {'type': 'string'},
            "name" : {'type': 'string'},
            "isbn" : {'type': 'string'},
            "authors" : {'type': ['string','list']},
            "numberOfPages" : {'type': 'integer'},
            "publisher" : {'type': 'string'},
            "country" : {'type': 'string'},
            "mediaType" : {'type': 'string'},
            "released" : {'type': 'date'},
            "characters" : {'type': ['string','list']},
            "povCharacters" : {'type': ['string','list']}            
        }

    response = requests.get("https://www.anapioficeandfire.com/api/books/1")

    v = Validator(schema)
    validate_response = v.validate(response.json(object_hook=date_hook))
    assert_that(validate_response, description=v.errors).is_true()

test_validate_books_schema()
print('Done')

我们在这里做的是在response.json中添加一个对象钩子,它将调用date_hook,这将适当地格式化日期/时间(see this answer)

一旦运行文件,就不会出现任何错误.

Python-3.x相关问答推荐

为什么打印语句在Python多处理脚本中执行两次?

在多个测试中维护和报告变量

使用 iloc 或 loc 对多列进行过滤

删除列表中的第二个出现

平移数组

在不改变 python 中原始数组顺序的情况下,对多维字符串数组进行降序排序?

如何沿单列获取嵌套列表中的唯一值?

Python3:是否可以将变量用作函数调用的一部分

Pandas 在每组两个条件之间获得时间增量

Pandas matplotlib:条形图占总数的百分比

如何从形状汇总图中提取实际值

为什么 Sympy 不能解决我的非线性系统? Python 解释器一直在执行,直到我终止进程

过滤阈值大小数据以使用 Pyspark 或 Python 读取

根据另一列值对多个数据框列进行分组

TypeError:JSON 对象必须是 str,而不是 'dict'

为什么包含类的名称不被识别为返回值函数注释?

为什么排序列表比未排序列表大

Python 3中星型导入的函数形式是什么

如何在 Python 3.2 中退出?

如何从 seaborn / matplotlib 图中删除或隐藏 x 轴标签