From c2371584a0550f43a959140efe3cd83b8c6ede63 Mon Sep 17 00:00:00 2001 From: Yuri Khan Date: Sat, 16 Sep 2017 17:48:54 +0700 Subject: Keep schema URI in GenericSchemaDocument and internal::Schema --- include/rapidjson/schema.h | 23 ++++++++++++++++++++--- test/unittest/schematest.cpp | 21 ++++++++++----------- 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/include/rapidjson/schema.h b/include/rapidjson/schema.h index e51b3692..5a818542 100644 --- a/include/rapidjson/schema.h +++ b/include/rapidjson/schema.h @@ -349,6 +349,7 @@ public: Schema(SchemaDocumentType* schemaDocument, const PointerType& p, const ValueType& value, const ValueType& document, AllocatorType* allocator) : allocator_(allocator), + uri_(schemaDocument->GetURI(), *allocator), pointer_(p), typeless_(schemaDocument->GetTypeless()), enum_(), @@ -597,6 +598,10 @@ public: #endif } + const SValue& GetURI() const { + return uri_; + } + const PointerType& GetPointer() const { return pointer_; } @@ -1220,6 +1225,7 @@ private: }; AllocatorType* allocator_; + SValue uri_; PointerType pointer_; const SchemaType* typeless_; uint64_t* enum_; @@ -1330,6 +1336,7 @@ public: typedef typename EncodingType::Ch Ch; typedef internal::Schema SchemaType; typedef GenericPointer PointerType; + typedef GenericValue URIType; friend class internal::Schema; template friend class GenericSchemaValidator; @@ -1339,10 +1346,13 @@ public: Compile a JSON document into schema document. \param document A JSON document as source. + \param uri The base URI of this schema document for purposes of violation reporting. + \param uriLength Length of \c name, in code points. \param remoteProvider An optional remote schema document provider for resolving remote reference. Can be null. \param allocator An optional allocator instance for allocating memory. Can be null. */ - explicit GenericSchemaDocument(const ValueType& document, IRemoteSchemaDocumentProviderType* remoteProvider = 0, Allocator* allocator = 0) : + explicit GenericSchemaDocument(const ValueType& document, const Ch* uri = 0, SizeType uriLength = 0, + IRemoteSchemaDocumentProviderType* remoteProvider = 0, Allocator* allocator = 0) : remoteProvider_(remoteProvider), allocator_(allocator), ownAllocator_(), @@ -1354,8 +1364,11 @@ public: if (!allocator_) ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); + Ch noUri[1] = {0}; + uri_.SetString(uri ? uri : noUri, uriLength, *allocator_); + typeless_ = static_cast(allocator_->Malloc(sizeof(SchemaType))); - new (typeless_) SchemaType(this, PointerType(), ValueType(kObjectType).Move(), ValueType(kObjectType).Move(), 0); + new (typeless_) SchemaType(this, PointerType(), ValueType(kObjectType).Move(), ValueType(kObjectType).Move(), allocator_); // Generate root schema, it will call CreateSchema() to create sub-schemas, // And call AddRefSchema() if there are $ref. @@ -1393,7 +1406,8 @@ public: root_(rhs.root_), typeless_(rhs.typeless_), schemaMap_(std::move(rhs.schemaMap_)), - schemaRef_(std::move(rhs.schemaRef_)) + schemaRef_(std::move(rhs.schemaRef_)), + uri_(std::move(rhs.uri_)) { rhs.remoteProvider_ = 0; rhs.allocator_ = 0; @@ -1415,6 +1429,8 @@ public: RAPIDJSON_DELETE(ownAllocator_); } + const URIType& GetURI() const { return uri_; } + //! Get the root schema. const SchemaType& GetRoot() const { return *root_; } @@ -1545,6 +1561,7 @@ private: SchemaType* typeless_; internal::Stack schemaMap_; // Stores created Pointer -> Schemas internal::Stack schemaRef_; // Stores Pointer from $ref and schema which holds the $ref + URIType uri_; }; //! GenericSchemaDocument using Value type. diff --git a/test/unittest/schematest.cpp b/test/unittest/schematest.cpp index 6c395d13..34436ac3 100644 --- a/test/unittest/schematest.cpp +++ b/test/unittest/schematest.cpp @@ -1071,6 +1071,12 @@ public: "jsonschema/remotes/folder/folderInteger.json", "draft-04/schema" }; + const char* uris[kCount] = { + "http://localhost:1234/integer.json", + "http://localhost:1234/subSchemas.json", + "http://localhost:1234/folder/folderInteger.json", + "http://json-schema.org/draft-04/schema" + }; for (size_t i = 0; i < kCount; i++) { sd_[i] = 0; @@ -1087,7 +1093,7 @@ public: MemoryPoolAllocator<> stackAllocator(stackBuffer, sizeof(stackBuffer)); DocumentType d(&documentAllocator_, 1024, &stackAllocator); d.Parse(json); - sd_[i] = new SchemaDocumentType(d, 0, &schemaAllocator_); + sd_[i] = new SchemaDocumentType(d, uris[i], static_cast(strlen(uris[i])), 0, &schemaAllocator_); MemoryPoolAllocator<>::Free(json); } }; @@ -1099,15 +1105,8 @@ public: } virtual const SchemaDocumentType* GetRemoteDocument(const char* uri, SizeType length) { - const char* uris[kCount] = { - "http://localhost:1234/integer.json", - "http://localhost:1234/subSchemas.json", - "http://localhost:1234/folder/folderInteger.json", - "http://json-schema.org/draft-04/schema" - }; - for (size_t i = 0; i < kCount; i++) - if (strncmp(uri, uris[i], length) == 0 && strlen(uris[i]) == length) + if (typename SchemaDocumentType::URIType(uri, length) == sd_[i]->GetURI()) return sd_[i]; return 0; } @@ -1196,7 +1195,7 @@ TEST(SchemaValidator, TestSuite) { else { for (Value::ConstValueIterator schemaItr = d.Begin(); schemaItr != d.End(); ++schemaItr) { { - SchemaDocumentType schema((*schemaItr)["schema"], &provider, &schemaAllocator); + SchemaDocumentType schema((*schemaItr)["schema"], filenames[i], static_cast(strlen(filenames[i])), &provider, &schemaAllocator); GenericSchemaValidator >, MemoryPoolAllocator<> > validator(schema, &validatorAllocator); const char* description1 = (*schemaItr)["description"].GetString(); const Value& tests = (*schemaItr)["tests"]; @@ -1359,7 +1358,7 @@ TEST(SchemaValidator, Ref_remote) { RemoteSchemaDocumentProvider provider; Document sd; sd.Parse("{\"$ref\": \"http://localhost:1234/subSchemas.json#/integer\"}"); - SchemaDocumentType s(sd, &provider); + SchemaDocumentType s(sd, 0, 0, &provider); typedef GenericSchemaValidator >, MemoryPoolAllocator<> > SchemaValidatorType; typedef GenericPointer > PointerType; INVALIDATE_(s, "null", "/integer", "type", "", SchemaValidatorType, PointerType); -- cgit v1.2.3 From f716c3bfb53d22ef7fab6fb07fcb869ccf19b014 Mon Sep 17 00:00:00 2001 From: Yuri Khan Date: Sat, 16 Sep 2017 21:39:22 +0700 Subject: Report schema violation details (#619) --- include/rapidjson/schema.h | 631 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 532 insertions(+), 99 deletions(-) diff --git a/include/rapidjson/schema.h b/include/rapidjson/schema.h index 5a818542..53062eb8 100644 --- a/include/rapidjson/schema.h +++ b/include/rapidjson/schema.h @@ -17,6 +17,7 @@ #include "document.h" #include "pointer.h" +#include "stringbuffer.h" #include // abs, floor #if !defined(RAPIDJSON_SCHEMA_USE_INTERNALREGEX) @@ -157,6 +158,62 @@ public: virtual void FreeState(void* p) = 0; }; +/////////////////////////////////////////////////////////////////////////////// +// IValidationErrorHandler + +template +class IValidationErrorHandler { +public: + typedef typename SchemaType::Ch Ch; + typedef typename SchemaType::SValue SValue; + + virtual ~IValidationErrorHandler() {} + + virtual void NotMultipleOf(int64_t actual, const SValue& expected) = 0; + virtual void NotMultipleOf(uint64_t actual, const SValue& expected) = 0; + virtual void NotMultipleOf(double actual, const SValue& expected) = 0; + virtual void AboveMaximum(int64_t actual, const SValue& expected, bool exclusive) = 0; + virtual void AboveMaximum(uint64_t actual, const SValue& expected, bool exclusive) = 0; + virtual void AboveMaximum(double actual, const SValue& expected, bool exclusive) = 0; + virtual void BelowMinimum(int64_t actual, const SValue& expected, bool exclusive) = 0; + virtual void BelowMinimum(uint64_t actual, const SValue& expected, bool exclusive) = 0; + virtual void BelowMinimum(double actual, const SValue& expected, bool exclusive) = 0; + + virtual void TooLong(const Ch* str, SizeType length, SizeType expected) = 0; + virtual void TooShort(const Ch* str, SizeType length, SizeType expected) = 0; + virtual void DoesNotMatch(const Ch* str, SizeType length) = 0; + + virtual void DisallowedItem(SizeType index) = 0; + virtual void TooFewItems(SizeType actualCount, SizeType expectedCount) = 0; + virtual void TooManyItems(SizeType actualCount, SizeType expectedCount) = 0; + virtual void DuplicateItems(SizeType index1, SizeType index2) = 0; + + virtual void TooManyProperties(SizeType actualCount, SizeType expectedCount) = 0; + virtual void TooFewProperties(SizeType actualCount, SizeType expectedCount) = 0; + virtual void StartMissingProperties() = 0; + virtual void AddMissingProperty(const SValue& name) = 0; + virtual bool EndMissingProperties() = 0; + virtual void PropertyViolations(ISchemaValidator** subvalidators, SizeType count) = 0; + virtual void DisallowedProperty(const Ch* name, SizeType length) = 0; + + virtual void StartDependencyErrors() = 0; + virtual void StartMissingDependentProperties() = 0; + virtual void AddMissingDependentProperty(const SValue& targetName) = 0; + virtual void EndMissingDependentProperties(const SValue& sourceName) = 0; + virtual void AddDependencySchemaError(const SValue& souceName, ISchemaValidator* subvalidator) = 0; + virtual bool EndDependencyErrors() = 0; + + virtual void DisallowedValue() = 0; + virtual void StartDisallowedType() = 0; + virtual void AddExpectedType(const typename SchemaType::ValueType& expectedType) = 0; + virtual void EndDisallowedType(const typename SchemaType::ValueType& actualType) = 0; + virtual void NotAllOf(ISchemaValidator** subvalidators, SizeType count) = 0; + virtual void NoneOf(ISchemaValidator** subvalidators, SizeType count) = 0; + virtual void NotOneOf(ISchemaValidator** subvalidators, SizeType count) = 0; + virtual void Disallowed() = 0; +}; + + /////////////////////////////////////////////////////////////////////////////// // Hasher @@ -345,6 +402,7 @@ public: typedef SchemaValidationContext Context; typedef Schema SchemaType; typedef GenericValue SValue; + typedef IValidationErrorHandler ErrorHandler; friend class GenericSchemaDocument; Schema(SchemaDocumentType* schemaDocument, const PointerType& p, const ValueType& value, const ValueType& document, AllocatorType* allocator) : @@ -606,7 +664,7 @@ public: return pointer_; } - bool BeginValue(Context& context) const { + bool BeginValue(Context& context, ErrorHandler& eh) const { if (context.inArray) { if (uniqueItems_) context.valueUniqueness = true; @@ -620,8 +678,10 @@ public: context.valueSchema = additionalItemsSchema_; else if (additionalItems_) context.valueSchema = typeless_; - else + else { + eh.DisallowedItem(context.arrayElementIndex); RAPIDJSON_INVALID_KEYWORD_RETURN(GetItemsString()); + } } else context.valueSchema = typeless_; @@ -631,7 +691,7 @@ public: return true; } - RAPIDJSON_FORCEINLINE bool EndValue(Context& context) const { + RAPIDJSON_FORCEINLINE bool EndValue(Context& context, ErrorHandler& eh) const { if (context.patternPropertiesValidatorCount > 0) { bool otherValid = false; SizeType count = context.patternPropertiesValidatorCount; @@ -646,15 +706,21 @@ public: } if (context.objectPatternValidatorType == Context::kPatternValidatorOnly) { - if (!patternValid) + if (!patternValid) { + eh.PropertyViolations(context.patternPropertiesValidators, count); RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString()); + } } else if (context.objectPatternValidatorType == Context::kPatternValidatorWithProperty) { - if (!patternValid || !otherValid) + if (!patternValid || !otherValid) { + eh.PropertyViolations(context.patternPropertiesValidators, count + 1); RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString()); + } } - else if (!patternValid && !otherValid) // kPatternValidatorWithAdditionalProperty) + else if (!patternValid && !otherValid) { // kPatternValidatorWithAdditionalProperty) + eh.PropertyViolations(context.patternPropertiesValidators, count + 1); RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString()); + } } if (enum_) { @@ -662,19 +728,23 @@ public: for (SizeType i = 0; i < enumCount_; i++) if (enum_[i] == h) goto foundEnum; + eh.DisallowedValue(); RAPIDJSON_INVALID_KEYWORD_RETURN(GetEnumString()); foundEnum:; } if (allOf_.schemas) for (SizeType i = allOf_.begin; i < allOf_.begin + allOf_.count; i++) - if (!context.validators[i]->IsValid()) + if (!context.validators[i]->IsValid()) { + eh.NotAllOf(&context.validators[allOf_.begin], allOf_.count); RAPIDJSON_INVALID_KEYWORD_RETURN(GetAllOfString()); + } if (anyOf_.schemas) { for (SizeType i = anyOf_.begin; i < anyOf_.begin + anyOf_.count; i++) if (context.validators[i]->IsValid()) goto foundAny; + eh.NoneOf(&context.validators[anyOf_.begin], anyOf_.count); RAPIDJSON_INVALID_KEYWORD_RETURN(GetAnyOfString()); foundAny:; } @@ -683,96 +753,117 @@ public: bool oneValid = false; for (SizeType i = oneOf_.begin; i < oneOf_.begin + oneOf_.count; i++) if (context.validators[i]->IsValid()) { - if (oneValid) + if (oneValid) { + eh.NotOneOf(&context.validators[oneOf_.begin], oneOf_.count); RAPIDJSON_INVALID_KEYWORD_RETURN(GetOneOfString()); - else + } else oneValid = true; } - if (!oneValid) + if (!oneValid) { + eh.NotOneOf(&context.validators[oneOf_.begin], oneOf_.count); RAPIDJSON_INVALID_KEYWORD_RETURN(GetOneOfString()); + } } - if (not_ && context.validators[notValidatorIndex_]->IsValid()) + if (not_ && context.validators[notValidatorIndex_]->IsValid()) { + eh.Disallowed(); RAPIDJSON_INVALID_KEYWORD_RETURN(GetNotString()); + } return true; } - bool Null(Context& context) const { - if (!(type_ & (1 << kNullSchemaType))) + bool Null(Context& context, ErrorHandler& eh) const { + if (!(type_ & (1 << kNullSchemaType))) { + DisallowedType(eh, GetNullString()); RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); + } return CreateParallelValidator(context); } - bool Bool(Context& context, bool) const { - if (!(type_ & (1 << kBooleanSchemaType))) + bool Bool(Context& context, ErrorHandler& eh, bool) const { + if (!(type_ & (1 << kBooleanSchemaType))) { + DisallowedType(eh, GetBooleanString()); RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); + } return CreateParallelValidator(context); } - bool Int(Context& context, int i) const { - if (!CheckInt(context, i)) + bool Int(Context& context, ErrorHandler& eh, int i) const { + if (!CheckInt(context, eh, i)) return false; return CreateParallelValidator(context); } - bool Uint(Context& context, unsigned u) const { - if (!CheckUint(context, u)) + bool Uint(Context& context, ErrorHandler& eh, unsigned u) const { + if (!CheckUint(context, eh, u)) return false; return CreateParallelValidator(context); } - bool Int64(Context& context, int64_t i) const { - if (!CheckInt(context, i)) + bool Int64(Context& context, ErrorHandler& eh, int64_t i) const { + if (!CheckInt(context, eh, i)) return false; return CreateParallelValidator(context); } - bool Uint64(Context& context, uint64_t u) const { - if (!CheckUint(context, u)) + bool Uint64(Context& context, ErrorHandler& eh, uint64_t u) const { + if (!CheckUint(context, eh, u)) return false; return CreateParallelValidator(context); } - bool Double(Context& context, double d) const { - if (!(type_ & (1 << kNumberSchemaType))) + bool Double(Context& context, ErrorHandler& eh, double d) const { + if (!(type_ & (1 << kNumberSchemaType))) { + DisallowedType(eh, GetNumberString()); RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); + } - if (!minimum_.IsNull() && !CheckDoubleMinimum(context, d)) + if (!minimum_.IsNull() && !CheckDoubleMinimum(context, eh, d)) return false; - if (!maximum_.IsNull() && !CheckDoubleMaximum(context, d)) + if (!maximum_.IsNull() && !CheckDoubleMaximum(context, eh, d)) return false; - if (!multipleOf_.IsNull() && !CheckDoubleMultipleOf(context, d)) + if (!multipleOf_.IsNull() && !CheckDoubleMultipleOf(context, eh, d)) return false; return CreateParallelValidator(context); } - bool String(Context& context, const Ch* str, SizeType length, bool) const { - if (!(type_ & (1 << kStringSchemaType))) + bool String(Context& context, ErrorHandler& eh, const Ch* str, SizeType length, bool) const { + if (!(type_ & (1 << kStringSchemaType))) { + DisallowedType(eh, GetStringString()); RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); + } if (minLength_ != 0 || maxLength_ != SizeType(~0)) { SizeType count; if (internal::CountStringCodePoint(str, length, &count)) { - if (count < minLength_) + if (count < minLength_) { + eh.TooShort(str, length, minLength_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinLengthString()); - if (count > maxLength_) + } + if (count > maxLength_) { + eh.TooLong(str, length, maxLength_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxLengthString()); + } } } - if (pattern_ && !IsPatternMatch(pattern_, str, length)) + if (pattern_ && !IsPatternMatch(pattern_, str, length)) { + eh.DoesNotMatch(str, length); RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternString()); + } return CreateParallelValidator(context); } - bool StartObject(Context& context) const { - if (!(type_ & (1 << kObjectSchemaType))) + bool StartObject(Context& context, ErrorHandler& eh) const { + if (!(type_ & (1 << kObjectSchemaType))) { + DisallowedType(eh, GetObjectString()); RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); + } if (hasDependencies_ || hasRequired_) { context.propertyExist = static_cast(context.factory.MallocState(sizeof(bool) * propertyCount_)); @@ -789,7 +880,7 @@ public: return CreateParallelValidator(context); } - bool Key(Context& context, const Ch* str, SizeType len, bool) const { + bool Key(Context& context, ErrorHandler& eh, const Ch* str, SizeType len, bool) const { if (patternProperties_) { context.patternPropertiesSchemaCount = 0; for (SizeType i = 0; i < patternPropertyCount_; i++) @@ -830,45 +921,65 @@ public: return true; } - if (context.patternPropertiesSchemaCount == 0) // patternProperties are not additional properties + if (context.patternPropertiesSchemaCount == 0) { // patternProperties are not additional properties + eh.DisallowedProperty(str, len); RAPIDJSON_INVALID_KEYWORD_RETURN(GetAdditionalPropertiesString()); + } return true; } - bool EndObject(Context& context, SizeType memberCount) const { - if (hasRequired_) + bool EndObject(Context& context, ErrorHandler& eh, SizeType memberCount) const { + if (hasRequired_) { + eh.StartMissingProperties(); for (SizeType index = 0; index < propertyCount_; index++) - if (properties_[index].required) - if (!context.propertyExist[index]) - RAPIDJSON_INVALID_KEYWORD_RETURN(GetRequiredString()); + if (properties_[index].required && !context.propertyExist[index]) + eh.AddMissingProperty(properties_[index].name); + if (eh.EndMissingProperties()) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetRequiredString()); + } - if (memberCount < minProperties_) + if (memberCount < minProperties_) { + eh.TooFewProperties(memberCount, minProperties_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinPropertiesString()); + } - if (memberCount > maxProperties_) + if (memberCount > maxProperties_) { + eh.TooManyProperties(memberCount, maxProperties_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxPropertiesString()); + } if (hasDependencies_) { - for (SizeType sourceIndex = 0; sourceIndex < propertyCount_; sourceIndex++) + eh.StartDependencyErrors(); + for (SizeType sourceIndex = 0; sourceIndex < propertyCount_; sourceIndex++) { + const Property& source = properties_[sourceIndex]; if (context.propertyExist[sourceIndex]) { - if (properties_[sourceIndex].dependencies) { + if (source.dependencies) { + eh.StartMissingDependentProperties(); for (SizeType targetIndex = 0; targetIndex < propertyCount_; targetIndex++) - if (properties_[sourceIndex].dependencies[targetIndex] && !context.propertyExist[targetIndex]) - RAPIDJSON_INVALID_KEYWORD_RETURN(GetDependenciesString()); + if (source.dependencies[targetIndex] && !context.propertyExist[targetIndex]) + eh.AddMissingDependentProperty(properties_[targetIndex].name); + eh.EndMissingDependentProperties(source.name); + } + else if (source.dependenciesSchema) { + ISchemaValidator* dependenciesValidator = context.validators[source.dependenciesValidatorIndex]; + if (!dependenciesValidator->IsValid()) + eh.AddDependencySchemaError(source.name, dependenciesValidator); } - else if (properties_[sourceIndex].dependenciesSchema) - if (!context.validators[properties_[sourceIndex].dependenciesValidatorIndex]->IsValid()) - RAPIDJSON_INVALID_KEYWORD_RETURN(GetDependenciesString()); } + } + if (eh.EndDependencyErrors()) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetDependenciesString()); } return true; } - bool StartArray(Context& context) const { - if (!(type_ & (1 << kArraySchemaType))) + bool StartArray(Context& context, ErrorHandler& eh) const { + if (!(type_ & (1 << kArraySchemaType))) { + DisallowedType(eh, GetArrayString()); RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); + } context.arrayElementIndex = 0; context.inArray = true; @@ -876,14 +987,18 @@ public: return CreateParallelValidator(context); } - bool EndArray(Context& context, SizeType elementCount) const { + bool EndArray(Context& context, ErrorHandler& eh, SizeType elementCount) const { context.inArray = false; - if (elementCount < minItems_) + if (elementCount < minItems_) { + eh.TooFewItems(elementCount, minItems_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinItemsString()); + } - if (elementCount > maxItems_) + if (elementCount > maxItems_) { + eh.TooManyItems(elementCount, maxItems_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxItemsString()); + } return true; } @@ -1103,104 +1218,144 @@ private: return false; } - bool CheckInt(Context& context, int64_t i) const { - if (!(type_ & ((1 << kIntegerSchemaType) | (1 << kNumberSchemaType)))) + bool CheckInt(Context& context, ErrorHandler& eh, int64_t i) const { + if (!(type_ & ((1 << kIntegerSchemaType) | (1 << kNumberSchemaType)))) { + DisallowedType(eh, GetIntegerString()); RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); + } if (!minimum_.IsNull()) { if (minimum_.IsInt64()) { - if (exclusiveMinimum_ ? i <= minimum_.GetInt64() : i < minimum_.GetInt64()) + if (exclusiveMinimum_ ? i <= minimum_.GetInt64() : i < minimum_.GetInt64()) { + eh.BelowMinimum(i, minimum_, exclusiveMinimum_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); + } } else if (minimum_.IsUint64()) { + eh.BelowMinimum(i, minimum_, exclusiveMinimum_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); // i <= max(int64_t) < minimum.GetUint64() } - else if (!CheckDoubleMinimum(context, static_cast(i))) + else if (!CheckDoubleMinimum(context, eh, static_cast(i))) return false; } if (!maximum_.IsNull()) { if (maximum_.IsInt64()) { - if (exclusiveMaximum_ ? i >= maximum_.GetInt64() : i > maximum_.GetInt64()) + if (exclusiveMaximum_ ? i >= maximum_.GetInt64() : i > maximum_.GetInt64()) { + eh.AboveMaximum(i, maximum_, exclusiveMaximum_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); + } } else if (maximum_.IsUint64()) { } /* do nothing */ // i <= max(int64_t) < maximum_.GetUint64() - else if (!CheckDoubleMaximum(context, static_cast(i))) + else if (!CheckDoubleMaximum(context, eh, static_cast(i))) return false; } if (!multipleOf_.IsNull()) { if (multipleOf_.IsUint64()) { - if (static_cast(i >= 0 ? i : -i) % multipleOf_.GetUint64() != 0) + if (static_cast(i >= 0 ? i : -i) % multipleOf_.GetUint64() != 0) { + eh.NotMultipleOf(i, multipleOf_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString()); + } } - else if (!CheckDoubleMultipleOf(context, static_cast(i))) + else if (!CheckDoubleMultipleOf(context, eh, static_cast(i))) return false; } return true; } - bool CheckUint(Context& context, uint64_t i) const { - if (!(type_ & ((1 << kIntegerSchemaType) | (1 << kNumberSchemaType)))) + bool CheckUint(Context& context, ErrorHandler& eh, uint64_t i) const { + if (!(type_ & ((1 << kIntegerSchemaType) | (1 << kNumberSchemaType)))) { + DisallowedType(eh, GetIntegerString()); RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); + } if (!minimum_.IsNull()) { if (minimum_.IsUint64()) { - if (exclusiveMinimum_ ? i <= minimum_.GetUint64() : i < minimum_.GetUint64()) + if (exclusiveMinimum_ ? i <= minimum_.GetUint64() : i < minimum_.GetUint64()) { + eh.BelowMinimum(i, minimum_, exclusiveMinimum_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); + } } else if (minimum_.IsInt64()) /* do nothing */; // i >= 0 > minimum.Getint64() - else if (!CheckDoubleMinimum(context, static_cast(i))) + else if (!CheckDoubleMinimum(context, eh, static_cast(i))) return false; } if (!maximum_.IsNull()) { if (maximum_.IsUint64()) { - if (exclusiveMaximum_ ? i >= maximum_.GetUint64() : i > maximum_.GetUint64()) + if (exclusiveMaximum_ ? i >= maximum_.GetUint64() : i > maximum_.GetUint64()) { + eh.AboveMaximum(i, maximum_, exclusiveMaximum_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); + } } - else if (maximum_.IsInt64()) + else if (maximum_.IsInt64()) { + eh.AboveMaximum(i, maximum_, exclusiveMaximum_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); // i >= 0 > maximum_ - else if (!CheckDoubleMaximum(context, static_cast(i))) + } + else if (!CheckDoubleMaximum(context, eh, static_cast(i))) return false; } if (!multipleOf_.IsNull()) { if (multipleOf_.IsUint64()) { - if (i % multipleOf_.GetUint64() != 0) + if (i % multipleOf_.GetUint64() != 0) { + eh.NotMultipleOf(i, multipleOf_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString()); + } } - else if (!CheckDoubleMultipleOf(context, static_cast(i))) + else if (!CheckDoubleMultipleOf(context, eh, static_cast(i))) return false; } return true; } - bool CheckDoubleMinimum(Context& context, double d) const { - if (exclusiveMinimum_ ? d <= minimum_.GetDouble() : d < minimum_.GetDouble()) + bool CheckDoubleMinimum(Context& context, ErrorHandler& eh, double d) const { + if (exclusiveMinimum_ ? d <= minimum_.GetDouble() : d < minimum_.GetDouble()) { + eh.BelowMinimum(d, minimum_, exclusiveMinimum_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); + } return true; } - bool CheckDoubleMaximum(Context& context, double d) const { - if (exclusiveMaximum_ ? d >= maximum_.GetDouble() : d > maximum_.GetDouble()) + bool CheckDoubleMaximum(Context& context, ErrorHandler& eh, double d) const { + if (exclusiveMaximum_ ? d >= maximum_.GetDouble() : d > maximum_.GetDouble()) { + eh.AboveMaximum(d, maximum_, exclusiveMaximum_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); + } return true; } - bool CheckDoubleMultipleOf(Context& context, double d) const { + bool CheckDoubleMultipleOf(Context& context, ErrorHandler& eh, double d) const { double a = std::abs(d), b = std::abs(multipleOf_.GetDouble()); double q = std::floor(a / b); double r = a - q * b; - if (r > 0.0) + if (r > 0.0) { + eh.NotMultipleOf(d, multipleOf_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString()); + } return true; } + void DisallowedType(ErrorHandler& eh, const ValueType& actualType) const { + eh.StartDisallowedType(); + + if (type_ & (1 << kNullSchemaType)) eh.AddExpectedType(GetNullString()); + if (type_ & (1 << kBooleanSchemaType)) eh.AddExpectedType(GetBooleanString()); + if (type_ & (1 << kObjectSchemaType)) eh.AddExpectedType(GetObjectString()); + if (type_ & (1 << kArraySchemaType)) eh.AddExpectedType(GetArrayString()); + if (type_ & (1 << kStringSchemaType)) eh.AddExpectedType(GetStringString()); + + if (type_ & (1 << kNumberSchemaType)) eh.AddExpectedType(GetNumberString()); + else if (type_ & (1 << kIntegerSchemaType)) eh.AddExpectedType(GetIntegerString()); + + eh.EndDisallowedType(actualType); + } + struct Property { Property() : schema(), dependenciesSchema(), dependenciesValidatorIndex(), dependencies(), required(false) {} ~Property() { AllocatorType::Free(dependencies); } @@ -1590,13 +1745,17 @@ template < typename StateAllocator = CrtAllocator> class GenericSchemaValidator : public internal::ISchemaStateFactory, - public internal::ISchemaValidator + public internal::ISchemaValidator, + public internal::IValidationErrorHandler { public: typedef typename SchemaDocumentType::SchemaType SchemaType; typedef typename SchemaDocumentType::PointerType PointerType; typedef typename SchemaType::EncodingType EncodingType; + typedef typename SchemaType::SValue SValue; typedef typename EncodingType::Ch Ch; + typedef GenericStringRef StringRefType; + typedef GenericValue ValueType; //! Constructor without output handler. /*! @@ -1618,6 +1777,9 @@ public: schemaStack_(allocator, schemaStackCapacity), documentStack_(allocator, documentStackCapacity), outputHandler_(0), + error_(kObjectType), + currentError_(), + missingDependents_(), valid_(true) #if RAPIDJSON_SCHEMA_VERBOSE , depth_(0) @@ -1646,6 +1808,9 @@ public: schemaStack_(allocator, schemaStackCapacity), documentStack_(allocator, documentStackCapacity), outputHandler_(&outputHandler), + error_(kObjectType), + currentError_(), + missingDependents_(), valid_(true) #if RAPIDJSON_SCHEMA_VERBOSE , depth_(0) @@ -1664,6 +1829,9 @@ public: while (!schemaStack_.Empty()) PopSchema(); documentStack_.Clear(); + error_.SetObject(); + currentError_.SetNull(); + missingDependents_.SetNull(); valid_ = true; } @@ -1671,6 +1839,10 @@ public: // Implementation of ISchemaValidator virtual bool IsValid() const { return valid_; } + //! Gets the error object. + ValueType& GetError() { return error_; } + const ValueType& GetError() const { return error_; } + //! Gets the JSON pointer pointed to the invalid schema. PointerType GetInvalidSchemaPointer() const { return schemaStack_.Empty() ? PointerType() : CurrentSchema().GetPointer(); @@ -1686,6 +1858,186 @@ public: return documentStack_.Empty() ? PointerType() : PointerType(documentStack_.template Bottom(), documentStack_.GetSize() / sizeof(Ch)); } + void NotMultipleOf(int64_t actual, const SValue& expected) { + AddNumberError(SchemaType::GetMultipleOfString(), ValueType(actual).Move(), expected); + } + void NotMultipleOf(uint64_t actual, const SValue& expected) { + AddNumberError(SchemaType::GetMultipleOfString(), ValueType(actual).Move(), expected); + } + void NotMultipleOf(double actual, const SValue& expected) { + AddNumberError(SchemaType::GetMultipleOfString(), ValueType(actual).Move(), expected); + } + void AboveMaximum(int64_t actual, const SValue& expected, bool exclusive) { + AddNumberError(SchemaType::GetMaximumString(), ValueType(actual).Move(), expected, + exclusive ? &SchemaType::GetExclusiveMaximumString : 0); + } + void AboveMaximum(uint64_t actual, const SValue& expected, bool exclusive) { + AddNumberError(SchemaType::GetMaximumString(), ValueType(actual).Move(), expected, + exclusive ? &SchemaType::GetExclusiveMaximumString : 0); + } + void AboveMaximum(double actual, const SValue& expected, bool exclusive) { + AddNumberError(SchemaType::GetMaximumString(), ValueType(actual).Move(), expected, + exclusive ? &SchemaType::GetExclusiveMaximumString : 0); + } + void BelowMinimum(int64_t actual, const SValue& expected, bool exclusive) { + AddNumberError(SchemaType::GetMinimumString(), ValueType(actual).Move(), expected, + exclusive ? &SchemaType::GetExclusiveMinimumString : 0); + } + void BelowMinimum(uint64_t actual, const SValue& expected, bool exclusive) { + AddNumberError(SchemaType::GetMinimumString(), ValueType(actual).Move(), expected, + exclusive ? &SchemaType::GetExclusiveMinimumString : 0); + } + void BelowMinimum(double actual, const SValue& expected, bool exclusive) { + AddNumberError(SchemaType::GetMinimumString(), ValueType(actual).Move(), expected, + exclusive ? &SchemaType::GetExclusiveMinimumString : 0); + } + + void TooLong(const Ch* str, SizeType length, SizeType expected) { + AddNumberError(SchemaType::GetMaxLengthString(), + ValueType(str, length, GetStateAllocator()).Move(), SValue(expected).Move()); + } + void TooShort(const Ch* str, SizeType length, SizeType expected) { + AddNumberError(SchemaType::GetMinLengthString(), + ValueType(str, length, GetStateAllocator()).Move(), SValue(expected).Move()); + } + void DoesNotMatch(const Ch* str, SizeType length) { + currentError_.SetObject(); + currentError_.AddMember(GetActualString(), ValueType(str, length, GetStateAllocator()).Move(), GetStateAllocator()); + AddCurrentError(SchemaType::GetPatternString()); + } + + void DisallowedItem(SizeType index) { + currentError_.SetObject(); + currentError_.AddMember(GetDisallowedString(), ValueType(index).Move(), GetStateAllocator()); + AddCurrentError(SchemaType::GetAdditionalItemsString(), true); + } + void TooFewItems(SizeType actualCount, SizeType expectedCount) { + AddNumberError(SchemaType::GetMinItemsString(), + ValueType(actualCount).Move(), SValue(expectedCount).Move()); + } + void TooManyItems(SizeType actualCount, SizeType expectedCount) { + AddNumberError(SchemaType::GetMaxItemsString(), + ValueType(actualCount).Move(), SValue(expectedCount).Move()); + } + void DuplicateItems(SizeType index1, SizeType index2) { + ValueType duplicates(kArrayType); + duplicates.PushBack(index1, GetStateAllocator()); + duplicates.PushBack(index2, GetStateAllocator()); + currentError_.SetObject(); + currentError_.AddMember(GetDuplicatesString(), duplicates, GetStateAllocator()); + AddCurrentError(SchemaType::GetUniqueItemsString(), true); + } + + void TooManyProperties(SizeType actualCount, SizeType expectedCount) { + AddNumberError(SchemaType::GetMaxPropertiesString(), + ValueType(actualCount).Move(), SValue(expectedCount).Move()); + } + void TooFewProperties(SizeType actualCount, SizeType expectedCount) { + AddNumberError(SchemaType::GetMinPropertiesString(), + ValueType(actualCount).Move(), SValue(expectedCount).Move()); + } + void StartMissingProperties() { + currentError_.SetArray(); + } + void AddMissingProperty(const SValue& name) { + currentError_.PushBack(ValueType(name, GetStateAllocator()).Move(), GetStateAllocator()); + } + bool EndMissingProperties() { + if (currentError_.Empty()) + return false; + ValueType error(kObjectType); + error.AddMember(GetMissingString(), currentError_, GetStateAllocator()); + currentError_ = error; + AddCurrentError(SchemaType::GetRequiredString()); + return true; + } + void PropertyViolations(ISchemaValidator** subvalidators, SizeType count) { + for (SizeType i = 0; i < count; ++i) + MergeError(static_cast(subvalidators[i])->GetError()); + } + void DisallowedProperty(const Ch* name, SizeType length) { + currentError_.SetObject(); + currentError_.AddMember(GetDisallowedString(), ValueType(name, length, GetStateAllocator()).Move(), GetStateAllocator()); + AddCurrentError(SchemaType::GetAdditionalPropertiesString(), true); + } + + void StartDependencyErrors() { + currentError_.SetObject(); + } + void StartMissingDependentProperties() { + missingDependents_.SetArray(); + } + void AddMissingDependentProperty(const SValue& targetName) { + missingDependents_.PushBack(ValueType(targetName, GetStateAllocator()).Move(), GetStateAllocator()); + } + void EndMissingDependentProperties(const SValue& sourceName) { + if (!missingDependents_.Empty()) + currentError_.AddMember(ValueType(sourceName, GetStateAllocator()).Move(), + missingDependents_, GetStateAllocator()); + } + void AddDependencySchemaError(const SValue& sourceName, ISchemaValidator* subvalidator) { + currentError_.AddMember(ValueType(sourceName, GetStateAllocator()).Move(), + static_cast(subvalidator)->GetError(), GetStateAllocator()); + } + bool EndDependencyErrors() { + if (currentError_.ObjectEmpty()) + return false; + ValueType error(kObjectType); + error.AddMember(GetErrorsString(), currentError_, GetStateAllocator()); + currentError_ = error; + AddCurrentError(SchemaType::GetDependenciesString()); + return true; + } + + void DisallowedValue() { + currentError_.SetObject(); + AddCurrentError(SchemaType::GetEnumString()); + } + void StartDisallowedType() { + currentError_.SetArray(); + } + void AddExpectedType(const typename SchemaType::ValueType& expectedType) { + currentError_.PushBack(ValueType(expectedType, GetStateAllocator()).Move(), GetStateAllocator()); + } + void EndDisallowedType(const typename SchemaType::ValueType& actualType) { + ValueType error(kObjectType); + error.AddMember(GetExpectedString(), currentError_, GetStateAllocator()); + error.AddMember(GetActualString(), ValueType(actualType, GetStateAllocator()).Move(), GetStateAllocator()); + currentError_ = error; + AddCurrentError(SchemaType::GetTypeString()); + } + void NotAllOf(ISchemaValidator** subvalidators, SizeType count) { + AddErrorArray(SchemaType::GetAllOfString(), subvalidators, count); + } + void NoneOf(ISchemaValidator** subvalidators, SizeType count) { + AddErrorArray(SchemaType::GetAnyOfString(), subvalidators, count); + } + void NotOneOf(ISchemaValidator** subvalidators, SizeType count) { + AddErrorArray(SchemaType::GetOneOfString(), subvalidators, count); + } + void Disallowed() { + currentError_.SetObject(); + AddCurrentError(SchemaType::GetNotString()); + } + +#define RAPIDJSON_STRING_(name, ...) \ + static const StringRefType& Get##name##String() {\ + static const Ch s[] = { __VA_ARGS__, '\0' };\ + static const StringRefType v(s, static_cast(sizeof(s) / sizeof(Ch) - 1)); \ + return v;\ + } + + RAPIDJSON_STRING_(InstanceRef, 'i', 'n', 's', 't', 'a', 'n', 'c', 'e', 'R', 'e', 'f') + RAPIDJSON_STRING_(SchemaRef, 's', 'c', 'h', 'e', 'm', 'a', 'R', 'e', 'f') + RAPIDJSON_STRING_(Expected, 'e', 'x', 'p', 'e', 'c', 't', 'e', 'd') + RAPIDJSON_STRING_(Actual, 'a', 'c', 't', 'u', 'a', 'l') + RAPIDJSON_STRING_(Disallowed, 'd', 'i', 's', 'a', 'l', 'l', 'o', 'w', 'e', 'd') + RAPIDJSON_STRING_(Missing, 'm', 'i', 's', 's', 'i', 'n', 'g') + RAPIDJSON_STRING_(Errors, 'e', 'r', 'r', 'o', 'r', 's') + RAPIDJSON_STRING_(Duplicates, 'd', 'u', 'p', 'l', 'i', 'c', 'a', 't', 'e', 's') + +#undef RAPIDJSON_STRING_ + #if RAPIDJSON_SCHEMA_VERBOSE #define RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_() \ RAPIDJSON_MULTILINEMACRO_BEGIN\ @@ -1724,20 +2076,20 @@ RAPIDJSON_MULTILINEMACRO_END RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(method, arg2);\ RAPIDJSON_SCHEMA_HANDLE_END_ (method, arg2) - bool Null() { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Null, (CurrentContext() ), ( )); } - bool Bool(bool b) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Bool, (CurrentContext(), b), (b)); } - bool Int(int i) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Int, (CurrentContext(), i), (i)); } - bool Uint(unsigned u) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Uint, (CurrentContext(), u), (u)); } - bool Int64(int64_t i) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Int64, (CurrentContext(), i), (i)); } - bool Uint64(uint64_t u) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Uint64, (CurrentContext(), u), (u)); } - bool Double(double d) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Double, (CurrentContext(), d), (d)); } + bool Null() { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Null, (CurrentContext(), *this), ( )); } + bool Bool(bool b) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Bool, (CurrentContext(), *this, b), (b)); } + bool Int(int i) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Int, (CurrentContext(), *this, i), (i)); } + bool Uint(unsigned u) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Uint, (CurrentContext(), *this, u), (u)); } + bool Int64(int64_t i) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Int64, (CurrentContext(), *this, i), (i)); } + bool Uint64(uint64_t u) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Uint64, (CurrentContext(), *this, u), (u)); } + bool Double(double d) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Double, (CurrentContext(), *this, d), (d)); } bool RawNumber(const Ch* str, SizeType length, bool copy) - { RAPIDJSON_SCHEMA_HANDLE_VALUE_(String, (CurrentContext(), str, length, copy), (str, length, copy)); } + { RAPIDJSON_SCHEMA_HANDLE_VALUE_(String, (CurrentContext(), *this, str, length, copy), (str, length, copy)); } bool String(const Ch* str, SizeType length, bool copy) - { RAPIDJSON_SCHEMA_HANDLE_VALUE_(String, (CurrentContext(), str, length, copy), (str, length, copy)); } + { RAPIDJSON_SCHEMA_HANDLE_VALUE_(String, (CurrentContext(), *this, str, length, copy), (str, length, copy)); } bool StartObject() { - RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartObject, (CurrentContext())); + RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartObject, (CurrentContext(), *this)); RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(StartObject, ()); return valid_ = !outputHandler_ || outputHandler_->StartObject(); } @@ -1745,7 +2097,7 @@ RAPIDJSON_MULTILINEMACRO_END bool Key(const Ch* str, SizeType len, bool copy) { if (!valid_) return false; AppendToken(str, len); - if (!CurrentSchema().Key(CurrentContext(), str, len, copy)) return valid_ = false; + if (!CurrentSchema().Key(CurrentContext(), *this, str, len, copy)) return valid_ = false; RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(Key, (str, len, copy)); return valid_ = !outputHandler_ || outputHandler_->Key(str, len, copy); } @@ -1753,12 +2105,12 @@ RAPIDJSON_MULTILINEMACRO_END bool EndObject(SizeType memberCount) { if (!valid_) return false; RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(EndObject, (memberCount)); - if (!CurrentSchema().EndObject(CurrentContext(), memberCount)) return valid_ = false; + if (!CurrentSchema().EndObject(CurrentContext(), *this, memberCount)) return valid_ = false; RAPIDJSON_SCHEMA_HANDLE_END_(EndObject, (memberCount)); } bool StartArray() { - RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartArray, (CurrentContext())); + RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartArray, (CurrentContext(), *this)); RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(StartArray, ()); return valid_ = !outputHandler_ || outputHandler_->StartArray(); } @@ -1766,7 +2118,7 @@ RAPIDJSON_MULTILINEMACRO_END bool EndArray(SizeType elementCount) { if (!valid_) return false; RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(EndArray, (elementCount)); - if (!CurrentSchema().EndArray(CurrentContext(), elementCount)) return valid_ = false; + if (!CurrentSchema().EndArray(CurrentContext(), *this, elementCount)) return valid_ = false; RAPIDJSON_SCHEMA_HANDLE_END_(EndArray, (elementCount)); } @@ -1777,7 +2129,7 @@ RAPIDJSON_MULTILINEMACRO_END // Implementation of ISchemaStateFactory virtual ISchemaValidator* CreateSchemaValidator(const SchemaType& root) { - return new (GetStateAllocator().Malloc(sizeof(GenericSchemaValidator))) GenericSchemaValidator(*schemaDocument_, root, + return new (GetStateAllocator().Malloc(sizeof(GenericSchemaValidator))) GenericSchemaValidator(*schemaDocument_, root, documentStack_.template Bottom(), documentStack_.GetSize(), #if RAPIDJSON_SCHEMA_VERBOSE depth_ + 1, #endif @@ -1820,6 +2172,7 @@ private: GenericSchemaValidator( const SchemaDocumentType& schemaDocument, const SchemaType& root, + const char* basePath, size_t basePathSize, #if RAPIDJSON_SCHEMA_VERBOSE unsigned depth, #endif @@ -1834,11 +2187,16 @@ private: schemaStack_(allocator, schemaStackCapacity), documentStack_(allocator, documentStackCapacity), outputHandler_(0), + error_(kObjectType), + currentError_(), + missingDependents_(), valid_(true) #if RAPIDJSON_SCHEMA_VERBOSE , depth_(depth) #endif { + if (basePath && basePathSize) + memcpy(documentStack_.template Push(basePathSize), basePath, basePathSize); } StateAllocator& GetStateAllocator() { @@ -1854,7 +2212,7 @@ private: if (CurrentContext().inArray) internal::TokenHelper, Ch>::AppendIndexToken(documentStack_, CurrentContext().arrayElementIndex); - if (!CurrentSchema().BeginValue(CurrentContext())) + if (!CurrentSchema().BeginValue(CurrentContext(), *this)) return false; SizeType count = CurrentContext().patternPropertiesSchemaCount; @@ -1879,7 +2237,7 @@ private: } bool EndValue() { - if (!CurrentSchema().EndValue(CurrentContext())) + if (!CurrentSchema().EndValue(CurrentContext(), *this)) return false; #if RAPIDJSON_SCHEMA_VERBOSE @@ -1902,8 +2260,10 @@ private: if (!a) CurrentContext().arrayElementHashCodes = a = new (GetStateAllocator().Malloc(sizeof(HashCodeArray))) HashCodeArray(kArrayType); for (typename HashCodeArray::ConstValueIterator itr = a->Begin(); itr != a->End(); ++itr) - if (itr->GetUint64() == h) + if (itr->GetUint64() == h) { + DuplicateItems(static_cast(itr - a->Begin()), a->Size()); RAPIDJSON_INVALID_KEYWORD_RETURN(SchemaType::GetUniqueItemsString()); + } a->PushBack(h, GetStateAllocator()); } } @@ -1943,6 +2303,70 @@ private: c->~Context(); } + void AddErrorLocation(ValueType& result, bool parent) { + GenericStringBuffer sb; + PointerType instancePointer = GetInvalidDocumentPointer(); + ((parent && instancePointer.GetTokenCount() > 0) + ? PointerType(instancePointer.GetTokens(), instancePointer.GetTokenCount() - 1) + : instancePointer).StringifyUriFragment(sb); + ValueType instanceRef(sb.GetString(), static_cast(sb.GetSize() / sizeof(Ch)), + GetStateAllocator()); + result.AddMember(GetInstanceRefString(), instanceRef, GetStateAllocator()); + sb.Clear(); + memcpy(sb.Push(CurrentSchema().GetURI().GetStringLength()), + CurrentSchema().GetURI().GetString(), + CurrentSchema().GetURI().GetStringLength() * sizeof(Ch)); + GetInvalidSchemaPointer().StringifyUriFragment(sb); + ValueType schemaRef(sb.GetString(), static_cast(sb.GetSize() / sizeof(Ch)), + GetStateAllocator()); + result.AddMember(GetSchemaRefString(), schemaRef, GetStateAllocator()); + } + + void AddError(ValueType& keyword, ValueType& error) { + typename ValueType::MemberIterator member = error_.FindMember(keyword); + if (member == error_.MemberEnd()) + error_.AddMember(keyword, error, GetStateAllocator()); + else { + if (member->value.IsObject()) { + ValueType errors(kArrayType); + errors.PushBack(member->value, GetStateAllocator()); + member->value = errors; + } + member->value.PushBack(error, GetStateAllocator()); + } + } + + void AddCurrentError(const typename SchemaType::ValueType& keyword, bool parent = false) { + AddErrorLocation(currentError_, parent); + AddError(ValueType(keyword, GetStateAllocator(), false).Move(), currentError_); + } + + void MergeError(ValueType& other) { + for (typename ValueType::MemberIterator it = other.MemberBegin(), end = other.MemberEnd(); it != end; ++it) { + AddError(it->name, it->value); + } + } + + void AddNumberError(const typename SchemaType::ValueType& keyword, ValueType& actual, const SValue& expected, + const typename SchemaType::ValueType& (*exclusive)() = 0) { + currentError_.SetObject(); + currentError_.AddMember(GetActualString(), actual, GetStateAllocator()); + currentError_.AddMember(GetExpectedString(), ValueType(expected, GetStateAllocator()).Move(), GetStateAllocator()); + if (exclusive) + currentError_.AddMember(ValueType(exclusive(), GetStateAllocator()).Move(), true, GetStateAllocator()); + AddCurrentError(keyword); + } + + void AddErrorArray(const typename SchemaType::ValueType& keyword, + ISchemaValidator** subvalidators, SizeType count) { + ValueType errors(kArrayType); + for (SizeType i = 0; i < count; ++i) + errors.PushBack(static_cast(subvalidators[i])->GetError(), GetStateAllocator()); + currentError_.SetObject(); + currentError_.AddMember(GetErrorsString(), errors, GetStateAllocator()); + AddCurrentError(keyword); + } + const SchemaType& CurrentSchema() const { return *schemaStack_.template Top()->schema; } Context& CurrentContext() { return *schemaStack_.template Top(); } const Context& CurrentContext() const { return *schemaStack_.template Top(); } @@ -1956,6 +2380,9 @@ private: internal::Stack schemaStack_; //!< stack to store the current path of schema (BaseSchemaType *) internal::Stack documentStack_; //!< stack to store the current path of validating document (Ch) OutputHandler* outputHandler_; + ValueType error_; + ValueType currentError_; + ValueType missingDependents_; bool valid_; #if RAPIDJSON_SCHEMA_VERBOSE unsigned depth_; @@ -1987,13 +2414,14 @@ class SchemaValidatingReader { public: typedef typename SchemaDocumentType::PointerType PointerType; typedef typename InputStream::Ch Ch; + typedef GenericValue ValueType; //! Constructor /*! \param is Input stream. \param sd Schema document. */ - SchemaValidatingReader(InputStream& is, const SchemaDocumentType& sd) : is_(is), sd_(sd), invalidSchemaKeyword_(), isValid_(true) {} + SchemaValidatingReader(InputStream& is, const SchemaDocumentType& sd) : is_(is), sd_(sd), invalidSchemaKeyword_(), error_(kObjectType), isValid_(true) {} template bool operator()(Handler& handler) { @@ -2006,11 +2434,13 @@ public: invalidSchemaPointer_ = PointerType(); invalidSchemaKeyword_ = 0; invalidDocumentPointer_ = PointerType(); + error_.SetObject(); } else { invalidSchemaPointer_ = validator.GetInvalidSchemaPointer(); invalidSchemaKeyword_ = validator.GetInvalidSchemaKeyword(); invalidDocumentPointer_ = validator.GetInvalidDocumentPointer(); + error_.CopyFrom(validator.GetError(), allocator_); } return parseResult_; @@ -2021,6 +2451,7 @@ public: const PointerType& GetInvalidSchemaPointer() const { return invalidSchemaPointer_; } const Ch* GetInvalidSchemaKeyword() const { return invalidSchemaKeyword_; } const PointerType& GetInvalidDocumentPointer() const { return invalidDocumentPointer_; } + const ValueType& GetError() const { return error_; } private: InputStream& is_; @@ -2030,6 +2461,8 @@ private: PointerType invalidSchemaPointer_; const Ch* invalidSchemaKeyword_; PointerType invalidDocumentPointer_; + StackAllocator allocator_; + ValueType error_; bool isValid_; }; -- cgit v1.2.3 From 0566716802964da289a60fa252e77e767b433747 Mon Sep 17 00:00:00 2001 From: Yuri Khan Date: Mon, 18 Sep 2017 00:06:07 +0700 Subject: Extend schema validation tests to compare error object --- test/unittest/schematest.cpp | 954 +++++++++++++++++++++++++++++++++++++------ 1 file changed, 825 insertions(+), 129 deletions(-) diff --git a/test/unittest/schematest.cpp b/test/unittest/schematest.cpp index 34436ac3..5bf39f88 100644 --- a/test/unittest/schematest.cpp +++ b/test/unittest/schematest.cpp @@ -119,15 +119,19 @@ TEST(SchemaValidator, Hasher) { sb.Clear();\ validator.GetInvalidDocumentPointer().StringifyUriFragment(sb);\ printf("Invalid document: %s\n", sb.GetString());\ + sb.Clear();\ + Writer w(sb);\ + validator.GetError().Accept(w);\ + printf("Validation error: %s\n", sb.GetString());\ }\ } -#define INVALIDATE(schema, json, invalidSchemaPointer, invalidSchemaKeyword, invalidDocumentPointer) \ +#define INVALIDATE(schema, json, invalidSchemaPointer, invalidSchemaKeyword, invalidDocumentPointer, error) \ {\ - INVALIDATE_(schema, json, invalidSchemaPointer, invalidSchemaKeyword, invalidDocumentPointer, SchemaValidator, Pointer) \ + INVALIDATE_(schema, json, invalidSchemaPointer, invalidSchemaKeyword, invalidDocumentPointer, error, SchemaValidator, Pointer) \ } -#define INVALIDATE_(schema, json, invalidSchemaPointer, invalidSchemaKeyword, invalidDocumentPointer,\ +#define INVALIDATE_(schema, json, invalidSchemaPointer, invalidSchemaKeyword, invalidDocumentPointer, error, \ SchemaValidatorType, PointerType) \ {\ SchemaValidatorType validator(schema);\ @@ -154,6 +158,15 @@ TEST(SchemaValidator, Hasher) { printf("GetInvalidDocumentPointer() Expected: %s Actual: %s\n", invalidDocumentPointer, sb.GetString());\ ADD_FAILURE();\ }\ + Document e;\ + e.Parse(error);\ + if (validator.GetError() != e) {\ + StringBuffer sb;\ + Writer w(sb);\ + validator.GetError().Accept(w);\ + printf("GetError() Expected: %s Actual: %s\n", error, sb.GetString());\ + ADD_FAILURE();\ + }\ } TEST(SchemaValidator, Typeless) { @@ -173,7 +186,11 @@ TEST(SchemaValidator, MultiType) { VALIDATE(s, "42", true); VALIDATE(s, "\"Life, the universe, and everything\"", true); - INVALIDATE(s, "[\"Life\", \"the universe\", \"and everything\"]", "", "type", ""); + INVALIDATE(s, "[\"Life\", \"the universe\", \"and everything\"]", "", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": [\"string\", \"number\"], \"actual\": \"array\"" + "}}"); } TEST(SchemaValidator, Enum_Typed) { @@ -182,7 +199,8 @@ TEST(SchemaValidator, Enum_Typed) { SchemaDocument s(sd); VALIDATE(s, "\"red\"", true); - INVALIDATE(s, "\"blue\"", "", "enum", ""); + INVALIDATE(s, "\"blue\"", "", "enum", "", + "{ \"enum\": { \"instanceRef\": \"#\", \"schemaRef\": \"#\" }}"); } TEST(SchemaValidator, Enum_Typless) { @@ -193,7 +211,8 @@ TEST(SchemaValidator, Enum_Typless) { VALIDATE(s, "\"red\"", true); VALIDATE(s, "null", true); VALIDATE(s, "42", true); - INVALIDATE(s, "0", "", "enum", ""); + INVALIDATE(s, "0", "", "enum", "", + "{ \"enum\": { \"instanceRef\": \"#\", \"schemaRef\": \"#\" }}"); } TEST(SchemaValidator, Enum_InvalidType) { @@ -202,7 +221,11 @@ TEST(SchemaValidator, Enum_InvalidType) { SchemaDocument s(sd); VALIDATE(s, "\"red\"", true); - INVALIDATE(s, "null", "", "type", ""); + INVALIDATE(s, "null", "", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": [\"string\"], \"actual\": \"null\"" + "}}"); } TEST(SchemaValidator, AllOf) { @@ -212,7 +235,17 @@ TEST(SchemaValidator, AllOf) { SchemaDocument s(sd); VALIDATE(s, "\"ok\"", true); - INVALIDATE(s, "\"too long\"", "", "allOf", ""); + INVALIDATE(s, "\"too long\"", "", "allOf", "", + "{ \"allOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"errors\": [" + " {}," + " { \"maxLength\": { " + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/1\", " + " \"expected\": 5, \"actual\": \"too long\"" + " }}" + " ]" + "}}"); } { Document sd; @@ -220,7 +253,16 @@ TEST(SchemaValidator, AllOf) { SchemaDocument s(sd); VALIDATE(s, "\"No way\"", false); - INVALIDATE(s, "-1", "", "allOf", ""); + INVALIDATE(s, "-1", "", "allOf", "", + "{ \"allOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"errors\": [" + " { \"type\": { \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/0\"," + " \"expected\": [\"string\"], \"actual\": \"integer\"" + " }}," + " {}" + " ]" + "}}"); } } @@ -231,7 +273,20 @@ TEST(SchemaValidator, AnyOf) { VALIDATE(s, "\"Yes\"", true); VALIDATE(s, "42", true); - INVALIDATE(s, "{ \"Not a\": \"string or number\" }", "", "anyOf", ""); + INVALIDATE(s, "{ \"Not a\": \"string or number\" }", "", "anyOf", "", + "{ \"anyOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\", " + " \"errors\": [" + " { \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/anyOf/0\"," + " \"expected\": [\"string\"], \"actual\": \"object\"" + " }}," + " { \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/anyOf/1\"," + " \"expected\": [\"number\"], \"actual\": \"object\"" + " }}" + " ]" + "}}"); } TEST(SchemaValidator, OneOf) { @@ -241,8 +296,22 @@ TEST(SchemaValidator, OneOf) { VALIDATE(s, "10", true); VALIDATE(s, "9", true); - INVALIDATE(s, "2", "", "oneOf", ""); - INVALIDATE(s, "15", "", "oneOf", ""); + INVALIDATE(s, "2", "", "oneOf", "", + "{ \"oneOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"errors\": [" + " { \"multipleOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/oneOf/0\"," + " \"expected\": 5, \"actual\": 2" + " }}," + " { \"multipleOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/oneOf/1\"," + " \"expected\": 3, \"actual\": 2" + " }}" + " ]" + "}}"); + INVALIDATE(s, "15", "", "oneOf", "", + "{ \"oneOf\": { \"instanceRef\": \"#\", \"schemaRef\": \"#\", \"errors\": [{}, {}]}}"); } TEST(SchemaValidator, Not) { @@ -252,7 +321,8 @@ TEST(SchemaValidator, Not) { VALIDATE(s, "42", true); VALIDATE(s, "{ \"key\": \"value\" }", true); - INVALIDATE(s, "\"I am a string\"", "", "not", ""); + INVALIDATE(s, "\"I am a string\"", "", "not", "", + "{ \"not\": { \"instanceRef\": \"#\", \"schemaRef\": \"#\" }}"); } TEST(SchemaValidator, Ref) { @@ -316,7 +386,17 @@ TEST(SchemaValidator, Ref_AllOf) { "}"); SchemaDocument s(sd); - INVALIDATE(s, "{\"shipping_address\": {\"street_address\": \"1600 Pennsylvania Avenue NW\", \"city\": \"Washington\", \"state\": \"DC\"} }", "/properties/shipping_address", "allOf", "/shipping_address"); + INVALIDATE(s, "{\"shipping_address\": {\"street_address\": \"1600 Pennsylvania Avenue NW\", \"city\": \"Washington\", \"state\": \"DC\"} }", "/properties/shipping_address", "allOf", "/shipping_address", + "{ \"allOf\": {" + " \"instanceRef\": \"#/shipping_address\"," + " \"schemaRef\": \"#/properties/shipping_address\"," + " \"errors\": [" + " {}," + " { \"required\": {" + " \"instanceRef\": \"#/shipping_address\"," + " \"schemaRef\": \"#/properties/shipping_address/allOf/1\"," + " \"missing\": [\"type\"]" + "}} ] }}"); VALIDATE(s, "{\"shipping_address\": {\"street_address\": \"1600 Pennsylvania Avenue NW\", \"city\": \"Washington\", \"state\": \"DC\", \"type\": \"business\"} }", true); } @@ -326,11 +406,31 @@ TEST(SchemaValidator, String) { SchemaDocument s(sd); VALIDATE(s, "\"I'm a string\"", true); - INVALIDATE(s, "42", "", "type", ""); - INVALIDATE(s, "2147483648", "", "type", ""); // 2^31 can only be fit in unsigned - INVALIDATE(s, "-2147483649", "", "type", ""); // -2^31 - 1 can only be fit in int64_t - INVALIDATE(s, "4294967296", "", "type", ""); // 2^32 can only be fit in int64_t - INVALIDATE(s, "3.1415926", "", "type", ""); + INVALIDATE(s, "42", "", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": [\"string\"], \"actual\": \"integer\"" + "}}"); + INVALIDATE(s, "2147483648", "", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": [\"string\"], \"actual\": \"integer\"" + "}}"); // 2^31 can only be fit in unsigned + INVALIDATE(s, "-2147483649", "", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": [\"string\"], \"actual\": \"integer\"" + "}}"); // -2^31 - 1 can only be fit in int64_t + INVALIDATE(s, "4294967296", "", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": [\"string\"], \"actual\": \"integer\"" + "}}"); // 2^32 can only be fit in int64_t + INVALIDATE(s, "3.1415926", "", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": [\"string\"], \"actual\": \"number\"" + "}}"); } TEST(SchemaValidator, String_LengthRange) { @@ -338,10 +438,18 @@ TEST(SchemaValidator, String_LengthRange) { sd.Parse("{\"type\":\"string\",\"minLength\":2,\"maxLength\":3}"); SchemaDocument s(sd); - INVALIDATE(s, "\"A\"", "", "minLength", ""); + INVALIDATE(s, "\"A\"", "", "minLength", "", + "{ \"minLength\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 2, \"actual\": \"A\"" + "}}"); VALIDATE(s, "\"AB\"", true); VALIDATE(s, "\"ABC\"", true); - INVALIDATE(s, "\"ABCD\"", "", "maxLength", ""); + INVALIDATE(s, "\"ABCD\"", "", "maxLength", "", + "{ \"maxLength\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 3, \"actual\": \"ABCD\"" + "}}"); } #if RAPIDJSON_SCHEMA_HAS_REGEX @@ -352,8 +460,16 @@ TEST(SchemaValidator, String_Pattern) { VALIDATE(s, "\"555-1212\"", true); VALIDATE(s, "\"(888)555-1212\"", true); - INVALIDATE(s, "\"(888)555-1212 ext. 532\"", "", "pattern", ""); - INVALIDATE(s, "\"(800)FLOWERS\"", "", "pattern", ""); + INVALIDATE(s, "\"(888)555-1212 ext. 532\"", "", "pattern", "", + "{ \"pattern\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"actual\": \"(888)555-1212 ext. 532\"" + "}}"); + INVALIDATE(s, "\"(800)FLOWERS\"", "", "pattern", "", + "{ \"pattern\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"actual\": \"(800)FLOWERS\"" + "}}"); } TEST(SchemaValidator, String_Pattern_Invalid) { @@ -378,8 +494,16 @@ TEST(SchemaValidator, Integer) { VALIDATE(s, "-2147483649", true); // -2^31 - 1 can only be fit in int64_t VALIDATE(s, "2147483648", true); // 2^31 can only be fit in unsigned VALIDATE(s, "4294967296", true); // 2^32 can only be fit in int64_t - INVALIDATE(s, "3.1415926", "", "type", ""); - INVALIDATE(s, "\"42\"", "", "type", ""); + INVALIDATE(s, "3.1415926", "", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": [\"integer\"], \"actual\": \"number\"" + "}}"); + INVALIDATE(s, "\"42\"", "", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": [\"integer\"], \"actual\": \"string\"" + "}}"); } TEST(SchemaValidator, Integer_Range) { @@ -387,12 +511,24 @@ TEST(SchemaValidator, Integer_Range) { sd.Parse("{\"type\":\"integer\",\"minimum\":0,\"maximum\":100,\"exclusiveMaximum\":true}"); SchemaDocument s(sd); - INVALIDATE(s, "-1", "", "minimum", ""); + INVALIDATE(s, "-1", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 0, \"actual\": -1" + "}}"); VALIDATE(s, "0", true); VALIDATE(s, "10", true); VALIDATE(s, "99", true); - INVALIDATE(s, "100", "", "maximum", ""); - INVALIDATE(s, "101", "", "maximum", ""); + INVALIDATE(s, "100", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 100, \"exclusiveMaximum\": true, \"actual\": 100" + "}}"); + INVALIDATE(s, "101", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 100, \"exclusiveMaximum\": true, \"actual\": 101" + "}}"); } TEST(SchemaValidator, Integer_Range64Boundary) { @@ -400,7 +536,11 @@ TEST(SchemaValidator, Integer_Range64Boundary) { sd.Parse("{\"type\":\"integer\",\"minimum\":-9223372036854775807,\"maximum\":9223372036854775806}"); SchemaDocument s(sd); - INVALIDATE(s, "-9223372036854775808", "", "minimum", ""); + INVALIDATE(s, "-9223372036854775808", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": -9223372036854775807, \"actual\": -9223372036854775808" + "}}"); VALIDATE(s, "-9223372036854775807", true); VALIDATE(s, "-2147483648", true); // int min VALIDATE(s, "0", true); @@ -408,8 +548,16 @@ TEST(SchemaValidator, Integer_Range64Boundary) { VALIDATE(s, "2147483648", true); // unsigned first VALIDATE(s, "4294967295", true); // unsigned max VALIDATE(s, "9223372036854775806", true); - INVALIDATE(s, "9223372036854775807", "", "maximum", ""); - INVALIDATE(s, "18446744073709551615", "", "maximum", ""); // uint64_t max + INVALIDATE(s, "9223372036854775807", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 9223372036854775806, \"actual\": 9223372036854775807" + "}}"); + INVALIDATE(s, "18446744073709551615", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 9223372036854775806, \"actual\": 18446744073709551615" + "}}"); // uint64_t max } TEST(SchemaValidator, Integer_RangeU64Boundary) { @@ -417,16 +565,48 @@ TEST(SchemaValidator, Integer_RangeU64Boundary) { sd.Parse("{\"type\":\"integer\",\"minimum\":9223372036854775808,\"maximum\":18446744073709551614}"); SchemaDocument s(sd); - INVALIDATE(s, "-9223372036854775808", "", "minimum", ""); - INVALIDATE(s, "9223372036854775807", "", "minimum", ""); - INVALIDATE(s, "-2147483648", "", "minimum", ""); // int min - INVALIDATE(s, "0", "", "minimum", ""); - INVALIDATE(s, "2147483647", "", "minimum", ""); // int max - INVALIDATE(s, "2147483648", "", "minimum", ""); // unsigned first - INVALIDATE(s, "4294967295", "", "minimum", ""); // unsigned max + INVALIDATE(s, "-9223372036854775808", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 9223372036854775808, \"actual\": -9223372036854775808" + "}}"); + INVALIDATE(s, "9223372036854775807", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 9223372036854775808, \"actual\": 9223372036854775807" + "}}"); + INVALIDATE(s, "-2147483648", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 9223372036854775808, \"actual\": -2147483648" + "}}"); // int min + INVALIDATE(s, "0", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 9223372036854775808, \"actual\": 0" + "}}"); + INVALIDATE(s, "2147483647", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 9223372036854775808, \"actual\": 2147483647" + "}}"); // int max + INVALIDATE(s, "2147483648", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 9223372036854775808, \"actual\": 2147483648" + "}}"); // unsigned first + INVALIDATE(s, "4294967295", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 9223372036854775808, \"actual\": 4294967295" + "}}"); // unsigned max VALIDATE(s, "9223372036854775808", true); VALIDATE(s, "18446744073709551614", true); - INVALIDATE(s, "18446744073709551615", "", "maximum", ""); + INVALIDATE(s, "18446744073709551615", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 18446744073709551614, \"actual\": 18446744073709551615" + "}}"); } TEST(SchemaValidator, Integer_Range64BoundaryExclusive) { @@ -434,10 +614,20 @@ TEST(SchemaValidator, Integer_Range64BoundaryExclusive) { sd.Parse("{\"type\":\"integer\",\"minimum\":-9223372036854775808,\"maximum\":18446744073709551615,\"exclusiveMinimum\":true,\"exclusiveMaximum\":true}"); SchemaDocument s(sd); - INVALIDATE(s, "-9223372036854775808", "", "minimum", ""); + INVALIDATE(s, "-9223372036854775808", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": -9223372036854775808, \"exclusiveMinimum\": true, " + " \"actual\": -9223372036854775808" + "}}"); VALIDATE(s, "-9223372036854775807", true); VALIDATE(s, "18446744073709551614", true); - INVALIDATE(s, "18446744073709551615", "", "maximum", ""); + INVALIDATE(s, "18446744073709551615", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 18446744073709551615, \"exclusiveMaximum\": true, " + " \"actual\": 18446744073709551615" + "}}"); } TEST(SchemaValidator, Integer_MultipleOf) { @@ -449,8 +639,16 @@ TEST(SchemaValidator, Integer_MultipleOf) { VALIDATE(s, "10", true); VALIDATE(s, "-10", true); VALIDATE(s, "20", true); - INVALIDATE(s, "23", "", "multipleOf", ""); - INVALIDATE(s, "-23", "", "multipleOf", ""); + INVALIDATE(s, "23", "", "multipleOf", "", + "{ \"multipleOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 10, \"actual\": 23" + "}}"); + INVALIDATE(s, "-23", "", "multipleOf", "", + "{ \"multipleOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 10, \"actual\": -23" + "}}"); } TEST(SchemaValidator, Integer_MultipleOf64Boundary) { @@ -460,7 +658,11 @@ TEST(SchemaValidator, Integer_MultipleOf64Boundary) { VALIDATE(s, "0", true); VALIDATE(s, "18446744073709551615", true); - INVALIDATE(s, "18446744073709551614", "", "multipleOf", ""); + INVALIDATE(s, "18446744073709551614", "", "multipleOf", "", + "{ \"multipleOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 18446744073709551615, \"actual\": 18446744073709551614" + "}}"); } TEST(SchemaValidator, Number_Range) { @@ -468,15 +670,31 @@ TEST(SchemaValidator, Number_Range) { sd.Parse("{\"type\":\"number\",\"minimum\":0,\"maximum\":100,\"exclusiveMaximum\":true}"); SchemaDocument s(sd); - INVALIDATE(s, "-1", "", "minimum", ""); + INVALIDATE(s, "-1", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 0, \"actual\": -1" + "}}"); VALIDATE(s, "0", true); VALIDATE(s, "0.1", true); VALIDATE(s, "10", true); VALIDATE(s, "99", true); VALIDATE(s, "99.9", true); - INVALIDATE(s, "100", "", "maximum", ""); - INVALIDATE(s, "100.0", "", "maximum", ""); - INVALIDATE(s, "101.5", "", "maximum", ""); + INVALIDATE(s, "100", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 100, \"exclusiveMaximum\": true, \"actual\": 100" + "}}"); + INVALIDATE(s, "100.0", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 100, \"exclusiveMaximum\": true, \"actual\": 100.0" + "}}"); + INVALIDATE(s, "101.5", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 100, \"exclusiveMaximum\": true, \"actual\": 101.5" + "}}"); } TEST(SchemaValidator, Number_RangeInt) { @@ -484,19 +702,63 @@ TEST(SchemaValidator, Number_RangeInt) { sd.Parse("{\"type\":\"number\",\"minimum\":-100,\"maximum\":-1,\"exclusiveMaximum\":true}"); SchemaDocument s(sd); - INVALIDATE(s, "-101", "", "minimum", ""); - INVALIDATE(s, "-100.1", "", "minimum", ""); + INVALIDATE(s, "-101", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": -100, \"actual\": -101" + "}}"); + INVALIDATE(s, "-100.1", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": -100, \"actual\": -100.1" + "}}"); VALIDATE(s, "-100", true); VALIDATE(s, "-2", true); - INVALIDATE(s, "-1", "", "maximum", ""); - INVALIDATE(s, "-0.9", "", "maximum", ""); - INVALIDATE(s, "0", "", "maximum", ""); - INVALIDATE(s, "2147483647", "", "maximum", ""); // int max - INVALIDATE(s, "2147483648", "", "maximum", ""); // unsigned first - INVALIDATE(s, "4294967295", "", "maximum", ""); // unsigned max - INVALIDATE(s, "9223372036854775808", "", "maximum", ""); - INVALIDATE(s, "18446744073709551614", "", "maximum", ""); - INVALIDATE(s, "18446744073709551615", "", "maximum", ""); + INVALIDATE(s, "-1", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": -1, \"exclusiveMaximum\": true, \"actual\": -1" + "}}"); + INVALIDATE(s, "-0.9", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": -1, \"exclusiveMaximum\": true, \"actual\": -0.9" + "}}"); + INVALIDATE(s, "0", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": -1, \"exclusiveMaximum\": true, \"actual\": 0" + "}}"); + INVALIDATE(s, "2147483647", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": -1, \"exclusiveMaximum\": true, \"actual\": 2147483647" + "}}"); // int max + INVALIDATE(s, "2147483648", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": -1, \"exclusiveMaximum\": true, \"actual\": 2147483648" + "}}"); // unsigned first + INVALIDATE(s, "4294967295", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": -1, \"exclusiveMaximum\": true, \"actual\": 4294967295" + "}}"); // unsigned max + INVALIDATE(s, "9223372036854775808", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": -1, \"exclusiveMaximum\": true, \"actual\": 9223372036854775808" + "}}"); + INVALIDATE(s, "18446744073709551614", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": -1, \"exclusiveMaximum\": true, \"actual\": 18446744073709551614" + "}}"); + INVALIDATE(s, "18446744073709551615", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": -1, \"exclusiveMaximum\": true, \"actual\": 18446744073709551615" + "}}"); } TEST(SchemaValidator, Number_RangeDouble) { @@ -504,23 +766,75 @@ TEST(SchemaValidator, Number_RangeDouble) { sd.Parse("{\"type\":\"number\",\"minimum\":0.1,\"maximum\":100.1,\"exclusiveMaximum\":true}"); SchemaDocument s(sd); - INVALIDATE(s, "-9223372036854775808", "", "minimum", ""); - INVALIDATE(s, "-2147483648", "", "minimum", ""); // int min - INVALIDATE(s, "-1", "", "minimum", ""); + INVALIDATE(s, "-9223372036854775808", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 0.1, \"actual\": -9223372036854775808" + "}}"); + INVALIDATE(s, "-2147483648", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 0.1, \"actual\": -2147483648" + "}}"); // int min + INVALIDATE(s, "-1", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 0.1, \"actual\": -1" + "}}"); VALIDATE(s, "0.1", true); VALIDATE(s, "10", true); VALIDATE(s, "99", true); VALIDATE(s, "100", true); - INVALIDATE(s, "101", "", "maximum", ""); - INVALIDATE(s, "101.5", "", "maximum", ""); - INVALIDATE(s, "18446744073709551614", "", "maximum", ""); - INVALIDATE(s, "18446744073709551615", "", "maximum", ""); - INVALIDATE(s, "2147483647", "", "maximum", ""); // int max - INVALIDATE(s, "2147483648", "", "maximum", ""); // unsigned first - INVALIDATE(s, "4294967295", "", "maximum", ""); // unsigned max - INVALIDATE(s, "9223372036854775808", "", "maximum", ""); - INVALIDATE(s, "18446744073709551614", "", "maximum", ""); - INVALIDATE(s, "18446744073709551615", "", "maximum", ""); + INVALIDATE(s, "101", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 100.1, \"exclusiveMaximum\": true, \"actual\": 101" + "}}"); + INVALIDATE(s, "101.5", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 100.1, \"exclusiveMaximum\": true, \"actual\": 101.5" + "}}"); + INVALIDATE(s, "18446744073709551614", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 100.1, \"exclusiveMaximum\": true, \"actual\": 18446744073709551614" + "}}"); + INVALIDATE(s, "18446744073709551615", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 100.1, \"exclusiveMaximum\": true, \"actual\": 18446744073709551615" + "}}"); + INVALIDATE(s, "2147483647", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 100.1, \"exclusiveMaximum\": true, \"actual\": 2147483647" + "}}"); // int max + INVALIDATE(s, "2147483648", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 100.1, \"exclusiveMaximum\": true, \"actual\": 2147483648" + "}}"); // unsigned first + INVALIDATE(s, "4294967295", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 100.1, \"exclusiveMaximum\": true, \"actual\": 4294967295" + "}}"); // unsigned max + INVALIDATE(s, "9223372036854775808", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 100.1, \"exclusiveMaximum\": true, \"actual\": 9223372036854775808" + "}}"); + INVALIDATE(s, "18446744073709551614", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 100.1, \"exclusiveMaximum\": true, \"actual\": 18446744073709551614" + "}}"); + INVALIDATE(s, "18446744073709551615", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 100.1, \"exclusiveMaximum\": true, \"actual\": 18446744073709551615" + "}}"); } TEST(SchemaValidator, Number_RangeDoubleU64Boundary) { @@ -528,15 +842,43 @@ TEST(SchemaValidator, Number_RangeDoubleU64Boundary) { sd.Parse("{\"type\":\"number\",\"minimum\":9223372036854775808.0,\"maximum\":18446744073709550000.0}"); SchemaDocument s(sd); - INVALIDATE(s, "-9223372036854775808", "", "minimum", ""); - INVALIDATE(s, "-2147483648", "", "minimum", ""); // int min - INVALIDATE(s, "0", "", "minimum", ""); - INVALIDATE(s, "2147483647", "", "minimum", ""); // int max - INVALIDATE(s, "2147483648", "", "minimum", ""); // unsigned first - INVALIDATE(s, "4294967295", "", "minimum", ""); // unsigned max + INVALIDATE(s, "-9223372036854775808", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 9223372036854775808.0, \"actual\": -9223372036854775808" + "}}"); + INVALIDATE(s, "-2147483648", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 9223372036854775808.0, \"actual\": -2147483648" + "}}"); // int min + INVALIDATE(s, "0", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 9223372036854775808.0, \"actual\": 0" + "}}"); + INVALIDATE(s, "2147483647", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 9223372036854775808.0, \"actual\": 2147483647" + "}}"); // int max + INVALIDATE(s, "2147483648", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 9223372036854775808.0, \"actual\": 2147483648" + "}}"); // unsigned first + INVALIDATE(s, "4294967295", "", "minimum", "", + "{ \"minimum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 9223372036854775808.0, \"actual\": 4294967295" + "}}"); // unsigned max VALIDATE(s, "9223372036854775808", true); VALIDATE(s, "18446744073709540000", true); - INVALIDATE(s, "18446744073709551615", "", "maximum", ""); + INVALIDATE(s, "18446744073709551615", "", "maximum", "", + "{ \"maximum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 18446744073709550000.0, \"actual\": 18446744073709551615" + "}}"); } TEST(SchemaValidator, Number_MultipleOf) { @@ -548,13 +890,33 @@ TEST(SchemaValidator, Number_MultipleOf) { VALIDATE(s, "10", true); VALIDATE(s, "-10", true); VALIDATE(s, "20", true); - INVALIDATE(s, "23", "", "multipleOf", ""); - INVALIDATE(s, "-2147483648", "", "multipleOf", ""); // int min + INVALIDATE(s, "23", "", "multipleOf", "", + "{ \"multipleOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 10.0, \"actual\": 23" + "}}"); + INVALIDATE(s, "-2147483648", "", "multipleOf", "", + "{ \"multipleOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 10.0, \"actual\": -2147483648" + "}}"); // int min VALIDATE(s, "-2147483640", true); - INVALIDATE(s, "2147483647", "", "multipleOf", ""); // int max - INVALIDATE(s, "2147483648", "", "multipleOf", ""); // unsigned first + INVALIDATE(s, "2147483647", "", "multipleOf", "", + "{ \"multipleOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 10.0, \"actual\": 2147483647" + "}}"); // int max + INVALIDATE(s, "2147483648", "", "multipleOf", "", + "{ \"multipleOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 10.0, \"actual\": 2147483648" + "}}"); // unsigned first VALIDATE(s, "2147483650", true); - INVALIDATE(s, "4294967295", "", "multipleOf", ""); // unsigned max + INVALIDATE(s, "4294967295", "", "multipleOf", "", + "{ \"multipleOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 10.0, \"actual\": 4294967295" + "}}"); // unsigned max VALIDATE(s, "4294967300", true); } @@ -565,7 +927,11 @@ TEST(SchemaValidator, Number_MultipleOfOne) { VALIDATE(s, "42", true); VALIDATE(s, "42.0", true); - INVALIDATE(s, "3.1415926", "", "multipleOf", ""); + INVALIDATE(s, "3.1415926", "", "multipleOf", "", + "{ \"multipleOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 1, \"actual\": 3.1415926" + "}}"); } TEST(SchemaValidator, Object) { @@ -575,8 +941,16 @@ TEST(SchemaValidator, Object) { VALIDATE(s, "{\"key\":\"value\",\"another_key\":\"another_value\"}", true); VALIDATE(s, "{\"Sun\":1.9891e30,\"Jupiter\":1.8986e27,\"Saturn\":5.6846e26,\"Neptune\":10.243e25,\"Uranus\":8.6810e25,\"Earth\":5.9736e24,\"Venus\":4.8685e24,\"Mars\":6.4185e23,\"Mercury\":3.3022e23,\"Moon\":7.349e22,\"Pluto\":1.25e22}", true); - INVALIDATE(s, "[\"An\", \"array\", \"not\", \"an\", \"object\"]", "", "type", ""); - INVALIDATE(s, "\"Not an object\"", "", "type", ""); + INVALIDATE(s, "[\"An\", \"array\", \"not\", \"an\", \"object\"]", "", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": [\"object\"], \"actual\": \"array\"" + "}}"); + INVALIDATE(s, "\"Not an object\"", "", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": [\"object\"], \"actual\": \"string\"" + "}}"); } TEST(SchemaValidator, Object_Properties) { @@ -594,7 +968,17 @@ TEST(SchemaValidator, Object_Properties) { SchemaDocument s(sd); VALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\" }", true); - INVALIDATE(s, "{ \"number\": \"1600\", \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\" }", "/properties/number", "type", "/number"); + INVALIDATE(s, "{ \"number\": \"1600\", \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\" }", "/properties/number", "type", "/number", + "{ \"type\": {" + " \"instanceRef\": \"#/number\", \"schemaRef\": \"#/properties/number\"," + " \"expected\": [\"number\"], \"actual\": \"string\"" + "}}"); + INVALIDATE(s, "{ \"number\": \"One\", \"street_name\": \"Microsoft\", \"street_type\": \"Way\" }", + "/properties/number", "type", "/number", + "{ \"type\": {" + " \"instanceRef\": \"#/number\", \"schemaRef\": \"#/properties/number\"," + " \"expected\": [\"number\"], \"actual\": \"string\"" + "}}"); // fail fast VALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\" }", true); VALIDATE(s, "{}", true); VALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\", \"direction\": \"NW\" }", true); @@ -618,7 +1002,11 @@ TEST(SchemaValidator, Object_AdditionalPropertiesBoolean) { SchemaDocument s(sd); VALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\" }", true); - INVALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\", \"direction\": \"NW\" }", "", "additionalProperties", "/direction"); + INVALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\", \"direction\": \"NW\" }", "", "additionalProperties", "/direction", + "{ \"additionalProperties\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"disallowed\": \"direction\"" + "}}"); } TEST(SchemaValidator, Object_AdditionalPropertiesObject) { @@ -639,7 +1027,11 @@ TEST(SchemaValidator, Object_AdditionalPropertiesObject) { VALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\" }", true); VALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\", \"direction\": \"NW\" }", true); - INVALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\", \"office_number\": 201 }", "/additionalProperties", "type", "/office_number"); + INVALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\", \"office_number\": 201 }", "/additionalProperties", "type", "/office_number", + "{ \"type\": {" + " \"instanceRef\": \"#/office_number\", \"schemaRef\": \"#/additionalProperties\"," + " \"expected\": [\"string\"], \"actual\": \"integer\"" + "}}"); } TEST(SchemaValidator, Object_Required) { @@ -659,7 +1051,16 @@ TEST(SchemaValidator, Object_Required) { VALIDATE(s, "{ \"name\": \"William Shakespeare\", \"email\" : \"bill@stratford-upon-avon.co.uk\" }", true); VALIDATE(s, "{ \"name\": \"William Shakespeare\", \"email\" : \"bill@stratford-upon-avon.co.uk\", \"address\" : \"Henley Street, Stratford-upon-Avon, Warwickshire, England\", \"authorship\" : \"in question\"}", true); - INVALIDATE(s, "{ \"name\": \"William Shakespeare\", \"address\" : \"Henley Street, Stratford-upon-Avon, Warwickshire, England\" }", "", "required", ""); + INVALIDATE(s, "{ \"name\": \"William Shakespeare\", \"address\" : \"Henley Street, Stratford-upon-Avon, Warwickshire, England\" }", "", "required", "", + "{ \"required\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"missing\": [\"email\"]" + "}}"); + INVALIDATE(s, "{}", "", "required", "", + "{ \"required\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"missing\": [\"name\", \"email\"]" + "}}"); } @@ -668,11 +1069,23 @@ TEST(SchemaValidator, Object_PropertiesRange) { sd.Parse("{\"type\":\"object\", \"minProperties\":2, \"maxProperties\":3}"); SchemaDocument s(sd); - INVALIDATE(s, "{}", "", "minProperties", ""); - INVALIDATE(s, "{\"a\":0}", "", "minProperties", ""); + INVALIDATE(s, "{}", "", "minProperties", "", + "{ \"minProperties\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 2, \"actual\": 0" + "}}"); + INVALIDATE(s, "{\"a\":0}", "", "minProperties", "", + "{ \"minProperties\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 2, \"actual\": 1" + "}}"); VALIDATE(s, "{\"a\":0,\"b\":1}", true); VALIDATE(s, "{\"a\":0,\"b\":1,\"c\":2}", true); - INVALIDATE(s, "{\"a\":0,\"b\":1,\"c\":2,\"d\":3}", "", "maxProperties", ""); + INVALIDATE(s, "{\"a\":0,\"b\":1,\"c\":2,\"d\":3}", "", "maxProperties", "", + "{ \"maxProperties\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\", " + " \"expected\": 3, \"actual\": 4" + "}}"); } TEST(SchemaValidator, Object_PropertyDependencies) { @@ -683,19 +1096,25 @@ TEST(SchemaValidator, Object_PropertyDependencies) { " \"properties\": {" " \"name\": { \"type\": \"string\" }," " \"credit_card\": { \"type\": \"number\" }," + " \"cvv_code\": { \"type\": \"number\" }," " \"billing_address\": { \"type\": \"string\" }" " }," " \"required\": [\"name\"]," " \"dependencies\": {" - " \"credit_card\": [\"billing_address\"]" + " \"credit_card\": [\"cvv_code\", \"billing_address\"]" " }" "}"); SchemaDocument s(sd); - VALIDATE(s, "{ \"name\": \"John Doe\", \"credit_card\": 5555555555555555, \"billing_address\": \"555 Debtor's Lane\" }", true); - INVALIDATE(s, "{ \"name\": \"John Doe\", \"credit_card\": 5555555555555555 }", "", "dependencies", ""); + VALIDATE(s, "{ \"name\": \"John Doe\", \"credit_card\": 5555555555555555, \"cvv_code\": 777, " + "\"billing_address\": \"555 Debtor's Lane\" }", true); + INVALIDATE(s, "{ \"name\": \"John Doe\", \"credit_card\": 5555555555555555 }", "", "dependencies", "", + "{ \"dependencies\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"errors\": {\"credit_card\": [\"cvv_code\", \"billing_address\"]}" + "}}"); VALIDATE(s, "{ \"name\": \"John Doe\"}", true); - VALIDATE(s, "{ \"name\": \"John Doe\", \"billing_address\": \"555 Debtor's Lane\" }", true); + VALIDATE(s, "{ \"name\": \"John Doe\", \"cvv_code\": 777, \"billing_address\": \"555 Debtor's Lane\" }", true); } TEST(SchemaValidator, Object_SchemaDependencies) { @@ -720,7 +1139,16 @@ TEST(SchemaValidator, Object_SchemaDependencies) { SchemaDocument s(sd); VALIDATE(s, "{\"name\": \"John Doe\", \"credit_card\" : 5555555555555555,\"billing_address\" : \"555 Debtor's Lane\"}", true); - INVALIDATE(s, "{\"name\": \"John Doe\", \"credit_card\" : 5555555555555555 }", "", "dependencies", ""); + INVALIDATE(s, "{\"name\": \"John Doe\", \"credit_card\" : 5555555555555555 }", "", "dependencies", "", + "{ \"dependencies\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"errors\": {" + " \"credit_card\": {" + " \"required\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/dependencies/credit_card\"," + " \"missing\": [\"billing_address\"]" + " } } }" + "}}"); VALIDATE(s, "{\"name\": \"John Doe\", \"billing_address\" : \"555 Debtor's Lane\"}", true); } @@ -739,11 +1167,77 @@ TEST(SchemaValidator, Object_PatternProperties) { VALIDATE(s, "{ \"S_25\": \"This is a string\" }", true); VALIDATE(s, "{ \"I_0\": 42 }", true); - INVALIDATE(s, "{ \"S_0\": 42 }", "", "patternProperties", "/S_0"); - INVALIDATE(s, "{ \"I_42\": \"This is a string\" }", "", "patternProperties", "/I_42"); + INVALIDATE(s, "{ \"S_0\": 42 }", "", "patternProperties", "/S_0", + "{ \"type\": {" + " \"instanceRef\": \"#/S_0\", \"schemaRef\": \"#/patternProperties/%5ES_\"," + " \"expected\": [\"string\"], \"actual\": \"integer\"" + "}}"); + INVALIDATE(s, "{ \"I_42\": \"This is a string\" }", "", "patternProperties", "/I_42", + "{ \"type\": {" + " \"instanceRef\": \"#/I_42\", \"schemaRef\": \"#/patternProperties/%5EI_\"," + " \"expected\": [\"integer\"], \"actual\": \"string\"" + "}}"); VALIDATE(s, "{ \"keyword\": \"value\" }", true); } +TEST(SchemaValidator, Object_PattternProperties_ErrorConflict) { + Document sd; + sd.Parse( + "{" + " \"type\": \"object\"," + " \"patternProperties\": {" + " \"^I_\": { \"multipleOf\": 5 }," + " \"30$\": { \"multipleOf\": 6 }" + " }" + "}"); + SchemaDocument s(sd); + + VALIDATE(s, "{ \"I_30\": 30 }", true); + INVALIDATE(s, "{ \"I_30\": 7 }", "", "patternProperties", "/I_30", + "{ \"multipleOf\": [" + " {" + " \"instanceRef\": \"#/I_30\", \"schemaRef\": \"#/patternProperties/%5EI_\"," + " \"expected\": 5, \"actual\": 7" + " }, {" + " \"instanceRef\": \"#/I_30\", \"schemaRef\": \"#/patternProperties/30%24\"," + " \"expected\": 6, \"actual\": 7" + " }" + "]}"); +} + +TEST(SchemaValidator, Object_Properties_PatternProperties) { + Document sd; + sd.Parse( + "{" + " \"type\": \"object\"," + " \"properties\": {" + " \"I_42\": { \"type\": \"integer\", \"minimum\": 73 }" + " }," + " \"patternProperties\": {" + " \"^I_\": { \"type\": \"integer\", \"multipleOf\": 6 }" + " }" + "}"); + SchemaDocument s(sd); + + VALIDATE(s, "{ \"I_6\": 6 }", true); + VALIDATE(s, "{ \"I_42\": 78 }", true); + INVALIDATE(s, "{ \"I_42\": 42 }", "", "patternProperties", "/I_42", + "{ \"minimum\": {" + " \"instanceRef\": \"#/I_42\", \"schemaRef\": \"#/properties/I_42\"," + " \"expected\": 73, \"actual\": 42" + "}}"); + INVALIDATE(s, "{ \"I_42\": 7 }", "", "patternProperties", "/I_42", + "{ \"minimum\": {" + " \"instanceRef\": \"#/I_42\", \"schemaRef\": \"#/properties/I_42\"," + " \"expected\": 73, \"actual\": 7" + " }," + " \"multipleOf\": {" + " \"instanceRef\": \"#/I_42\", \"schemaRef\": \"#/patternProperties/%5EI_\"," + " \"expected\": 6, \"actual\": 7" + " }" + "}"); +} + TEST(SchemaValidator, Object_PatternProperties_AdditionalProperties) { Document sd; sd.Parse( @@ -762,7 +1256,11 @@ TEST(SchemaValidator, Object_PatternProperties_AdditionalProperties) { VALIDATE(s, "{ \"builtin\": 42 }", true); VALIDATE(s, "{ \"keyword\": \"value\" }", true); - INVALIDATE(s, "{ \"keyword\": 42 }", "/additionalProperties", "type", "/keyword"); + INVALIDATE(s, "{ \"keyword\": 42 }", "/additionalProperties", "type", "/keyword", + "{ \"type\": {" + " \"instanceRef\": \"#/keyword\", \"schemaRef\": \"#/additionalProperties\"," + " \"expected\": [\"string\"], \"actual\": \"integer\"" + "}}"); } #endif @@ -773,7 +1271,11 @@ TEST(SchemaValidator, Array) { VALIDATE(s, "[1, 2, 3, 4, 5]", true); VALIDATE(s, "[3, \"different\", { \"types\" : \"of values\" }]", true); - INVALIDATE(s, "{\"Not\": \"an array\"}", "", "type", ""); + INVALIDATE(s, "{\"Not\": \"an array\"}", "", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": [\"array\"], \"actual\": \"object\"" + "}}"); } TEST(SchemaValidator, Array_ItemsList) { @@ -788,7 +1290,11 @@ TEST(SchemaValidator, Array_ItemsList) { SchemaDocument s(sd); VALIDATE(s, "[1, 2, 3, 4, 5]", true); - INVALIDATE(s, "[1, 2, \"3\", 4, 5]", "/items", "type", "/2"); + INVALIDATE(s, "[1, 2, \"3\", 4, 5]", "/items", "type", "/2", + "{ \"type\": {" + " \"instanceRef\": \"#/2\", \"schemaRef\": \"#/items\"," + " \"expected\": [\"number\"], \"actual\": \"string\"" + "}}"); VALIDATE(s, "[]", true); } @@ -817,8 +1323,18 @@ TEST(SchemaValidator, Array_ItemsTuple) { SchemaDocument s(sd); VALIDATE(s, "[1600, \"Pennsylvania\", \"Avenue\", \"NW\"]", true); - INVALIDATE(s, "[24, \"Sussex\", \"Drive\"]", "/items/2", "enum", "/2"); - INVALIDATE(s, "[\"Palais de l'Elysee\"]", "/items/0", "type", "/0"); + INVALIDATE(s, "[24, \"Sussex\", \"Drive\"]", "/items/2", "enum", "/2", + "{ \"enum\": { \"instanceRef\": \"#/2\", \"schemaRef\": \"#/items/2\" }}"); + INVALIDATE(s, "[\"Palais de l'Elysee\"]", "/items/0", "type", "/0", + "{ \"type\": {" + " \"instanceRef\": \"#/0\", \"schemaRef\": \"#/items/0\"," + " \"expected\": [\"number\"], \"actual\": \"string\"" + "}}"); + INVALIDATE(s, "[\"Twenty-four\", \"Sussex\", \"Drive\"]", "/items/0", "type", "/0", + "{ \"type\": {" + " \"instanceRef\": \"#/0\", \"schemaRef\": \"#/items/0\"," + " \"expected\": [\"number\"], \"actual\": \"string\"" + "}}"); // fail fast VALIDATE(s, "[10, \"Downing\", \"Street\"]", true); VALIDATE(s, "[1600, \"Pennsylvania\", \"Avenue\", \"NW\", \"Washington\"]", true); } @@ -850,7 +1366,11 @@ TEST(SchemaValidator, Array_AdditionalItmes) { VALIDATE(s, "[1600, \"Pennsylvania\", \"Avenue\", \"NW\"]", true); VALIDATE(s, "[1600, \"Pennsylvania\", \"Avenue\"]", true); - INVALIDATE(s, "[1600, \"Pennsylvania\", \"Avenue\", \"NW\", \"Washington\"]", "", "items", "/4"); + INVALIDATE(s, "[1600, \"Pennsylvania\", \"Avenue\", \"NW\", \"Washington\"]", "", "items", "/4", + "{ \"additionalItems\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"disallowed\": 4" + "}}"); } TEST(SchemaValidator, Array_ItemsRange) { @@ -858,11 +1378,23 @@ TEST(SchemaValidator, Array_ItemsRange) { sd.Parse("{\"type\": \"array\",\"minItems\": 2,\"maxItems\" : 3}"); SchemaDocument s(sd); - INVALIDATE(s, "[]", "", "minItems", ""); - INVALIDATE(s, "[1]", "", "minItems", ""); + INVALIDATE(s, "[]", "", "minItems", "", + "{ \"minItems\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 2, \"actual\": 0" + "}}"); + INVALIDATE(s, "[1]", "", "minItems", "", + "{ \"minItems\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 2, \"actual\": 1" + "}}"); VALIDATE(s, "[1, 2]", true); VALIDATE(s, "[1, 2, 3]", true); - INVALIDATE(s, "[1, 2, 3, 4]", "", "maxItems", ""); + INVALIDATE(s, "[1, 2, 3, 4]", "", "maxItems", "", + "{ \"maxItems\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 3, \"actual\": 4" + "}}"); } TEST(SchemaValidator, Array_UniqueItems) { @@ -871,7 +1403,16 @@ TEST(SchemaValidator, Array_UniqueItems) { SchemaDocument s(sd); VALIDATE(s, "[1, 2, 3, 4, 5]", true); - INVALIDATE(s, "[1, 2, 3, 3, 4]", "", "uniqueItems", "/3"); + INVALIDATE(s, "[1, 2, 3, 3, 4]", "", "uniqueItems", "/3", + "{ \"uniqueItems\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"duplicates\": [2, 3]" + "}}"); + INVALIDATE(s, "[1, 2, 3, 3, 3]", "", "uniqueItems", "/3", + "{ \"uniqueItems\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"duplicates\": [2, 3]" + "}}"); // fail fast VALIDATE(s, "[]", true); } @@ -882,8 +1423,16 @@ TEST(SchemaValidator, Boolean) { VALIDATE(s, "true", true); VALIDATE(s, "false", true); - INVALIDATE(s, "\"true\"", "", "type", ""); - INVALIDATE(s, "0", "", "type", ""); + INVALIDATE(s, "\"true\"", "", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": [\"boolean\"], \"actual\": \"string\"" + "}}"); + INVALIDATE(s, "0", "", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": [\"boolean\"], \"actual\": \"integer\"" + "}}"); } TEST(SchemaValidator, Null) { @@ -892,9 +1441,21 @@ TEST(SchemaValidator, Null) { SchemaDocument s(sd); VALIDATE(s, "null", true); - INVALIDATE(s, "false", "", "type", ""); - INVALIDATE(s, "0", "", "type", ""); - INVALIDATE(s, "\"\"", "", "type", ""); + INVALIDATE(s, "false", "", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": [\"null\"], \"actual\": \"boolean\"" + "}}"); + INVALIDATE(s, "0", "", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": [\"null\"], \"actual\": \"integer\"" + "}}"); + INVALIDATE(s, "\"\"", "", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": [\"null\"], \"actual\": \"string\"" + "}}"); } // Additional tests @@ -905,8 +1466,16 @@ TEST(SchemaValidator, ObjectInArray) { SchemaDocument s(sd); VALIDATE(s, "[\"a\"]", true); - INVALIDATE(s, "[1]", "/items", "type", "/0"); - INVALIDATE(s, "[{}]", "/items", "type", "/0"); + INVALIDATE(s, "[1]", "/items", "type", "/0", + "{ \"type\": {" + " \"instanceRef\": \"#/0\", \"schemaRef\": \"#/items\"," + " \"expected\": [\"string\"], \"actual\": \"integer\"" + "}}"); + INVALIDATE(s, "[{}]", "/items", "type", "/0", + "{ \"type\": {" + " \"instanceRef\": \"#/0\", \"schemaRef\": \"#/items\"," + " \"expected\": [\"string\"], \"actual\": \"object\"" + "}}"); } TEST(SchemaValidator, MultiTypeInObject) { @@ -924,7 +1493,11 @@ TEST(SchemaValidator, MultiTypeInObject) { VALIDATE(s, "{ \"tel\": 999 }", true); VALIDATE(s, "{ \"tel\": \"123-456\" }", true); - INVALIDATE(s, "{ \"tel\": true }", "/properties/tel", "type", "/tel"); + INVALIDATE(s, "{ \"tel\": true }", "/properties/tel", "type", "/tel", + "{ \"type\": {" + " \"instanceRef\": \"#/tel\", \"schemaRef\": \"#/properties/tel\"," + " \"expected\": [\"string\", \"integer\"], \"actual\": \"boolean\"" + "}}"); } TEST(SchemaValidator, MultiTypeWithObject) { @@ -942,7 +1515,11 @@ TEST(SchemaValidator, MultiTypeWithObject) { VALIDATE(s, "\"Hello\"", true); VALIDATE(s, "{ \"tel\": 999 }", true); - INVALIDATE(s, "{ \"tel\": \"fail\" }", "/properties/tel", "type", "/tel"); + INVALIDATE(s, "{ \"tel\": \"fail\" }", "/properties/tel", "type", "/tel", + "{ \"type\": {" + " \"instanceRef\": \"#/tel\", \"schemaRef\": \"#/properties/tel\"," + " \"expected\": [\"integer\"], \"actual\": \"string\"" + "}}"); } TEST(SchemaValidator, AllOf_Nested) { @@ -959,11 +1536,88 @@ TEST(SchemaValidator, AllOf_Nested) { VALIDATE(s, "\"ok\"", true); VALIDATE(s, "\"OK\"", true); - INVALIDATE(s, "\"okay\"", "", "allOf", ""); - INVALIDATE(s, "\"o\"", "", "allOf", ""); - INVALIDATE(s, "\"n\"", "", "allOf", ""); - INVALIDATE(s, "\"too long\"", "", "allOf", ""); - INVALIDATE(s, "123", "", "allOf", ""); + INVALIDATE(s, "\"okay\"", "", "allOf", "", + "{ \"allOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"errors\": [" + " {}, " + " {}, " + " { \"allOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2\"," + " \"errors\": [" + " {}, " + " { \"enum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/1\"" + "}} ] }} ] }}"); + INVALIDATE(s, "\"o\"", "", "allOf", "", + "{ \"allOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"errors\": [" + " { \"minLength\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/0\"," + " \"expected\": 2, \"actual\": \"o\"" + " }}," + " {}," + " {}" + " ]" + "}}"); + INVALIDATE(s, "\"n\"", "", "allOf", "", + "{ \"allOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"errors\": [" + " { \"minLength\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/0\"," + " \"expected\": 2, \"actual\": \"n\"" + " }}," + " {}, " + " { \"allOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2\"," + " \"errors\": [" + " { \"enum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/0\"" + " }}," + " { \"enum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/1\"" + "}} ] }} ] }}"); + INVALIDATE(s, "\"too long\"", "", "allOf", "", + "{ \"allOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"errors\": [" + " {}, " + " { \"maxLength\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/1\"," + " \"expected\": 5, \"actual\": \"too long\"" + " }}," + " { \"allOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2\"," + " \"errors\": [" + " { \"enum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/0\"" + " }}," + " { \"enum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/1\"" + "}} ] }} ] }}"); + INVALIDATE(s, "123", "", "allOf", "", + "{ \"allOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"errors\": [" + " { \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/0\"," + " \"expected\": [\"string\"], \"actual\": \"integer\"" + " }}," + " { \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/1\"," + " \"expected\": [\"string\"], \"actual\": \"integer\"" + " }}," + " { \"allOf\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2\"," + " \"errors\": [" + " { \"enum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/0\"" + " }}, " + " { \"enum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/1\"" + "}} ] }} ] }}"); } TEST(SchemaValidator, EscapedPointer) { @@ -976,7 +1630,11 @@ TEST(SchemaValidator, EscapedPointer) { " }" "}"); SchemaDocument s(sd); - INVALIDATE(s, "{\"~/\":true}", "/properties/~0~1", "type", "/~0~1"); + INVALIDATE(s, "{\"~/\":true}", "/properties/~0~1", "type", "/~0~1", + "{ \"type\": {" + " \"instanceRef\": \"#/~0~1\", \"schemaRef\": \"#/properties/~0~1\"," + " \"expected\": [\"number\"], \"actual\": \"boolean\"" + "}}"); } template @@ -1026,6 +1684,10 @@ TEST(SchemaValidator, ValidateMetaSchema) { sb.Clear(); validator.GetInvalidDocumentPointer().StringifyUriFragment(sb); printf("Invalid document: %s\n", sb.GetString()); + sb.Clear(); + Writer w(sb); + validator.GetError().Accept(w); + printf("Validation error: %s\n", sb.GetString()); ADD_FAILURE(); } CrtAllocator::Free(json); @@ -1053,6 +1715,10 @@ TEST(SchemaValidator, ValidateMetaSchema_UTF16) { sb.Clear(); validator.GetInvalidDocumentPointer().StringifyUriFragment(sb); wprintf(L"Invalid document: %ls\n", sb.GetString()); + sb.Clear(); + Writer >, UTF16<> > w(sb); + validator.GetError().Accept(w); + printf("Validation error: %ls\n", sb.GetString()); ADD_FAILURE(); } CrtAllocator::Free(json); @@ -1260,6 +1926,15 @@ TEST(SchemaValidatingReader, Invalid) { EXPECT_TRUE(reader.GetInvalidSchemaPointer() == SchemaDocument::PointerType("")); EXPECT_TRUE(reader.GetInvalidDocumentPointer() == SchemaDocument::PointerType("")); EXPECT_TRUE(d.IsNull()); + Document e; + e.Parse( + "{ \"maxLength\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 3, \"actual\": \"ABCD\"" + "}}"); + if (e != reader.GetError()) { + ADD_FAILURE(); + } } TEST(SchemaValidatingWriter, Simple) { @@ -1284,6 +1959,13 @@ TEST(SchemaValidatingWriter, Simple) { EXPECT_FALSE(validator.IsValid()); EXPECT_TRUE(validator.GetInvalidSchemaPointer() == SchemaDocument::PointerType("")); EXPECT_TRUE(validator.GetInvalidDocumentPointer() == SchemaDocument::PointerType("")); + Document e; + e.Parse( + "{ \"maxLength\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": 3, \"actual\": \"ABCD\"" + "}}"); + EXPECT_EQ(e, validator.GetError()); } TEST(Schema, Issue848) { @@ -1305,7 +1987,11 @@ TEST(Schema, Issue552) { SchemaDocument s = ReturnSchemaDocument(); VALIDATE(s, "42", true); VALIDATE(s, "\"Life, the universe, and everything\"", true); - INVALIDATE(s, "[\"Life\", \"the universe\", \"and everything\"]", "", "type", ""); + INVALIDATE(s, "[\"Life\", \"the universe\", \"and everything\"]", "", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"expected\": [\"string\", \"number\"], \"actual\": \"array\"" + "}}"); } #endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS @@ -1316,7 +2002,11 @@ TEST(SchemaValidator, Issue608) { SchemaDocument s(sd); VALIDATE(s, "{\"a\" : null, \"b\": null}", true); - INVALIDATE(s, "{\"a\" : null, \"a\" : null}", "", "required", ""); + INVALIDATE(s, "{\"a\" : null, \"a\" : null}", "", "required", "", + "{ \"required\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," + " \"missing\": [\"b\"]" + "}}"); } // Fail to resolve $ref in allOf causes crash in SchemaValidator::StartObject() @@ -1361,7 +2051,13 @@ TEST(SchemaValidator, Ref_remote) { SchemaDocumentType s(sd, 0, 0, &provider); typedef GenericSchemaValidator >, MemoryPoolAllocator<> > SchemaValidatorType; typedef GenericPointer > PointerType; - INVALIDATE_(s, "null", "/integer", "type", "", SchemaValidatorType, PointerType); + INVALIDATE_(s, "null", "/integer", "type", "", + "{ \"type\": {" + " \"instanceRef\": \"#\"," + " \"schemaRef\": \"http://localhost:1234/subSchemas.json#/integer\"," + " \"expected\": [\"integer\"], \"actual\": \"null\"" + "}}", + SchemaValidatorType, PointerType); } #ifdef __clang__ -- cgit v1.2.3 From 384df14e6dc630269ae3ba9855e74ffb44fb6d80 Mon Sep 17 00:00:00 2001 From: Yuri Khan Date: Fri, 22 Sep 2017 21:20:17 +0700 Subject: Document schema violation format --- doc/Doxyfile.in | 1 + doc/schema-errors.md | 269 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 270 insertions(+) create mode 100644 doc/schema-errors.md diff --git a/doc/Doxyfile.in b/doc/Doxyfile.in index ca142339..4f23a797 100644 --- a/doc/Doxyfile.in +++ b/doc/Doxyfile.in @@ -776,6 +776,7 @@ INPUT = readme.md \ doc/dom.md \ doc/sax.md \ doc/schema.md \ + doc/schema-errors.md \ doc/performance.md \ doc/internals.md \ doc/faq.md diff --git a/doc/schema-errors.md b/doc/schema-errors.md new file mode 100644 index 00000000..f82120eb --- /dev/null +++ b/doc/schema-errors.md @@ -0,0 +1,269 @@ +# Schema violation reporting + +(Unreleased as of 2017-09-20) + +When validating an instance against a JSON Schema, +it is often desirable to report not only whether the instance is valid, +but also the ways in which it violates the schema. + +The `SchemaValidator` class +collects errors encountered during validation +into a JSON `Value`. +This error object can then be accessed as `validator.GetError()`. + +The structure of the error object is subject to change +in future versions of RapidJSON, +as there is no standard schema for violations. +The details below this point are provisional only. + +[TOC] + +# General provisions {#General} + +Validation of an instance value against a schema +produces an error value. +The error value is always an object. +An empty object `{}` indicates the instance is valid. + +* The name of each member + corresponds to the JSON Schema keyword that is violated. +* The value is either an object describing a single violation, + or an array of such objects. + +Each violation object contains two string-valued members +named `instanceRef` and `schemaRef`. +`instanceRef` contains the URI fragment serialization +of a JSON Pointer to the instance subobject +in which the violation was detected. +`schemaRef` contains the URI of the schema +and the fragment serialization of a JSON Pointer +to the subschema that was violated. + +Individual violation objects can contain other keyword-specific members. +These are detailed further. + +For example, validating this instance: + +~~~json +{"numbers": [1, 2, "3", 4, 5]} +~~~ + +against this schema: + +~~~json +{ + "type": "object", + "properties": { + "numbers": {"$ref": "numbers.schema.json"} + } +} +~~~ + +where `numbers.schema.json` refers +(via a suitable `IRemoteSchemaDocumentProvider`) +to this schema: + +~~~json +{ + "type": "array", + "items": {"type": "number"} +} +~~~ + +produces the following error object: + +~~~json +{ + "type": { + "instanceRef": "#/numbers/2", + "schemaRef": "numbers.schema.json#/items", + "expected": ["number"], + "actual": "string" + } +} +~~~ + +# Validation keywords for numbers {#numbers} + +## multipleOf {#multipleOf} + +* `expected`: required number strictly greater than 0. + The value of the `multipleOf` keyword specified in the schema. +* `actual`: required number. + The instance value. + +## maximum {#maximum} + +* `expected`: required number. + The value of the `maximum` keyword specified in the schema. +* `exclusiveMaximum`: optional boolean. + This will be true if the schema specified `"exclusiveMaximum": true`, + and will be omitted otherwise. +* `actual`: required number. + The instance value. + +## minimum {#minimum} + +* `expected`: required number. + The value of the `minimum` keyword specified in the schema. +* `exclusiveMinimum`: optional boolean. + This will be true if the schema specified `"exclusiveMinimum": true`, + and will be omitted otherwise. +* `actual`: required number. + The instance value. + +# Validation keywords for strings {#strings} + +## maxLength {#maxLength} + +* `expected`: required number greater than or equal to 0. + The value of the `maxLength` keyword specified in the schema. +* `actual`: required string. + The instance value. + +## minLength {#minLength} + +* `expected`: required number greater than or equal to 0. + The value of the `minLength` keyword specified in the schema. +* `actual`: required string. + The instance value. + +## pattern {#pattern} + +* `actual`: required string. + The instance value. + +(The expected pattern is not reported +because the internal representation in `SchemaDocument` +does not store the pattern in original string form.) + +# Validation keywords for arrays {#arrays} + +## additionalItems {#additionalItems} + +This keyword is reported +when the value of `items` schema keyword is an array, +the value of `additionalItems` is `false`, +and the instance is an array +with more items than specified in the `items` array. + +* `disallowed`: required integer greater than or equal to 0. + The index of the first item that has no corresponding schema. + +## maxItems and minItems {#maxItems} + +* `expected`: required integer greater than or equal to 0. + The value of `maxItems` (respectively, `minItems`) + specified in the schema. +* `actual`: required integer greater than or equal to 0. + Number of items in the instance array. + +## uniqueItems {#uniqueItems} + +* `duplicates`: required array + whose items are integers greater than or equal to 0. + Indices of items of the instance that are equal. + +(RapidJSON only reports the first two equal items, +for performance reasons.) + +# Validation keywords for objects + +## maxProperties and minProperties {#maxProperties} + +* `expected`: required integer greater than or equal to 0. + The value of `maxProperties` (respectively, `minProperties`) + specified in the schema. +* `actual`: required integer greater than or equal to 0. + Number of properties in the instance object. + +## required {#required} + +* `missing`: required array of one or more unique strings. + The names of properties + that are listed in the value of the `required` schema keyword + but not present in the instance object. + +## additionalProperties {#additionalProperties} + +This keyword is reported +when the schema specifies `additionalProperties: false` +and the name of a property of the instance is +neither listed in the `properties` keyword +nor matches any regular expression in the `patternProperties` keyword. + +* `disallowed`: required string. + Name of the offending property of the instance. + +(For performance reasons, +RapidJSON only reports the first such property encountered.) + +## dependencies {#dependencies} + +* `errors`: required object with one or more properties. + Names and values of its properties are described below. + +Recall that JSON Schema Draft 04 supports +*schema dependencies*, +where presence of a named *controlling* property +requires the instance object to be valid against a subschema, +and *property dependencies*, +where presence of a controlling property +requires other *dependent* properties to be also present. + +For a violated schema dependency, +`errors` will contain a property +with the name of the controlling property +and its value will be the error object +produced by validating the instance object +against the dependent schema. + +For a violated property dependency, +`errors` will contain a property +with the name of the controlling property +and its value will be an array of one or more unique strings +listing the missing dependent properties. + +# Validation keywords for any instance type {#anytypes} + +## enum {#enum} + +This keyword has no additional properties +beyond `instanceRef` and `schemaRef`. + +* The allowed values are not listed + because `SchemaDocument` does not store them in original form. +* The violating value is not reported + because it might be unwieldy. + +If you need to report these details to your users, +you can access the necessary information +by following `instanceRef` and `schemaRef`. + +## type {#type} + +* `expected`: required array of one or more unique strings, + each of which is one of the seven primitive types + defined by the JSON Schema Draft 04 Core specification. + Lists the types allowed by the `type` schema keyword. +* `actual`: required string, also one of seven primitive types. + The primitive type of the instance. + +## allOf, anyOf, and oneOf {#allOf} + +* `errors`: required array of at least one object. + There will be as many items as there are subschemas + in the `allOf`, `anyOf` or `oneOf` schema keyword, respectively. + Each item will be the error value + produced by validating the instance + against the corresponding subschema. + +For `allOf`, at least one error value will be non-empty. +For `anyOf`, all error values will be non-empty. +For `oneOf`, either all error values will be non-empty, +or more than one will be empty. + +## not {#not} + +This keyword has no additional properties +apart from `instanceRef` and `schemaRef`. -- cgit v1.2.3 From a4b62ff61be74061bb015c78770f48d6247c413b Mon Sep 17 00:00:00 2001 From: Yuri Khan Date: Fri, 22 Sep 2017 21:35:27 +0700 Subject: Update schemavalidator example to demonstrate GetError() --- example/schemavalidator/schemavalidator.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/example/schemavalidator/schemavalidator.cpp b/example/schemavalidator/schemavalidator.cpp index ce36ea95..06bbe4dd 100644 --- a/example/schemavalidator/schemavalidator.cpp +++ b/example/schemavalidator/schemavalidator.cpp @@ -6,6 +6,7 @@ #include "rapidjson/filereadstream.h" #include "rapidjson/schema.h" #include "rapidjson/stringbuffer.h" +#include "rapidjson/prettywriter.h" using namespace rapidjson; @@ -67,6 +68,11 @@ int main(int argc, char *argv[]) { sb.Clear(); validator.GetInvalidDocumentPointer().StringifyUriFragment(sb); fprintf(stderr, "Invalid document: %s\n", sb.GetString()); + // Detailed violation report is available as a JSON value + sb.Clear(); + PrettyWriter w(sb); + validator.GetError().Accept(w); + fprintf(stderr, "Error report:\n%s\n", sb.GetString()); return EXIT_FAILURE; } } -- cgit v1.2.3 From 1f75402704a56532332a6b7e09e3f0ea85f02503 Mon Sep 17 00:00:00 2001 From: Yuri Khan Date: Sat, 30 Sep 2017 19:05:25 +0700 Subject: refactor Schema: Keep ErrorHandler reference in Context --- include/rapidjson/schema.h | 200 +++++++++++++++++++++++---------------------- 1 file changed, 102 insertions(+), 98 deletions(-) diff --git a/include/rapidjson/schema.h b/include/rapidjson/schema.h index 53062eb8..b4d1a261 100644 --- a/include/rapidjson/schema.h +++ b/include/rapidjson/schema.h @@ -318,6 +318,7 @@ template struct SchemaValidationContext { typedef Schema SchemaType; typedef ISchemaStateFactory SchemaValidatorFactoryType; + typedef IValidationErrorHandler ErrorHandlerType; typedef typename SchemaType::ValueType ValueType; typedef typename ValueType::Ch Ch; @@ -327,8 +328,9 @@ struct SchemaValidationContext { kPatternValidatorWithAdditionalProperty }; - SchemaValidationContext(SchemaValidatorFactoryType& f, const SchemaType* s) : + SchemaValidationContext(SchemaValidatorFactoryType& f, ErrorHandlerType& eh, const SchemaType* s) : factory(f), + error_handler(eh), schema(s), valueSchema(), invalidKeyword(), @@ -368,6 +370,7 @@ struct SchemaValidationContext { } SchemaValidatorFactoryType& factory; + ErrorHandlerType& error_handler; const SchemaType* schema; const SchemaType* valueSchema; const Ch* invalidKeyword; @@ -664,7 +667,7 @@ public: return pointer_; } - bool BeginValue(Context& context, ErrorHandler& eh) const { + bool BeginValue(Context& context) const { if (context.inArray) { if (uniqueItems_) context.valueUniqueness = true; @@ -679,7 +682,7 @@ public: else if (additionalItems_) context.valueSchema = typeless_; else { - eh.DisallowedItem(context.arrayElementIndex); + context.error_handler.DisallowedItem(context.arrayElementIndex); RAPIDJSON_INVALID_KEYWORD_RETURN(GetItemsString()); } } @@ -691,7 +694,7 @@ public: return true; } - RAPIDJSON_FORCEINLINE bool EndValue(Context& context, ErrorHandler& eh) const { + RAPIDJSON_FORCEINLINE bool EndValue(Context& context) const { if (context.patternPropertiesValidatorCount > 0) { bool otherValid = false; SizeType count = context.patternPropertiesValidatorCount; @@ -707,18 +710,18 @@ public: if (context.objectPatternValidatorType == Context::kPatternValidatorOnly) { if (!patternValid) { - eh.PropertyViolations(context.patternPropertiesValidators, count); + context.error_handler.PropertyViolations(context.patternPropertiesValidators, count); RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString()); } } else if (context.objectPatternValidatorType == Context::kPatternValidatorWithProperty) { if (!patternValid || !otherValid) { - eh.PropertyViolations(context.patternPropertiesValidators, count + 1); + context.error_handler.PropertyViolations(context.patternPropertiesValidators, count + 1); RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString()); } } else if (!patternValid && !otherValid) { // kPatternValidatorWithAdditionalProperty) - eh.PropertyViolations(context.patternPropertiesValidators, count + 1); + context.error_handler.PropertyViolations(context.patternPropertiesValidators, count + 1); RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString()); } } @@ -728,7 +731,7 @@ public: for (SizeType i = 0; i < enumCount_; i++) if (enum_[i] == h) goto foundEnum; - eh.DisallowedValue(); + context.error_handler.DisallowedValue(); RAPIDJSON_INVALID_KEYWORD_RETURN(GetEnumString()); foundEnum:; } @@ -736,7 +739,7 @@ public: if (allOf_.schemas) for (SizeType i = allOf_.begin; i < allOf_.begin + allOf_.count; i++) if (!context.validators[i]->IsValid()) { - eh.NotAllOf(&context.validators[allOf_.begin], allOf_.count); + context.error_handler.NotAllOf(&context.validators[allOf_.begin], allOf_.count); RAPIDJSON_INVALID_KEYWORD_RETURN(GetAllOfString()); } @@ -744,7 +747,7 @@ public: for (SizeType i = anyOf_.begin; i < anyOf_.begin + anyOf_.count; i++) if (context.validators[i]->IsValid()) goto foundAny; - eh.NoneOf(&context.validators[anyOf_.begin], anyOf_.count); + context.error_handler.NoneOf(&context.validators[anyOf_.begin], anyOf_.count); RAPIDJSON_INVALID_KEYWORD_RETURN(GetAnyOfString()); foundAny:; } @@ -754,86 +757,86 @@ public: for (SizeType i = oneOf_.begin; i < oneOf_.begin + oneOf_.count; i++) if (context.validators[i]->IsValid()) { if (oneValid) { - eh.NotOneOf(&context.validators[oneOf_.begin], oneOf_.count); + context.error_handler.NotOneOf(&context.validators[oneOf_.begin], oneOf_.count); RAPIDJSON_INVALID_KEYWORD_RETURN(GetOneOfString()); } else oneValid = true; } if (!oneValid) { - eh.NotOneOf(&context.validators[oneOf_.begin], oneOf_.count); + context.error_handler.NotOneOf(&context.validators[oneOf_.begin], oneOf_.count); RAPIDJSON_INVALID_KEYWORD_RETURN(GetOneOfString()); } } if (not_ && context.validators[notValidatorIndex_]->IsValid()) { - eh.Disallowed(); + context.error_handler.Disallowed(); RAPIDJSON_INVALID_KEYWORD_RETURN(GetNotString()); } return true; } - bool Null(Context& context, ErrorHandler& eh) const { + bool Null(Context& context) const { if (!(type_ & (1 << kNullSchemaType))) { - DisallowedType(eh, GetNullString()); + DisallowedType(context, GetNullString()); RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); } return CreateParallelValidator(context); } - bool Bool(Context& context, ErrorHandler& eh, bool) const { + bool Bool(Context& context, bool) const { if (!(type_ & (1 << kBooleanSchemaType))) { - DisallowedType(eh, GetBooleanString()); + DisallowedType(context, GetBooleanString()); RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); } return CreateParallelValidator(context); } - bool Int(Context& context, ErrorHandler& eh, int i) const { - if (!CheckInt(context, eh, i)) + bool Int(Context& context, int i) const { + if (!CheckInt(context, i)) return false; return CreateParallelValidator(context); } - bool Uint(Context& context, ErrorHandler& eh, unsigned u) const { - if (!CheckUint(context, eh, u)) + bool Uint(Context& context, unsigned u) const { + if (!CheckUint(context, u)) return false; return CreateParallelValidator(context); } - bool Int64(Context& context, ErrorHandler& eh, int64_t i) const { - if (!CheckInt(context, eh, i)) + bool Int64(Context& context, int64_t i) const { + if (!CheckInt(context, i)) return false; return CreateParallelValidator(context); } - bool Uint64(Context& context, ErrorHandler& eh, uint64_t u) const { - if (!CheckUint(context, eh, u)) + bool Uint64(Context& context, uint64_t u) const { + if (!CheckUint(context, u)) return false; return CreateParallelValidator(context); } - bool Double(Context& context, ErrorHandler& eh, double d) const { + bool Double(Context& context, double d) const { if (!(type_ & (1 << kNumberSchemaType))) { - DisallowedType(eh, GetNumberString()); + DisallowedType(context, GetNumberString()); RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); } - if (!minimum_.IsNull() && !CheckDoubleMinimum(context, eh, d)) + if (!minimum_.IsNull() && !CheckDoubleMinimum(context, d)) return false; - if (!maximum_.IsNull() && !CheckDoubleMaximum(context, eh, d)) + if (!maximum_.IsNull() && !CheckDoubleMaximum(context, d)) return false; - if (!multipleOf_.IsNull() && !CheckDoubleMultipleOf(context, eh, d)) + if (!multipleOf_.IsNull() && !CheckDoubleMultipleOf(context, d)) return false; return CreateParallelValidator(context); } - bool String(Context& context, ErrorHandler& eh, const Ch* str, SizeType length, bool) const { + bool String(Context& context, const Ch* str, SizeType length, bool) const { if (!(type_ & (1 << kStringSchemaType))) { - DisallowedType(eh, GetStringString()); + DisallowedType(context, GetStringString()); RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); } @@ -841,27 +844,27 @@ public: SizeType count; if (internal::CountStringCodePoint(str, length, &count)) { if (count < minLength_) { - eh.TooShort(str, length, minLength_); + context.error_handler.TooShort(str, length, minLength_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinLengthString()); } if (count > maxLength_) { - eh.TooLong(str, length, maxLength_); + context.error_handler.TooLong(str, length, maxLength_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxLengthString()); } } } if (pattern_ && !IsPatternMatch(pattern_, str, length)) { - eh.DoesNotMatch(str, length); + context.error_handler.DoesNotMatch(str, length); RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternString()); } return CreateParallelValidator(context); } - bool StartObject(Context& context, ErrorHandler& eh) const { + bool StartObject(Context& context) const { if (!(type_ & (1 << kObjectSchemaType))) { - DisallowedType(eh, GetObjectString()); + DisallowedType(context, GetObjectString()); RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); } @@ -880,7 +883,7 @@ public: return CreateParallelValidator(context); } - bool Key(Context& context, ErrorHandler& eh, const Ch* str, SizeType len, bool) const { + bool Key(Context& context, const Ch* str, SizeType len, bool) const { if (patternProperties_) { context.patternPropertiesSchemaCount = 0; for (SizeType i = 0; i < patternPropertyCount_; i++) @@ -922,62 +925,62 @@ public: } if (context.patternPropertiesSchemaCount == 0) { // patternProperties are not additional properties - eh.DisallowedProperty(str, len); + context.error_handler.DisallowedProperty(str, len); RAPIDJSON_INVALID_KEYWORD_RETURN(GetAdditionalPropertiesString()); } return true; } - bool EndObject(Context& context, ErrorHandler& eh, SizeType memberCount) const { + bool EndObject(Context& context, SizeType memberCount) const { if (hasRequired_) { - eh.StartMissingProperties(); + context.error_handler.StartMissingProperties(); for (SizeType index = 0; index < propertyCount_; index++) if (properties_[index].required && !context.propertyExist[index]) - eh.AddMissingProperty(properties_[index].name); - if (eh.EndMissingProperties()) + context.error_handler.AddMissingProperty(properties_[index].name); + if (context.error_handler.EndMissingProperties()) RAPIDJSON_INVALID_KEYWORD_RETURN(GetRequiredString()); } if (memberCount < minProperties_) { - eh.TooFewProperties(memberCount, minProperties_); + context.error_handler.TooFewProperties(memberCount, minProperties_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinPropertiesString()); } if (memberCount > maxProperties_) { - eh.TooManyProperties(memberCount, maxProperties_); + context.error_handler.TooManyProperties(memberCount, maxProperties_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxPropertiesString()); } if (hasDependencies_) { - eh.StartDependencyErrors(); + context.error_handler.StartDependencyErrors(); for (SizeType sourceIndex = 0; sourceIndex < propertyCount_; sourceIndex++) { const Property& source = properties_[sourceIndex]; if (context.propertyExist[sourceIndex]) { if (source.dependencies) { - eh.StartMissingDependentProperties(); + context.error_handler.StartMissingDependentProperties(); for (SizeType targetIndex = 0; targetIndex < propertyCount_; targetIndex++) if (source.dependencies[targetIndex] && !context.propertyExist[targetIndex]) - eh.AddMissingDependentProperty(properties_[targetIndex].name); - eh.EndMissingDependentProperties(source.name); + context.error_handler.AddMissingDependentProperty(properties_[targetIndex].name); + context.error_handler.EndMissingDependentProperties(source.name); } else if (source.dependenciesSchema) { ISchemaValidator* dependenciesValidator = context.validators[source.dependenciesValidatorIndex]; if (!dependenciesValidator->IsValid()) - eh.AddDependencySchemaError(source.name, dependenciesValidator); + context.error_handler.AddDependencySchemaError(source.name, dependenciesValidator); } } } - if (eh.EndDependencyErrors()) + if (context.error_handler.EndDependencyErrors()) RAPIDJSON_INVALID_KEYWORD_RETURN(GetDependenciesString()); } return true; } - bool StartArray(Context& context, ErrorHandler& eh) const { + bool StartArray(Context& context) const { if (!(type_ & (1 << kArraySchemaType))) { - DisallowedType(eh, GetArrayString()); + DisallowedType(context, GetArrayString()); RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); } @@ -987,16 +990,16 @@ public: return CreateParallelValidator(context); } - bool EndArray(Context& context, ErrorHandler& eh, SizeType elementCount) const { + bool EndArray(Context& context, SizeType elementCount) const { context.inArray = false; if (elementCount < minItems_) { - eh.TooFewItems(elementCount, minItems_); + context.error_handler.TooFewItems(elementCount, minItems_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinItemsString()); } if (elementCount > maxItems_) { - eh.TooManyItems(elementCount, maxItems_); + context.error_handler.TooManyItems(elementCount, maxItems_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxItemsString()); } @@ -1218,130 +1221,131 @@ private: return false; } - bool CheckInt(Context& context, ErrorHandler& eh, int64_t i) const { + bool CheckInt(Context& context, int64_t i) const { if (!(type_ & ((1 << kIntegerSchemaType) | (1 << kNumberSchemaType)))) { - DisallowedType(eh, GetIntegerString()); + DisallowedType(context, GetIntegerString()); RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); } if (!minimum_.IsNull()) { if (minimum_.IsInt64()) { if (exclusiveMinimum_ ? i <= minimum_.GetInt64() : i < minimum_.GetInt64()) { - eh.BelowMinimum(i, minimum_, exclusiveMinimum_); + context.error_handler.BelowMinimum(i, minimum_, exclusiveMinimum_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); } } else if (minimum_.IsUint64()) { - eh.BelowMinimum(i, minimum_, exclusiveMinimum_); + context.error_handler.BelowMinimum(i, minimum_, exclusiveMinimum_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); // i <= max(int64_t) < minimum.GetUint64() } - else if (!CheckDoubleMinimum(context, eh, static_cast(i))) + else if (!CheckDoubleMinimum(context, static_cast(i))) return false; } if (!maximum_.IsNull()) { if (maximum_.IsInt64()) { if (exclusiveMaximum_ ? i >= maximum_.GetInt64() : i > maximum_.GetInt64()) { - eh.AboveMaximum(i, maximum_, exclusiveMaximum_); + context.error_handler.AboveMaximum(i, maximum_, exclusiveMaximum_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); } } else if (maximum_.IsUint64()) { } /* do nothing */ // i <= max(int64_t) < maximum_.GetUint64() - else if (!CheckDoubleMaximum(context, eh, static_cast(i))) + else if (!CheckDoubleMaximum(context, static_cast(i))) return false; } if (!multipleOf_.IsNull()) { if (multipleOf_.IsUint64()) { if (static_cast(i >= 0 ? i : -i) % multipleOf_.GetUint64() != 0) { - eh.NotMultipleOf(i, multipleOf_); + context.error_handler.NotMultipleOf(i, multipleOf_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString()); } } - else if (!CheckDoubleMultipleOf(context, eh, static_cast(i))) + else if (!CheckDoubleMultipleOf(context, static_cast(i))) return false; } return true; } - bool CheckUint(Context& context, ErrorHandler& eh, uint64_t i) const { + bool CheckUint(Context& context, uint64_t i) const { if (!(type_ & ((1 << kIntegerSchemaType) | (1 << kNumberSchemaType)))) { - DisallowedType(eh, GetIntegerString()); + DisallowedType(context, GetIntegerString()); RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); } if (!minimum_.IsNull()) { if (minimum_.IsUint64()) { if (exclusiveMinimum_ ? i <= minimum_.GetUint64() : i < minimum_.GetUint64()) { - eh.BelowMinimum(i, minimum_, exclusiveMinimum_); + context.error_handler.BelowMinimum(i, minimum_, exclusiveMinimum_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); } } else if (minimum_.IsInt64()) /* do nothing */; // i >= 0 > minimum.Getint64() - else if (!CheckDoubleMinimum(context, eh, static_cast(i))) + else if (!CheckDoubleMinimum(context, static_cast(i))) return false; } if (!maximum_.IsNull()) { if (maximum_.IsUint64()) { if (exclusiveMaximum_ ? i >= maximum_.GetUint64() : i > maximum_.GetUint64()) { - eh.AboveMaximum(i, maximum_, exclusiveMaximum_); + context.error_handler.AboveMaximum(i, maximum_, exclusiveMaximum_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); } } else if (maximum_.IsInt64()) { - eh.AboveMaximum(i, maximum_, exclusiveMaximum_); + context.error_handler.AboveMaximum(i, maximum_, exclusiveMaximum_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); // i >= 0 > maximum_ } - else if (!CheckDoubleMaximum(context, eh, static_cast(i))) + else if (!CheckDoubleMaximum(context, static_cast(i))) return false; } if (!multipleOf_.IsNull()) { if (multipleOf_.IsUint64()) { if (i % multipleOf_.GetUint64() != 0) { - eh.NotMultipleOf(i, multipleOf_); + context.error_handler.NotMultipleOf(i, multipleOf_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString()); } } - else if (!CheckDoubleMultipleOf(context, eh, static_cast(i))) + else if (!CheckDoubleMultipleOf(context, static_cast(i))) return false; } return true; } - bool CheckDoubleMinimum(Context& context, ErrorHandler& eh, double d) const { + bool CheckDoubleMinimum(Context& context, double d) const { if (exclusiveMinimum_ ? d <= minimum_.GetDouble() : d < minimum_.GetDouble()) { - eh.BelowMinimum(d, minimum_, exclusiveMinimum_); + context.error_handler.BelowMinimum(d, minimum_, exclusiveMinimum_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); } return true; } - bool CheckDoubleMaximum(Context& context, ErrorHandler& eh, double d) const { + bool CheckDoubleMaximum(Context& context, double d) const { if (exclusiveMaximum_ ? d >= maximum_.GetDouble() : d > maximum_.GetDouble()) { - eh.AboveMaximum(d, maximum_, exclusiveMaximum_); + context.error_handler.AboveMaximum(d, maximum_, exclusiveMaximum_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); } return true; } - bool CheckDoubleMultipleOf(Context& context, ErrorHandler& eh, double d) const { + bool CheckDoubleMultipleOf(Context& context, double d) const { double a = std::abs(d), b = std::abs(multipleOf_.GetDouble()); double q = std::floor(a / b); double r = a - q * b; if (r > 0.0) { - eh.NotMultipleOf(d, multipleOf_); + context.error_handler.NotMultipleOf(d, multipleOf_); RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString()); } return true; } - void DisallowedType(ErrorHandler& eh, const ValueType& actualType) const { + void DisallowedType(Context& context, const ValueType& actualType) const { + ErrorHandler& eh = context.error_handler; eh.StartDisallowedType(); if (type_ & (1 << kNullSchemaType)) eh.AddExpectedType(GetNullString()); @@ -2076,20 +2080,20 @@ RAPIDJSON_MULTILINEMACRO_END RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(method, arg2);\ RAPIDJSON_SCHEMA_HANDLE_END_ (method, arg2) - bool Null() { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Null, (CurrentContext(), *this), ( )); } - bool Bool(bool b) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Bool, (CurrentContext(), *this, b), (b)); } - bool Int(int i) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Int, (CurrentContext(), *this, i), (i)); } - bool Uint(unsigned u) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Uint, (CurrentContext(), *this, u), (u)); } - bool Int64(int64_t i) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Int64, (CurrentContext(), *this, i), (i)); } - bool Uint64(uint64_t u) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Uint64, (CurrentContext(), *this, u), (u)); } - bool Double(double d) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Double, (CurrentContext(), *this, d), (d)); } + bool Null() { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Null, (CurrentContext()), ( )); } + bool Bool(bool b) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Bool, (CurrentContext(), b), (b)); } + bool Int(int i) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Int, (CurrentContext(), i), (i)); } + bool Uint(unsigned u) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Uint, (CurrentContext(), u), (u)); } + bool Int64(int64_t i) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Int64, (CurrentContext(), i), (i)); } + bool Uint64(uint64_t u) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Uint64, (CurrentContext(), u), (u)); } + bool Double(double d) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Double, (CurrentContext(), d), (d)); } bool RawNumber(const Ch* str, SizeType length, bool copy) - { RAPIDJSON_SCHEMA_HANDLE_VALUE_(String, (CurrentContext(), *this, str, length, copy), (str, length, copy)); } + { RAPIDJSON_SCHEMA_HANDLE_VALUE_(String, (CurrentContext(), str, length, copy), (str, length, copy)); } bool String(const Ch* str, SizeType length, bool copy) - { RAPIDJSON_SCHEMA_HANDLE_VALUE_(String, (CurrentContext(), *this, str, length, copy), (str, length, copy)); } + { RAPIDJSON_SCHEMA_HANDLE_VALUE_(String, (CurrentContext(), str, length, copy), (str, length, copy)); } bool StartObject() { - RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartObject, (CurrentContext(), *this)); + RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartObject, (CurrentContext())); RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(StartObject, ()); return valid_ = !outputHandler_ || outputHandler_->StartObject(); } @@ -2097,7 +2101,7 @@ RAPIDJSON_MULTILINEMACRO_END bool Key(const Ch* str, SizeType len, bool copy) { if (!valid_) return false; AppendToken(str, len); - if (!CurrentSchema().Key(CurrentContext(), *this, str, len, copy)) return valid_ = false; + if (!CurrentSchema().Key(CurrentContext(), str, len, copy)) return valid_ = false; RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(Key, (str, len, copy)); return valid_ = !outputHandler_ || outputHandler_->Key(str, len, copy); } @@ -2105,12 +2109,12 @@ RAPIDJSON_MULTILINEMACRO_END bool EndObject(SizeType memberCount) { if (!valid_) return false; RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(EndObject, (memberCount)); - if (!CurrentSchema().EndObject(CurrentContext(), *this, memberCount)) return valid_ = false; + if (!CurrentSchema().EndObject(CurrentContext(), memberCount)) return valid_ = false; RAPIDJSON_SCHEMA_HANDLE_END_(EndObject, (memberCount)); } bool StartArray() { - RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartArray, (CurrentContext(), *this)); + RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartArray, (CurrentContext())); RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(StartArray, ()); return valid_ = !outputHandler_ || outputHandler_->StartArray(); } @@ -2118,7 +2122,7 @@ RAPIDJSON_MULTILINEMACRO_END bool EndArray(SizeType elementCount) { if (!valid_) return false; RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(EndArray, (elementCount)); - if (!CurrentSchema().EndArray(CurrentContext(), *this, elementCount)) return valid_ = false; + if (!CurrentSchema().EndArray(CurrentContext(), elementCount)) return valid_ = false; RAPIDJSON_SCHEMA_HANDLE_END_(EndArray, (elementCount)); } @@ -2212,7 +2216,7 @@ private: if (CurrentContext().inArray) internal::TokenHelper, Ch>::AppendIndexToken(documentStack_, CurrentContext().arrayElementIndex); - if (!CurrentSchema().BeginValue(CurrentContext(), *this)) + if (!CurrentSchema().BeginValue(CurrentContext())) return false; SizeType count = CurrentContext().patternPropertiesSchemaCount; @@ -2237,7 +2241,7 @@ private: } bool EndValue() { - if (!CurrentSchema().EndValue(CurrentContext(), *this)) + if (!CurrentSchema().EndValue(CurrentContext())) return false; #if RAPIDJSON_SCHEMA_VERBOSE @@ -2292,7 +2296,7 @@ private: } } - RAPIDJSON_FORCEINLINE void PushSchema(const SchemaType& schema) { new (schemaStack_.template Push()) Context(*this, &schema); } + RAPIDJSON_FORCEINLINE void PushSchema(const SchemaType& schema) { new (schemaStack_.template Push()) Context(*this, *this, &schema); } RAPIDJSON_FORCEINLINE void PopSchema() { Context* c = schemaStack_.template Pop(1); -- cgit v1.2.3 From 8353e868d52edf825e4343f7afcbe263f1a24737 Mon Sep 17 00:00:00 2001 From: Yuri Khan Date: Sat, 30 Sep 2017 19:44:54 +0700 Subject: Move schema violation docs into Schema chapter --- doc/Doxyfile.in | 1 - doc/schema-errors.md | 269 ------------------------------------------------ doc/schema.md | 286 +++++++++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 277 insertions(+), 279 deletions(-) delete mode 100644 doc/schema-errors.md diff --git a/doc/Doxyfile.in b/doc/Doxyfile.in index 4f23a797..ca142339 100644 --- a/doc/Doxyfile.in +++ b/doc/Doxyfile.in @@ -776,7 +776,6 @@ INPUT = readme.md \ doc/dom.md \ doc/sax.md \ doc/schema.md \ - doc/schema-errors.md \ doc/performance.md \ doc/internals.md \ doc/faq.md diff --git a/doc/schema-errors.md b/doc/schema-errors.md deleted file mode 100644 index f82120eb..00000000 --- a/doc/schema-errors.md +++ /dev/null @@ -1,269 +0,0 @@ -# Schema violation reporting - -(Unreleased as of 2017-09-20) - -When validating an instance against a JSON Schema, -it is often desirable to report not only whether the instance is valid, -but also the ways in which it violates the schema. - -The `SchemaValidator` class -collects errors encountered during validation -into a JSON `Value`. -This error object can then be accessed as `validator.GetError()`. - -The structure of the error object is subject to change -in future versions of RapidJSON, -as there is no standard schema for violations. -The details below this point are provisional only. - -[TOC] - -# General provisions {#General} - -Validation of an instance value against a schema -produces an error value. -The error value is always an object. -An empty object `{}` indicates the instance is valid. - -* The name of each member - corresponds to the JSON Schema keyword that is violated. -* The value is either an object describing a single violation, - or an array of such objects. - -Each violation object contains two string-valued members -named `instanceRef` and `schemaRef`. -`instanceRef` contains the URI fragment serialization -of a JSON Pointer to the instance subobject -in which the violation was detected. -`schemaRef` contains the URI of the schema -and the fragment serialization of a JSON Pointer -to the subschema that was violated. - -Individual violation objects can contain other keyword-specific members. -These are detailed further. - -For example, validating this instance: - -~~~json -{"numbers": [1, 2, "3", 4, 5]} -~~~ - -against this schema: - -~~~json -{ - "type": "object", - "properties": { - "numbers": {"$ref": "numbers.schema.json"} - } -} -~~~ - -where `numbers.schema.json` refers -(via a suitable `IRemoteSchemaDocumentProvider`) -to this schema: - -~~~json -{ - "type": "array", - "items": {"type": "number"} -} -~~~ - -produces the following error object: - -~~~json -{ - "type": { - "instanceRef": "#/numbers/2", - "schemaRef": "numbers.schema.json#/items", - "expected": ["number"], - "actual": "string" - } -} -~~~ - -# Validation keywords for numbers {#numbers} - -## multipleOf {#multipleOf} - -* `expected`: required number strictly greater than 0. - The value of the `multipleOf` keyword specified in the schema. -* `actual`: required number. - The instance value. - -## maximum {#maximum} - -* `expected`: required number. - The value of the `maximum` keyword specified in the schema. -* `exclusiveMaximum`: optional boolean. - This will be true if the schema specified `"exclusiveMaximum": true`, - and will be omitted otherwise. -* `actual`: required number. - The instance value. - -## minimum {#minimum} - -* `expected`: required number. - The value of the `minimum` keyword specified in the schema. -* `exclusiveMinimum`: optional boolean. - This will be true if the schema specified `"exclusiveMinimum": true`, - and will be omitted otherwise. -* `actual`: required number. - The instance value. - -# Validation keywords for strings {#strings} - -## maxLength {#maxLength} - -* `expected`: required number greater than or equal to 0. - The value of the `maxLength` keyword specified in the schema. -* `actual`: required string. - The instance value. - -## minLength {#minLength} - -* `expected`: required number greater than or equal to 0. - The value of the `minLength` keyword specified in the schema. -* `actual`: required string. - The instance value. - -## pattern {#pattern} - -* `actual`: required string. - The instance value. - -(The expected pattern is not reported -because the internal representation in `SchemaDocument` -does not store the pattern in original string form.) - -# Validation keywords for arrays {#arrays} - -## additionalItems {#additionalItems} - -This keyword is reported -when the value of `items` schema keyword is an array, -the value of `additionalItems` is `false`, -and the instance is an array -with more items than specified in the `items` array. - -* `disallowed`: required integer greater than or equal to 0. - The index of the first item that has no corresponding schema. - -## maxItems and minItems {#maxItems} - -* `expected`: required integer greater than or equal to 0. - The value of `maxItems` (respectively, `minItems`) - specified in the schema. -* `actual`: required integer greater than or equal to 0. - Number of items in the instance array. - -## uniqueItems {#uniqueItems} - -* `duplicates`: required array - whose items are integers greater than or equal to 0. - Indices of items of the instance that are equal. - -(RapidJSON only reports the first two equal items, -for performance reasons.) - -# Validation keywords for objects - -## maxProperties and minProperties {#maxProperties} - -* `expected`: required integer greater than or equal to 0. - The value of `maxProperties` (respectively, `minProperties`) - specified in the schema. -* `actual`: required integer greater than or equal to 0. - Number of properties in the instance object. - -## required {#required} - -* `missing`: required array of one or more unique strings. - The names of properties - that are listed in the value of the `required` schema keyword - but not present in the instance object. - -## additionalProperties {#additionalProperties} - -This keyword is reported -when the schema specifies `additionalProperties: false` -and the name of a property of the instance is -neither listed in the `properties` keyword -nor matches any regular expression in the `patternProperties` keyword. - -* `disallowed`: required string. - Name of the offending property of the instance. - -(For performance reasons, -RapidJSON only reports the first such property encountered.) - -## dependencies {#dependencies} - -* `errors`: required object with one or more properties. - Names and values of its properties are described below. - -Recall that JSON Schema Draft 04 supports -*schema dependencies*, -where presence of a named *controlling* property -requires the instance object to be valid against a subschema, -and *property dependencies*, -where presence of a controlling property -requires other *dependent* properties to be also present. - -For a violated schema dependency, -`errors` will contain a property -with the name of the controlling property -and its value will be the error object -produced by validating the instance object -against the dependent schema. - -For a violated property dependency, -`errors` will contain a property -with the name of the controlling property -and its value will be an array of one or more unique strings -listing the missing dependent properties. - -# Validation keywords for any instance type {#anytypes} - -## enum {#enum} - -This keyword has no additional properties -beyond `instanceRef` and `schemaRef`. - -* The allowed values are not listed - because `SchemaDocument` does not store them in original form. -* The violating value is not reported - because it might be unwieldy. - -If you need to report these details to your users, -you can access the necessary information -by following `instanceRef` and `schemaRef`. - -## type {#type} - -* `expected`: required array of one or more unique strings, - each of which is one of the seven primitive types - defined by the JSON Schema Draft 04 Core specification. - Lists the types allowed by the `type` schema keyword. -* `actual`: required string, also one of seven primitive types. - The primitive type of the instance. - -## allOf, anyOf, and oneOf {#allOf} - -* `errors`: required array of at least one object. - There will be as many items as there are subschemas - in the `allOf`, `anyOf` or `oneOf` schema keyword, respectively. - Each item will be the error value - produced by validating the instance - against the corresponding subschema. - -For `allOf`, at least one error value will be non-empty. -For `anyOf`, all error values will be non-empty. -For `oneOf`, either all error values will be non-empty, -or more than one will be empty. - -## not {#not} - -This keyword has no additional properties -apart from `instanceRef` and `schemaRef`. diff --git a/doc/schema.md b/doc/schema.md index 29ba4f54..9d1b21a7 100644 --- a/doc/schema.md +++ b/doc/schema.md @@ -8,7 +8,7 @@ RapidJSON implemented a JSON Schema validator for [JSON Schema Draft v4](http:// [TOC] -## Basic Usage +# Basic Usage {#Basic} First of all, you need to parse a JSON Schema into `Document`, and then compile the `Document` into a `SchemaDocument`. @@ -52,11 +52,11 @@ Some notes: * One `SchemaDocment` can be referenced by multiple `SchemaValidator`s. It will not be modified by `SchemaValidator`s. * A `SchemaValidator` may be reused to validate multiple documents. To run it for other documents, call `validator.Reset()` first. -## Validation during parsing/serialization +# Validation during parsing/serialization {#Fused} Unlike most JSON Schema validator implementations, RapidJSON provides a SAX-based schema validator. Therefore, you can parse a JSON from a stream while validating it on the fly. If the validator encounters a JSON value that invalidates the supplied schema, the parsing will be terminated immediately. This design is especially useful for parsing large JSON files. -### DOM parsing +## DOM parsing {#DOM} For using DOM in parsing, `Document` needs some preparation and finalizing tasks, in addition to receiving SAX events, thus it needs some work to route the reader, validator and the document. `SchemaValidatingReader` is a helper class that doing such work. @@ -97,7 +97,7 @@ if (!reader.GetParseResult()) { } ~~~ -### SAX parsing +## SAX parsing {#SAX} For using SAX in parsing, it is much simpler. If it only need to validate the JSON without further processing, it is simply: @@ -126,7 +126,7 @@ if (!reader.Parse(ss, validator)) { } ~~~ -### Serialization +## Serialization {#Serialization} It is also possible to do validation during serializing. This can ensure the result JSON is valid according to the JSON schema. @@ -144,7 +144,7 @@ if (!d.Accept(validator)) { Of course, if your application only needs SAX-style serialization, it can simply send SAX events to `SchemaValidator` instead of `Writer`. -## Remote Schema +# Remote Schema {#Remote} JSON Schema supports [`$ref` keyword](http://spacetelescope.github.io/understanding-json-schema/structuring.html), which is a [JSON pointer](doc/pointer.md) referencing to a local or remote schema. Local pointer is prefixed with `#`, while remote pointer is an relative or absolute URI. For example: @@ -168,7 +168,7 @@ MyRemoteSchemaDocumentProvider provider; SchemaDocument schema(sd, &provider); ~~~ -## Conformance +# Conformance {#Conformance} RapidJSON passed 262 out of 263 tests in [JSON Schema Test Suite](https://github.com/json-schema/JSON-Schema-Test-Suite) (Json Schema draft 4). @@ -176,7 +176,7 @@ The failed test is "changed scope ref invalid" of "change resolution scope" in ` Besides, the `format` schema keyword for string values is ignored, since it is not required by the specification. -### Regular Expression +## Regular Expression {#Regex} The schema keyword `pattern` and `patternProperties` uses regular expression to match the required pattern. @@ -211,7 +211,7 @@ RapidJSON implemented a simple NFA regular expression engine, which is used by d For C++11 compiler, it is also possible to use the `std::regex` by defining `RAPIDJSON_SCHEMA_USE_INTERNALREGEX=0` and `RAPIDJSON_SCHEMA_USE_STDREGEX=1`. If your schemas do not need `pattern` and `patternProperties`, you can set both macros to zero to disable this feature, which will reduce some code size. -## Performance +# Performance {#Performance} Most C++ JSON libraries do not yet support JSON Schema. So we tried to evaluate the performance of RapidJSON's JSON Schema validator according to [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark), which tests 11 JavaScript libraries running on Node.js. @@ -235,3 +235,271 @@ On a Mac Book Pro (2.8 GHz Intel Core i7), the following results are collected. |[`jayschema`](https://github.com/natesilva/jayschema)|0.1%|21 (± 1.14%)| That is, RapidJSON is about 1.5x faster than the fastest JavaScript library (ajv). And 1400x faster than the slowest one. + +# Schema violation reporting {#Reporting} + +(Unreleased as of 2017-09-20) + +When validating an instance against a JSON Schema, +it is often desirable to report not only whether the instance is valid, +but also the ways in which it violates the schema. + +The `SchemaValidator` class +collects errors encountered during validation +into a JSON `Value`. +This error object can then be accessed as `validator.GetError()`. + +The structure of the error object is subject to change +in future versions of RapidJSON, +as there is no standard schema for violations. +The details below this point are provisional only. + +## General provisions {#ReportingGeneral} + +Validation of an instance value against a schema +produces an error value. +The error value is always an object. +An empty object `{}` indicates the instance is valid. + +* The name of each member + corresponds to the JSON Schema keyword that is violated. +* The value is either an object describing a single violation, + or an array of such objects. + +Each violation object contains two string-valued members +named `instanceRef` and `schemaRef`. +`instanceRef` contains the URI fragment serialization +of a JSON Pointer to the instance subobject +in which the violation was detected. +`schemaRef` contains the URI of the schema +and the fragment serialization of a JSON Pointer +to the subschema that was violated. + +Individual violation objects can contain other keyword-specific members. +These are detailed further. + +For example, validating this instance: + +~~~json +{"numbers": [1, 2, "3", 4, 5]} +~~~ + +against this schema: + +~~~json +{ + "type": "object", + "properties": { + "numbers": {"$ref": "numbers.schema.json"} + } +} +~~~ + +where `numbers.schema.json` refers +(via a suitable `IRemoteSchemaDocumentProvider`) +to this schema: + +~~~json +{ + "type": "array", + "items": {"type": "number"} +} +~~~ + +produces the following error object: + +~~~json +{ + "type": { + "instanceRef": "#/numbers/2", + "schemaRef": "numbers.schema.json#/items", + "expected": ["number"], + "actual": "string" + } +} +~~~ + +## Validation keywords for numbers {#Numbers} + +### multipleOf {#multipleof} + +* `expected`: required number strictly greater than 0. + The value of the `multipleOf` keyword specified in the schema. +* `actual`: required number. + The instance value. + +### maximum {#maximum} + +* `expected`: required number. + The value of the `maximum` keyword specified in the schema. +* `exclusiveMaximum`: optional boolean. + This will be true if the schema specified `"exclusiveMaximum": true`, + and will be omitted otherwise. +* `actual`: required number. + The instance value. + +### minimum {#minimum} + +* `expected`: required number. + The value of the `minimum` keyword specified in the schema. +* `exclusiveMinimum`: optional boolean. + This will be true if the schema specified `"exclusiveMinimum": true`, + and will be omitted otherwise. +* `actual`: required number. + The instance value. + +## Validation keywords for strings {#Strings} + +### maxLength {#maxLength} + +* `expected`: required number greater than or equal to 0. + The value of the `maxLength` keyword specified in the schema. +* `actual`: required string. + The instance value. + +### minLength {#minLength} + +* `expected`: required number greater than or equal to 0. + The value of the `minLength` keyword specified in the schema. +* `actual`: required string. + The instance value. + +### pattern {#pattern} + +* `actual`: required string. + The instance value. + +(The expected pattern is not reported +because the internal representation in `SchemaDocument` +does not store the pattern in original string form.) + +## Validation keywords for arrays {#Arrays} + +### additionalItems {#additionalItems} + +This keyword is reported +when the value of `items` schema keyword is an array, +the value of `additionalItems` is `false`, +and the instance is an array +with more items than specified in the `items` array. + +* `disallowed`: required integer greater than or equal to 0. + The index of the first item that has no corresponding schema. + +### maxItems and minItems {#maxItems-minItems} + +* `expected`: required integer greater than or equal to 0. + The value of `maxItems` (respectively, `minItems`) + specified in the schema. +* `actual`: required integer greater than or equal to 0. + Number of items in the instance array. + +### uniqueItems {#uniqueItems} + +* `duplicates`: required array + whose items are integers greater than or equal to 0. + Indices of items of the instance that are equal. + +(RapidJSON only reports the first two equal items, +for performance reasons.) + +## Validation keywords for objects + +### maxProperties and minProperties {#maxProperties-minProperties} + +* `expected`: required integer greater than or equal to 0. + The value of `maxProperties` (respectively, `minProperties`) + specified in the schema. +* `actual`: required integer greater than or equal to 0. + Number of properties in the instance object. + +### required {#required} + +* `missing`: required array of one or more unique strings. + The names of properties + that are listed in the value of the `required` schema keyword + but not present in the instance object. + +### additionalProperties {#additionalProperties} + +This keyword is reported +when the schema specifies `additionalProperties: false` +and the name of a property of the instance is +neither listed in the `properties` keyword +nor matches any regular expression in the `patternProperties` keyword. + +* `disallowed`: required string. + Name of the offending property of the instance. + +(For performance reasons, +RapidJSON only reports the first such property encountered.) + +### dependencies {#dependencies} + +* `errors`: required object with one or more properties. + Names and values of its properties are described below. + +Recall that JSON Schema Draft 04 supports +*schema dependencies*, +where presence of a named *controlling* property +requires the instance object to be valid against a subschema, +and *property dependencies*, +where presence of a controlling property +requires other *dependent* properties to be also present. + +For a violated schema dependency, +`errors` will contain a property +with the name of the controlling property +and its value will be the error object +produced by validating the instance object +against the dependent schema. + +For a violated property dependency, +`errors` will contain a property +with the name of the controlling property +and its value will be an array of one or more unique strings +listing the missing dependent properties. + +## Validation keywords for any instance type {#AnyTypes} + +### enum {#enum} + +This keyword has no additional properties +beyond `instanceRef` and `schemaRef`. + +* The allowed values are not listed + because `SchemaDocument` does not store them in original form. +* The violating value is not reported + because it might be unwieldy. + +If you need to report these details to your users, +you can access the necessary information +by following `instanceRef` and `schemaRef`. + +### type {#type} + +* `expected`: required array of one or more unique strings, + each of which is one of the seven primitive types + defined by the JSON Schema Draft 04 Core specification. + Lists the types allowed by the `type` schema keyword. +* `actual`: required string, also one of seven primitive types. + The primitive type of the instance. + +### allOf, anyOf, and oneOf {#allOf-anyOf-oneOf} + +* `errors`: required array of at least one object. + There will be as many items as there are subschemas + in the `allOf`, `anyOf` or `oneOf` schema keyword, respectively. + Each item will be the error value + produced by validating the instance + against the corresponding subschema. + +For `allOf`, at least one error value will be non-empty. +For `anyOf`, all error values will be non-empty. +For `oneOf`, either all error values will be non-empty, +or more than one will be empty. + +### not {#not} + +This keyword has no additional properties +apart from `instanceRef` and `schemaRef`. -- cgit v1.2.3 From 8c182e51e76dced3cc998f3c37812118c9653231 Mon Sep 17 00:00:00 2001 From: Yuri Khan Date: Sat, 30 Sep 2017 20:16:03 +0700 Subject: Flatten allOf keyword violations --- include/rapidjson/schema.h | 4 +- test/unittest/schematest.cpp | 148 ++++++++++++++----------------------------- 2 files changed, 49 insertions(+), 103 deletions(-) diff --git a/include/rapidjson/schema.h b/include/rapidjson/schema.h index b4d1a261..e7c87f66 100644 --- a/include/rapidjson/schema.h +++ b/include/rapidjson/schema.h @@ -2011,7 +2011,9 @@ public: AddCurrentError(SchemaType::GetTypeString()); } void NotAllOf(ISchemaValidator** subvalidators, SizeType count) { - AddErrorArray(SchemaType::GetAllOfString(), subvalidators, count); + for (SizeType i = 0; i < count; ++i) { + MergeError(static_cast(subvalidators[i])->GetError()); + } } void NoneOf(ISchemaValidator** subvalidators, SizeType count) { AddErrorArray(SchemaType::GetAnyOfString(), subvalidators, count); diff --git a/test/unittest/schematest.cpp b/test/unittest/schematest.cpp index 5bf39f88..121d3861 100644 --- a/test/unittest/schematest.cpp +++ b/test/unittest/schematest.cpp @@ -236,15 +236,9 @@ TEST(SchemaValidator, AllOf) { VALIDATE(s, "\"ok\"", true); INVALIDATE(s, "\"too long\"", "", "allOf", "", - "{ \"allOf\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," - " \"errors\": [" - " {}," - " { \"maxLength\": { " - " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/1\", " - " \"expected\": 5, \"actual\": \"too long\"" - " }}" - " ]" + "{ \"maxLength\": { " + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/1\", " + " \"expected\": 5, \"actual\": \"too long\"" "}}"); } { @@ -254,14 +248,8 @@ TEST(SchemaValidator, AllOf) { VALIDATE(s, "\"No way\"", false); INVALIDATE(s, "-1", "", "allOf", "", - "{ \"allOf\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," - " \"errors\": [" - " { \"type\": { \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/0\"," - " \"expected\": [\"string\"], \"actual\": \"integer\"" - " }}," - " {}" - " ]" + "{ \"type\": { \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/0\"," + " \"expected\": [\"string\"], \"actual\": \"integer\"" "}}"); } } @@ -387,16 +375,11 @@ TEST(SchemaValidator, Ref_AllOf) { SchemaDocument s(sd); INVALIDATE(s, "{\"shipping_address\": {\"street_address\": \"1600 Pennsylvania Avenue NW\", \"city\": \"Washington\", \"state\": \"DC\"} }", "/properties/shipping_address", "allOf", "/shipping_address", - "{ \"allOf\": {" + "{ \"required\": {" " \"instanceRef\": \"#/shipping_address\"," - " \"schemaRef\": \"#/properties/shipping_address\"," - " \"errors\": [" - " {}," - " { \"required\": {" - " \"instanceRef\": \"#/shipping_address\"," - " \"schemaRef\": \"#/properties/shipping_address/allOf/1\"," - " \"missing\": [\"type\"]" - "}} ] }}"); + " \"schemaRef\": \"#/properties/shipping_address/allOf/1\"," + " \"missing\": [\"type\"]" + "}}"); VALIDATE(s, "{\"shipping_address\": {\"street_address\": \"1600 Pennsylvania Avenue NW\", \"city\": \"Washington\", \"state\": \"DC\", \"type\": \"business\"} }", true); } @@ -1537,87 +1520,48 @@ TEST(SchemaValidator, AllOf_Nested) { VALIDATE(s, "\"ok\"", true); VALIDATE(s, "\"OK\"", true); INVALIDATE(s, "\"okay\"", "", "allOf", "", - "{ \"allOf\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," - " \"errors\": [" - " {}, " - " {}, " - " { \"allOf\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2\"," - " \"errors\": [" - " {}, " - " { \"enum\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/1\"" - "}} ] }} ] }}"); + "{ \"enum\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/1\"" + "}}"); INVALIDATE(s, "\"o\"", "", "allOf", "", - "{ \"allOf\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," - " \"errors\": [" - " { \"minLength\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/0\"," - " \"expected\": 2, \"actual\": \"o\"" - " }}," - " {}," - " {}" - " ]" + "{ \"minLength\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/0\"," + " \"expected\": 2, \"actual\": \"o\"" "}}"); INVALIDATE(s, "\"n\"", "", "allOf", "", - "{ \"allOf\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," - " \"errors\": [" - " { \"minLength\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/0\"," - " \"expected\": 2, \"actual\": \"n\"" - " }}," - " {}, " - " { \"allOf\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2\"," - " \"errors\": [" - " { \"enum\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/0\"" - " }}," - " { \"enum\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/1\"" - "}} ] }} ] }}"); + "{ \"minLength\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/0\"," + " \"expected\": 2, \"actual\": \"n\"" + " }," + " \"enum\": [" + " {\"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/0\"}," + " {\"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/1\"}" + " ]" + "}") INVALIDATE(s, "\"too long\"", "", "allOf", "", - "{ \"allOf\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," - " \"errors\": [" - " {}, " - " { \"maxLength\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/1\"," - " \"expected\": 5, \"actual\": \"too long\"" - " }}," - " { \"allOf\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2\"," - " \"errors\": [" - " { \"enum\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/0\"" - " }}," - " { \"enum\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/1\"" - "}} ] }} ] }}"); + "{ \"maxLength\": {" + " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/1\"," + " \"expected\": 5, \"actual\": \"too long\"" + " }," + " \"enum\": [" + " {\"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/0\"}," + " {\"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/1\"}" + " ]" + "}"); INVALIDATE(s, "123", "", "allOf", "", - "{ \"allOf\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#\"," - " \"errors\": [" - " { \"type\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/0\"," - " \"expected\": [\"string\"], \"actual\": \"integer\"" - " }}," - " { \"type\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/1\"," - " \"expected\": [\"string\"], \"actual\": \"integer\"" - " }}," - " { \"allOf\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2\"," - " \"errors\": [" - " { \"enum\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/0\"" - " }}, " - " { \"enum\": {" - " \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/1\"" - "}} ] }} ] }}"); + "{ \"type\": [" + " { \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/0\"," + " \"expected\": [\"string\"], \"actual\": \"integer\"" + " }," + " { \"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/1\"," + " \"expected\": [\"string\"], \"actual\": \"integer\"" + " }" + " ]," + " \"enum\": [" + " {\"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/0\"}," + " {\"instanceRef\": \"#\", \"schemaRef\": \"#/allOf/2/allOf/1\"}" + " ]" + "}"); } TEST(SchemaValidator, EscapedPointer) { -- cgit v1.2.3