Json schema improvements (#1078)

* Test multipleOf

* Refactor defaulting

* Use default if invalid for non-object/array properties

* Add tests
This commit is contained in:
toasted-nutbread 2020-11-30 18:56:28 -05:00 committed by GitHub
parent ff6ebdab88
commit ae9a20e0de
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 108 additions and 15 deletions

View File

@ -594,23 +594,22 @@ class JsonSchemaValidator {
return null;
}
_getDefaultSchemaValue(schema) {
const schemaType = schema.type;
const schemaDefault = schema.default;
return (
typeof schemaDefault !== 'undefined' &&
this._isValueTypeAny(schemaDefault, this._getValueType(schemaDefault), schemaType) ?
clone(schemaDefault) :
this._getDefaultTypeValue(schemaType)
);
}
_getValidValueOrDefault(schema, value, info) {
let type = this._getValueType(value);
const schemaType = schema.type;
if (typeof value === 'undefined' || !this._isValueTypeAny(value, type, schemaType)) {
let assignDefault = true;
const schemaDefault = schema.default;
if (typeof schemaDefault !== 'undefined') {
value = clone(schemaDefault);
if (typeof value === 'undefined' || !this._isValueTypeAny(value, type, schema.type)) {
value = this._getDefaultSchemaValue(schema);
type = this._getValueType(value);
assignDefault = !this._isValueTypeAny(value, type, schemaType);
}
if (assignDefault) {
value = this._getDefaultTypeValue(schemaType);
type = this._getValueType(value);
}
}
switch (type) {
@ -620,6 +619,14 @@ class JsonSchemaValidator {
case 'array':
value = this._populateArrayDefaults(value, schema, info);
break;
default:
if (!this.isValid(value, schema)) {
const schemaDefault = this._getDefaultSchemaValue(schema);
if (this.isValid(schemaDefault, schema)) {
value = schemaDefault;
}
}
break;
}
return value;

View File

@ -358,6 +358,19 @@ function testValidate2() {
{expected: false, value: 1}
]
},
{
schema: {
type: 'integer',
multipleOf: 2
},
inputs: [
{expected: true, value: -2},
{expected: false, value: -1},
{expected: true, value: 0},
{expected: false, value: 1},
{expected: true, value: 2}
]
},
// Numeric type tests
{
@ -595,6 +608,79 @@ function testGetValidValueOrDefault1() {
{toString: 'default'}
]
]
},
// Test enum
{
schema: {
type: 'object',
required: ['test'],
properties: {
test: {
type: 'string',
default: 'value1',
enum: ['value1', 'value2', 'value3']
}
}
},
inputs: [
[
{test: 'value1'},
{test: 'value1'}
],
[
{test: 'value2'},
{test: 'value2'}
],
[
{test: 'value3'},
{test: 'value3'}
],
[
{test: 'value4'},
{test: 'value1'}
]
]
},
// Test valid vs invalid default
{
schema: {
type: 'object',
required: ['test'],
properties: {
test: {
type: 'integer',
default: 2,
minimum: 1
}
}
},
inputs: [
[
{test: -1},
{test: 2}
]
]
},
{
schema: {
type: 'object',
required: ['test'],
properties: {
test: {
type: 'integer',
default: 1,
minimum: 2
}
}
},
inputs: [
[
{test: -1},
{test: -1}
]
]
}
];