我正在嘗試驗證 JSON 模式。date為Cerberus指定正確的資料型別時released會引發錯誤。
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
檔案指出資料型別released為. Date當我指定string它released作業時。
uj5u.com熱心網友回復:
稍微改變你的代碼,如下所示:
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,它適當地格式化日期/時間(見這個答案)
運行檔案后,您應該不會收到任何錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/465646.html
標籤:python-3.x pytest 地狱犬
