Swagger 2.0
如果字段required
未实际定义为required
,则表示我遇到了一些问题。
这是我的Swagger YML
文件的剪切版本。
definitions:
category:
type: object
required:
- name
- code
properties:
name:
type: string
description: Category name
code:
type: string
description: Category code
_links:
$ref: '#/definitions/categoryLinks'
children:
type: array
items:
$ref: '#/definitions/category'
categoryLinks:
required:
- self
- parent
- children
properties:
self:
description: Canonical link to this category
$ref: '#/definitions/genericLink'
parent:
description: Link to the parent category
$ref: '#/definitions/genericLink'
children:
description: Link to the child categories
$ref: '#/definitions/genericLink'
genericLink:
properties:
href:
type: string
description: The absolute URL being linked to.
paths:
'/categories/{category_code}':
get:
summary: Get a specific category
description: Returns information about a specific category.
parameters:
- name: category_code
description: Code of category to get
type: string
in: path
required: true
responses:
200:
description: Information about requested category.
schema:
$ref: '#/definitions/category'
get '/categories/awesome-cat'
的回复如下:
{
"name" => "My awesome Category",
"code" => "awesome-cat",
"_links" => {
"self" => {
"href" => "https://api.test.testing/categories/awesome-cat.json"
},
"parent"=> {},
"children" => {}
}
}
这符合预期,符合我对上述类别的定义。
我正在使用conform_to_the_documented_model_for
项目提供的名为Apivore
的swagger rspec匹配器来验证我所有API端点的输出:
matcher :conform_to_the_documented_model_for do |swagger, fragment|
match do |body|
body = JSON.parse(body)
@errors = JSON::Validator.fully_validate(swagger, body, fragment: fragment)
@errors.empty?
end
failure_message do |body|
@errors.map { |e| e.sub("'#", "'#{path}#").gsub(/^The property|in schema.*$/,'') }.join("\n")
end
end
唉,我的测试失败了。
3) the V1 API path /categories/{category_code} method get response 200 responds with the specified models
Failure/Error: expect(response.body).to conform_to_the_documented_model_for(swagger, fragment)
'#/_links/parent' did not contain a required property of 'href'
'#/_links/children' did not contain a required property of 'href'
'#' did not contain a required property of 'children'
由于某些原因,JSON验证器不将链接的href
属性视为可选,也不将children
的{{1}}属性视为可选。
据我了解,category
部分下未列出的属性是可选的。为什么required
将其视为非可选项?
答案 0 :(得分:1)
:strict
模式,这假设所有字段都是必需的。这是我在解决围绕additionalProperties
的误解后我最近做出的一项改变。我现在认为验证器的:strict
模式并不是非常有用。默认的JSON模式验证是正确的,没有理由做任何更严格的'。
确保您拥有最新版本的Apivore gem(0.0.2或更高版本)可以解决您的问题。