diff options
author | joaodasilva@chromium.org <joaodasilva@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2013-08-13 22:55:07 +0000 |
---|---|---|
committer | joaodasilva@chromium.org <joaodasilva@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2013-08-13 22:55:07 +0000 |
commit | fb1397cef99cab7b52130905de9006d52b28d0e6 (patch) | |
tree | 36787176f93388470ed6b8593b56915c3105e5d1 /components | |
parent | 475a87a928354bd896d4149f69de2c01185f6187 (diff) | |
download | chromium_src-fb1397cef99cab7b52130905de9006d52b28d0e6.zip chromium_src-fb1397cef99cab7b52130905de9006d52b28d0e6.tar.gz chromium_src-fb1397cef99cab7b52130905de9006d52b28d0e6.tar.bz2 |
Moved chrome/common/json_schema to components/json_schema.
BUG=271392
Review URL: https://chromiumcodereview.appspot.com/22807004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@217364 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'components')
21 files changed, 2096 insertions, 2 deletions
diff --git a/components/OWNERS b/components/OWNERS index 7884fe2..e24fd60 100644 --- a/components/OWNERS +++ b/components/OWNERS @@ -8,8 +8,11 @@ per-file breakpad.gypi=jochen@chromium.org per-file breakpad.gypi=rsesek@chromium.org per-file breakpad.gypi=thestig@chromium.org -per-file tracing*=jbauman@chromium.org -per-file tracing*=nduca@chromium.org +per-file json_schema.gypi=asargent@chromium.org +per-file json_schema.gypi=calamity@chromium.org +per-file json_schema.gypi=kalman@chromium.org +per-file json_schema.gypi=koz@chromium.org +per-file json_schema.gypi=mpcomplete@chromium.org per-file nacl*=bradchen@chromium.org per-file nacl*=bradnelson@chromium.org @@ -24,6 +27,9 @@ per-file navigation_interception.gypi=mkosiba@chromium.org per-file sessions.gypi=marja@chromium.org per-file sessions.gypi=sky@chromium.org +per-file tracing*=jbauman@chromium.org +per-file tracing*=nduca@chromium.org + per-file user_prefs.gypi=battre@chromium.org per-file user_prefs.gypi=bauerb@chromium.org per-file user_prefs.gypi=mnissler@chromium.org diff --git a/components/components.gyp b/components/components.gyp index 61c496c..fa458e1 100644 --- a/components/components.gyp +++ b/components/components.gyp @@ -15,6 +15,7 @@ 'breakpad.gypi', 'browser_context_keyed_service.gypi', 'components_tests.gypi', + 'json_schema.gypi', 'navigation_interception.gypi', 'sessions.gypi', 'user_prefs.gypi', diff --git a/components/components_tests.gypi b/components/components_tests.gypi index b8e5600..58b7151 100644 --- a/components/components_tests.gypi +++ b/components/components_tests.gypi @@ -13,6 +13,9 @@ 'auto_login_parser/auto_login_parser_unittest.cc', 'browser_context_keyed_service/browser_context_dependency_manager_unittest.cc', 'browser_context_keyed_service/dependency_graph_unittest.cc', + 'json_schema/json_schema_validator_unittest.cc', + 'json_schema/json_schema_validator_unittest_base.cc', + 'json_schema/json_schema_validator_unittest_base.h', 'navigation_interception/intercept_navigation_resource_throttle_unittest.cc', 'sessions/serialized_navigation_entry_unittest.cc', 'test/run_all_unittests.cc', @@ -38,6 +41,9 @@ # Dependencies of encryptor 'encryptor', + # Dependencies of json_schema + 'json_schema', + # Dependencies of intercept_navigation_resource_throttle_unittest.cc '../content/content.gyp:test_support_content', '../skia/skia.gyp:skia', diff --git a/components/components_unittests.isolate b/components/components_unittests.isolate index 0c18d8f..f60a380 100644 --- a/components/components_unittests.isolate +++ b/components/components_unittests.isolate @@ -8,6 +8,9 @@ 'isolate_dependency_tracked': [ '<(PRODUCT_DIR)/content_resources.pak', ], + 'isolate_dependency_untracked': [ + 'test/data/', + ], }, }], ], diff --git a/components/json_schema.gypi b/components/json_schema.gypi new file mode 100644 index 0000000..510f97d --- /dev/null +++ b/components/json_schema.gypi @@ -0,0 +1,25 @@ +# Copyright 2013 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +{ + 'targets': [ + { + 'target_name': 'json_schema', + 'type': 'static_library', + 'dependencies': [ + '../base/base.gyp:base', + '../ui/ui.gyp:ui', + ], + 'include_dirs': [ + '..', + ], + 'sources': [ + 'json_schema/json_schema_constants.cc', + 'json_schema/json_schema_constants.h', + 'json_schema/json_schema_validator.cc', + 'json_schema/json_schema_validator.h', + ], + }, + ], +} diff --git a/components/json_schema/DEPS b/components/json_schema/DEPS new file mode 100644 index 0000000..e7cf2c6f --- /dev/null +++ b/components/json_schema/DEPS @@ -0,0 +1,3 @@ +include_rules = [ + "+ui/base", +] diff --git a/components/json_schema/OWNERS b/components/json_schema/OWNERS new file mode 100644 index 0000000..f7e95c9 --- /dev/null +++ b/components/json_schema/OWNERS @@ -0,0 +1,5 @@ +asargent@chromium.org +calamity@chromium.org +kalman@chromium.org +koz@chromium.org +mpcomplete@chromium.org diff --git a/components/json_schema/README b/components/json_schema/README new file mode 100644 index 0000000..c7453db --- /dev/null +++ b/components/json_schema/README @@ -0,0 +1,6 @@ +The //components/json_schema component provides: + +a) JSON schema constants, which can be used to inspect schema objects. + +b) The JSONSchemaValidator class, which can be used to parse and validate JSON +schemas, and to validate JSON objects against the parsed schema. diff --git a/components/json_schema/json_schema_constants.cc b/components/json_schema/json_schema_constants.cc new file mode 100644 index 0000000..0152cfc --- /dev/null +++ b/components/json_schema/json_schema_constants.cc @@ -0,0 +1,38 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/json_schema/json_schema_constants.h" + +namespace json_schema_constants { + +const char kAdditionalProperties[] = "additionalProperties"; +const char kAny[] = "any"; +const char kArray[] = "array"; +const char kBoolean[] = "boolean"; +const char kChoices[] = "choices"; +const char kDescription[] = "description"; +const char kEnum[] = "enum"; +const char kId[] = "id"; +const char kInteger[] = "integer"; +const char kItems[] = "items"; +const char kMaximum[] = "maximum"; +const char kMaxItems[] = "maxItems"; +const char kMaxLength[] = "maxLength"; +const char kMinimum[] = "minimum"; +const char kMinItems[] = "minItems"; +const char kMinLength[] = "minLength"; +const char kNull[] = "null"; +const char kNumber[] = "number"; +const char kObject[] = "object"; +const char kOptional[] = "optional"; +const char kPattern[] = "pattern"; +const char kPatternProperties[] = "patternProperties"; +const char kProperties[] = "properties"; +const char kRef[] = "$ref"; +const char kSchema[] = "$schema"; +const char kString[] = "string"; +const char kTitle[] = "title"; +const char kType[] = "type"; + +} // namespace json_schema_constants diff --git a/components/json_schema/json_schema_constants.h b/components/json_schema/json_schema_constants.h new file mode 100644 index 0000000..5c64ebb --- /dev/null +++ b/components/json_schema/json_schema_constants.h @@ -0,0 +1,42 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_CONSTANTS_H_ +#define COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_CONSTANTS_H_ + +// These constants are shared by code that uses JSON schemas. +namespace json_schema_constants { + +extern const char kAdditionalProperties[]; +extern const char kAny[]; +extern const char kArray[]; +extern const char kBoolean[]; +extern const char kChoices[]; +extern const char kDescription[]; +extern const char kEnum[]; +extern const char kId[]; +extern const char kInteger[]; +extern const char kItems[]; +extern const char kMaximum[]; +extern const char kMaxItems[]; +extern const char kMaxLength[]; +extern const char kMinimum[]; +extern const char kMinItems[]; +extern const char kMinLength[]; +extern const char kNull[]; +extern const char kNumber[]; +extern const char kObject[]; +extern const char kOptional[]; +extern const char kPattern[]; +extern const char kPatternProperties[]; +extern const char kProperties[]; +extern const char kRef[]; +extern const char kSchema[]; +extern const char kString[]; +extern const char kTitle[]; +extern const char kType[]; + +} // namespace json_schema_constants + +#endif // COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_CONSTANTS_H_ diff --git a/components/json_schema/json_schema_validator.cc b/components/json_schema/json_schema_validator.cc new file mode 100644 index 0000000..3816a76 --- /dev/null +++ b/components/json_schema/json_schema_validator.cc @@ -0,0 +1,727 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/json_schema/json_schema_validator.h" + +#include <algorithm> +#include <cfloat> +#include <cmath> + +#include "base/json/json_reader.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" +#include "base/values.h" +#include "components/json_schema/json_schema_constants.h" +#include "ui/base/l10n/l10n_util.h" + +namespace schema = json_schema_constants; + +namespace { + +double GetNumberValue(const base::Value* value) { + double result = 0; + CHECK(value->GetAsDouble(&result)) + << "Unexpected value type: " << value->GetType(); + return result; +} + +bool IsValidType(const std::string& type) { + static const char* kValidTypes[] = { + schema::kAny, + schema::kArray, + schema::kBoolean, + schema::kInteger, + schema::kNull, + schema::kNumber, + schema::kObject, + schema::kString, + }; + const char** end = kValidTypes + arraysize(kValidTypes); + return std::find(kValidTypes, end, type) != end; +} + +// Maps a schema attribute name to its expected type. +struct ExpectedType { + const char* key; + base::Value::Type type; +}; + +// Helper for std::lower_bound. +bool CompareToString(const ExpectedType& entry, const std::string& key) { + return entry.key < key; +} + +bool IsValidSchema(const base::DictionaryValue* dict, std::string* error) { + // This array must be sorted, so that std::lower_bound can perform a + // binary search. + static const ExpectedType kExpectedTypes[] = { + // Note: kRef == "$ref", kSchema == "$schema" + { schema::kRef, base::Value::TYPE_STRING }, + { schema::kSchema, base::Value::TYPE_STRING }, + + { schema::kAdditionalProperties, base::Value::TYPE_DICTIONARY }, + { schema::kChoices, base::Value::TYPE_LIST }, + { schema::kDescription, base::Value::TYPE_STRING }, + { schema::kEnum, base::Value::TYPE_LIST }, + { schema::kId, base::Value::TYPE_STRING }, + { schema::kMaxItems, base::Value::TYPE_INTEGER }, + { schema::kMaxLength, base::Value::TYPE_INTEGER }, + { schema::kMaximum, base::Value::TYPE_DOUBLE }, + { schema::kMinItems, base::Value::TYPE_INTEGER }, + { schema::kMinLength, base::Value::TYPE_INTEGER }, + { schema::kMinimum, base::Value::TYPE_DOUBLE }, + { schema::kOptional, base::Value::TYPE_BOOLEAN }, + { schema::kProperties, base::Value::TYPE_DICTIONARY }, + { schema::kTitle, base::Value::TYPE_STRING }, + }; + + bool has_type = false; + const base::ListValue* list_value = NULL; + const base::DictionaryValue* dictionary_value = NULL; + std::string string_value; + + for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd(); it.Advance()) { + // Validate the "type" attribute, which may be a string or a list. + if (it.key() == schema::kType) { + switch (it.value().GetType()) { + case base::Value::TYPE_STRING: + it.value().GetAsString(&string_value); + if (!IsValidType(string_value)) { + *error = "Invalid value for type attribute"; + return false; + } + break; + case base::Value::TYPE_LIST: + it.value().GetAsList(&list_value); + for (size_t i = 0; i < list_value->GetSize(); ++i) { + if (!list_value->GetString(i, &string_value) || + !IsValidType(string_value)) { + *error = "Invalid value for type attribute"; + return false; + } + } + break; + default: + *error = "Invalid value for type attribute"; + return false; + } + has_type = true; + continue; + } + + // Validate the "items" attribute, which is a schema or a list of schemas. + if (it.key() == schema::kItems) { + if (it.value().GetAsDictionary(&dictionary_value)) { + if (!IsValidSchema(dictionary_value, error)) { + DCHECK(!error->empty()); + return false; + } + } else if (it.value().GetAsList(&list_value)) { + for (size_t i = 0; i < list_value->GetSize(); ++i) { + if (!list_value->GetDictionary(i, &dictionary_value)) { + *error = base::StringPrintf( + "Invalid entry in items attribute at index %d", + static_cast<int>(i)); + return false; + } + if (!IsValidSchema(dictionary_value, error)) { + DCHECK(!error->empty()); + return false; + } + } + } else { + *error = "Invalid value for items attribute"; + return false; + } + continue; + } + + // All the other attributes have a single valid type. + const ExpectedType* end = kExpectedTypes + arraysize(kExpectedTypes); + const ExpectedType* entry = std::lower_bound( + kExpectedTypes, end, it.key(), CompareToString); + if (entry == end || entry->key != it.key()) { + *error = base::StringPrintf("Invalid attribute %s", it.key().c_str()); + return false; + } + if (!it.value().IsType(entry->type)) { + *error = base::StringPrintf("Invalid value for %s attribute", + it.key().c_str()); + return false; + } + + // base::Value::TYPE_INTEGER attributes must be >= 0. + // This applies to "minItems", "maxItems", "minLength" and "maxLength". + if (it.value().IsType(base::Value::TYPE_INTEGER)) { + int integer_value; + it.value().GetAsInteger(&integer_value); + if (integer_value < 0) { + *error = base::StringPrintf("Value of %s must be >= 0, got %d", + it.key().c_str(), integer_value); + return false; + } + } + + // Validate the "properties" attribute. Each entry maps a key to a schema. + if (it.key() == schema::kProperties) { + it.value().GetAsDictionary(&dictionary_value); + for (base::DictionaryValue::Iterator it(*dictionary_value); + !it.IsAtEnd(); it.Advance()) { + if (!it.value().GetAsDictionary(&dictionary_value)) { + *error = "Invalid value for properties attribute"; + return false; + } + if (!IsValidSchema(dictionary_value, error)) { + DCHECK(!error->empty()); + return false; + } + } + } + + // Validate "additionalProperties" attribute, which is a schema. + if (it.key() == schema::kAdditionalProperties) { + it.value().GetAsDictionary(&dictionary_value); + if (!IsValidSchema(dictionary_value, error)) { + DCHECK(!error->empty()); + return false; + } + } + + // Validate the values contained in an "enum" attribute. + if (it.key() == schema::kEnum) { + it.value().GetAsList(&list_value); + for (size_t i = 0; i < list_value->GetSize(); ++i) { + const base::Value* value = NULL; + list_value->Get(i, &value); + switch (value->GetType()) { + case base::Value::TYPE_NULL: + case base::Value::TYPE_BOOLEAN: + case base::Value::TYPE_INTEGER: + case base::Value::TYPE_DOUBLE: + case base::Value::TYPE_STRING: + break; + default: + *error = "Invalid value in enum attribute"; + return false; + } + } + } + + // Validate the schemas contained in a "choices" attribute. + if (it.key() == schema::kChoices) { + it.value().GetAsList(&list_value); + for (size_t i = 0; i < list_value->GetSize(); ++i) { + if (!list_value->GetDictionary(i, &dictionary_value)) { + *error = "Invalid choices attribute"; + return false; + } + if (!IsValidSchema(dictionary_value, error)) { + DCHECK(!error->empty()); + return false; + } + } + } + } + + if (!has_type) { + *error = "Schema must have a type attribute"; + return false; + } + + return true; +} + +} // namespace + + +JSONSchemaValidator::Error::Error() { +} + +JSONSchemaValidator::Error::Error(const std::string& message) + : path(message) { +} + +JSONSchemaValidator::Error::Error(const std::string& path, + const std::string& message) + : path(path), message(message) { +} + + +const char JSONSchemaValidator::kUnknownTypeReference[] = + "Unknown schema reference: *."; +const char JSONSchemaValidator::kInvalidChoice[] = + "Value does not match any valid type choices."; +const char JSONSchemaValidator::kInvalidEnum[] = + "Value does not match any valid enum choices."; +const char JSONSchemaValidator::kObjectPropertyIsRequired[] = + "Property is required."; +const char JSONSchemaValidator::kUnexpectedProperty[] = + "Unexpected property."; +const char JSONSchemaValidator::kArrayMinItems[] = + "Array must have at least * items."; +const char JSONSchemaValidator::kArrayMaxItems[] = + "Array must not have more than * items."; +const char JSONSchemaValidator::kArrayItemRequired[] = + "Item is required."; +const char JSONSchemaValidator::kStringMinLength[] = + "String must be at least * characters long."; +const char JSONSchemaValidator::kStringMaxLength[] = + "String must not be more than * characters long."; +const char JSONSchemaValidator::kStringPattern[] = + "String must match the pattern: *."; +const char JSONSchemaValidator::kNumberMinimum[] = + "Value must not be less than *."; +const char JSONSchemaValidator::kNumberMaximum[] = + "Value must not be greater than *."; +const char JSONSchemaValidator::kInvalidType[] = + "Expected '*' but got '*'."; +const char JSONSchemaValidator::kInvalidTypeIntegerNumber[] = + "Expected 'integer' but got 'number', consider using Math.round()."; + + +// static +std::string JSONSchemaValidator::GetJSONSchemaType(const base::Value* value) { + switch (value->GetType()) { + case base::Value::TYPE_NULL: + return schema::kNull; + case base::Value::TYPE_BOOLEAN: + return schema::kBoolean; + case base::Value::TYPE_INTEGER: + return schema::kInteger; + case base::Value::TYPE_DOUBLE: { + double double_value = 0; + value->GetAsDouble(&double_value); + if (std::abs(double_value) <= std::pow(2.0, DBL_MANT_DIG) && + double_value == floor(double_value)) { + return schema::kInteger; + } else { + return schema::kNumber; + } + } + case base::Value::TYPE_STRING: + return schema::kString; + case base::Value::TYPE_DICTIONARY: + return schema::kObject; + case base::Value::TYPE_LIST: + return schema::kArray; + default: + NOTREACHED() << "Unexpected value type: " << value->GetType(); + return std::string(); + } +} + +// static +std::string JSONSchemaValidator::FormatErrorMessage(const std::string& format, + const std::string& s1) { + std::string ret_val = format; + ReplaceFirstSubstringAfterOffset(&ret_val, 0, "*", s1); + return ret_val; +} + +// static +std::string JSONSchemaValidator::FormatErrorMessage(const std::string& format, + const std::string& s1, + const std::string& s2) { + std::string ret_val = format; + ReplaceFirstSubstringAfterOffset(&ret_val, 0, "*", s1); + ReplaceFirstSubstringAfterOffset(&ret_val, 0, "*", s2); + return ret_val; +} + +// static +scoped_ptr<base::DictionaryValue> JSONSchemaValidator::IsValidSchema( + const std::string& schema, + std::string* error) { + base::JSONParserOptions options = base::JSON_PARSE_RFC; + scoped_ptr<base::Value> json( + base::JSONReader::ReadAndReturnError(schema, options, NULL, error)); + if (!json) + return scoped_ptr<base::DictionaryValue>(); + base::DictionaryValue* dict = NULL; + if (!json->GetAsDictionary(&dict)) { + *error = "Schema must be a JSON object"; + return scoped_ptr<base::DictionaryValue>(); + } + if (!::IsValidSchema(dict, error)) + return scoped_ptr<base::DictionaryValue>(); + ignore_result(json.release()); + return make_scoped_ptr(dict); +} + +JSONSchemaValidator::JSONSchemaValidator(base::DictionaryValue* schema) + : schema_root_(schema), default_allow_additional_properties_(false) { +} + +JSONSchemaValidator::JSONSchemaValidator(base::DictionaryValue* schema, + base::ListValue* types) + : schema_root_(schema), default_allow_additional_properties_(false) { + if (!types) + return; + + for (size_t i = 0; i < types->GetSize(); ++i) { + base::DictionaryValue* type = NULL; + CHECK(types->GetDictionary(i, &type)); + + std::string id; + CHECK(type->GetString(schema::kId, &id)); + + CHECK(types_.find(id) == types_.end()); + types_[id] = type; + } +} + +JSONSchemaValidator::~JSONSchemaValidator() {} + +bool JSONSchemaValidator::Validate(const base::Value* instance) { + errors_.clear(); + Validate(instance, schema_root_, std::string()); + return errors_.empty(); +} + +void JSONSchemaValidator::Validate(const base::Value* instance, + const base::DictionaryValue* schema, + const std::string& path) { + // If this schema defines itself as reference type, save it in this.types. + std::string id; + if (schema->GetString(schema::kId, &id)) { + TypeMap::iterator iter = types_.find(id); + if (iter == types_.end()) + types_[id] = schema; + else + DCHECK(iter->second == schema); + } + + // If the schema has a $ref property, the instance must validate against + // that schema. It must be present in types_ to be referenced. + std::string ref; + if (schema->GetString(schema::kRef, &ref)) { + TypeMap::iterator type = types_.find(ref); + if (type == types_.end()) { + errors_.push_back( + Error(path, FormatErrorMessage(kUnknownTypeReference, ref))); + } else { + Validate(instance, type->second, path); + } + return; + } + + // If the schema has a choices property, the instance must validate against at + // least one of the items in that array. + const base::ListValue* choices = NULL; + if (schema->GetList(schema::kChoices, &choices)) { + ValidateChoices(instance, choices, path); + return; + } + + // If the schema has an enum property, the instance must be one of those + // values. + const base::ListValue* enumeration = NULL; + if (schema->GetList(schema::kEnum, &enumeration)) { + ValidateEnum(instance, enumeration, path); + return; + } + + std::string type; + schema->GetString(schema::kType, &type); + CHECK(!type.empty()); + if (type != schema::kAny) { + if (!ValidateType(instance, type, path)) + return; + + // These casts are safe because of checks in ValidateType(). + if (type == schema::kObject) { + ValidateObject(static_cast<const base::DictionaryValue*>(instance), + schema, + path); + } else if (type == schema::kArray) { + ValidateArray(static_cast<const base::ListValue*>(instance), + schema, path); + } else if (type == schema::kString) { + // Intentionally NOT downcasting to StringValue*. TYPE_STRING only implies + // GetAsString() can safely be carried out, not that it's a StringValue. + ValidateString(instance, schema, path); + } else if (type == schema::kNumber || type == schema::kInteger) { + ValidateNumber(instance, schema, path); + } else if (type != schema::kBoolean && type != schema::kNull) { + NOTREACHED() << "Unexpected type: " << type; + } + } +} + +void JSONSchemaValidator::ValidateChoices(const base::Value* instance, + const base::ListValue* choices, + const std::string& path) { + size_t original_num_errors = errors_.size(); + + for (size_t i = 0; i < choices->GetSize(); ++i) { + const base::DictionaryValue* choice = NULL; + CHECK(choices->GetDictionary(i, &choice)); + + Validate(instance, choice, path); + if (errors_.size() == original_num_errors) + return; + + // We discard the error from each choice. We only want to know if any of the + // validations succeeded. + errors_.resize(original_num_errors); + } + + // Now add a generic error that no choices matched. + errors_.push_back(Error(path, kInvalidChoice)); + return; +} + +void JSONSchemaValidator::ValidateEnum(const base::Value* instance, + const base::ListValue* choices, + const std::string& path) { + for (size_t i = 0; i < choices->GetSize(); ++i) { + const base::Value* choice = NULL; + CHECK(choices->Get(i, &choice)); + switch (choice->GetType()) { + case base::Value::TYPE_NULL: + case base::Value::TYPE_BOOLEAN: + case base::Value::TYPE_STRING: + if (instance->Equals(choice)) + return; + break; + + case base::Value::TYPE_INTEGER: + case base::Value::TYPE_DOUBLE: + if (instance->IsType(base::Value::TYPE_INTEGER) || + instance->IsType(base::Value::TYPE_DOUBLE)) { + if (GetNumberValue(choice) == GetNumberValue(instance)) + return; + } + break; + + default: + NOTREACHED() << "Unexpected type in enum: " << choice->GetType(); + } + } + + errors_.push_back(Error(path, kInvalidEnum)); +} + +void JSONSchemaValidator::ValidateObject(const base::DictionaryValue* instance, + const base::DictionaryValue* schema, + const std::string& path) { + const base::DictionaryValue* properties = NULL; + schema->GetDictionary(schema::kProperties, &properties); + if (properties) { + for (base::DictionaryValue::Iterator it(*properties); !it.IsAtEnd(); + it.Advance()) { + std::string prop_path = path.empty() ? it.key() : (path + "." + it.key()); + const base::DictionaryValue* prop_schema = NULL; + CHECK(it.value().GetAsDictionary(&prop_schema)); + + const base::Value* prop_value = NULL; + if (instance->Get(it.key(), &prop_value)) { + Validate(prop_value, prop_schema, prop_path); + } else { + // Properties are required unless there is an optional field set to + // 'true'. + bool is_optional = false; + prop_schema->GetBoolean(schema::kOptional, &is_optional); + if (!is_optional) { + errors_.push_back(Error(prop_path, kObjectPropertyIsRequired)); + } + } + } + } + + const base::DictionaryValue* additional_properties_schema = NULL; + if (SchemaAllowsAnyAdditionalItems(schema, &additional_properties_schema)) + return; + + // Validate additional properties. + for (base::DictionaryValue::Iterator it(*instance); !it.IsAtEnd(); + it.Advance()) { + if (properties && properties->HasKey(it.key())) + continue; + + std::string prop_path = path.empty() ? it.key() : path + "." + it.key(); + if (!additional_properties_schema) { + errors_.push_back(Error(prop_path, kUnexpectedProperty)); + } else { + Validate(&it.value(), additional_properties_schema, prop_path); + } + } +} + +void JSONSchemaValidator::ValidateArray(const base::ListValue* instance, + const base::DictionaryValue* schema, + const std::string& path) { + const base::DictionaryValue* single_type = NULL; + size_t instance_size = instance->GetSize(); + if (schema->GetDictionary(schema::kItems, &single_type)) { + int min_items = 0; + if (schema->GetInteger(schema::kMinItems, &min_items)) { + CHECK(min_items >= 0); + if (instance_size < static_cast<size_t>(min_items)) { + errors_.push_back(Error(path, FormatErrorMessage( + kArrayMinItems, base::IntToString(min_items)))); + } + } + + int max_items = 0; + if (schema->GetInteger(schema::kMaxItems, &max_items)) { + CHECK(max_items >= 0); + if (instance_size > static_cast<size_t>(max_items)) { + errors_.push_back(Error(path, FormatErrorMessage( + kArrayMaxItems, base::IntToString(max_items)))); + } + } + + // If the items property is a single schema, each item in the array must + // validate against that schema. + for (size_t i = 0; i < instance_size; ++i) { + const base::Value* item = NULL; + CHECK(instance->Get(i, &item)); + std::string i_str = base::Uint64ToString(i); + std::string item_path = path.empty() ? i_str : (path + "." + i_str); + Validate(item, single_type, item_path); + } + + return; + } + + // Otherwise, the list must be a tuple type, where each item in the list has a + // particular schema. + ValidateTuple(instance, schema, path); +} + +void JSONSchemaValidator::ValidateTuple(const base::ListValue* instance, + const base::DictionaryValue* schema, + const std::string& path) { + const base::ListValue* tuple_type = NULL; + schema->GetList(schema::kItems, &tuple_type); + size_t tuple_size = tuple_type ? tuple_type->GetSize() : 0; + if (tuple_type) { + for (size_t i = 0; i < tuple_size; ++i) { + std::string i_str = base::Uint64ToString(i); + std::string item_path = path.empty() ? i_str : (path + "." + i_str); + const base::DictionaryValue* item_schema = NULL; + CHECK(tuple_type->GetDictionary(i, &item_schema)); + const base::Value* item_value = NULL; + instance->Get(i, &item_value); + if (item_value && item_value->GetType() != base::Value::TYPE_NULL) { + Validate(item_value, item_schema, item_path); + } else { + bool is_optional = false; + item_schema->GetBoolean(schema::kOptional, &is_optional); + if (!is_optional) { + errors_.push_back(Error(item_path, kArrayItemRequired)); + return; + } + } + } + } + + const base::DictionaryValue* additional_properties_schema = NULL; + if (SchemaAllowsAnyAdditionalItems(schema, &additional_properties_schema)) + return; + + size_t instance_size = instance->GetSize(); + if (additional_properties_schema) { + // Any additional properties must validate against the additionalProperties + // schema. + for (size_t i = tuple_size; i < instance_size; ++i) { + std::string i_str = base::Uint64ToString(i); + std::string item_path = path.empty() ? i_str : (path + "." + i_str); + const base::Value* item_value = NULL; + CHECK(instance->Get(i, &item_value)); + Validate(item_value, additional_properties_schema, item_path); + } + } else if (instance_size > tuple_size) { + errors_.push_back(Error(path, FormatErrorMessage( + kArrayMaxItems, base::Uint64ToString(tuple_size)))); + } +} + +void JSONSchemaValidator::ValidateString(const base::Value* instance, + const base::DictionaryValue* schema, + const std::string& path) { + std::string value; + CHECK(instance->GetAsString(&value)); + + int min_length = 0; + if (schema->GetInteger(schema::kMinLength, &min_length)) { + CHECK(min_length >= 0); + if (value.size() < static_cast<size_t>(min_length)) { + errors_.push_back(Error(path, FormatErrorMessage( + kStringMinLength, base::IntToString(min_length)))); + } + } + + int max_length = 0; + if (schema->GetInteger(schema::kMaxLength, &max_length)) { + CHECK(max_length >= 0); + if (value.size() > static_cast<size_t>(max_length)) { + errors_.push_back(Error(path, FormatErrorMessage( + kStringMaxLength, base::IntToString(max_length)))); + } + } + + CHECK(!schema->HasKey(schema::kPattern)) << "Pattern is not supported."; +} + +void JSONSchemaValidator::ValidateNumber(const base::Value* instance, + const base::DictionaryValue* schema, + const std::string& path) { + double value = GetNumberValue(instance); + + // TODO(aa): It would be good to test that the double is not infinity or nan, + // but isnan and isinf aren't defined on Windows. + + double minimum = 0; + if (schema->GetDouble(schema::kMinimum, &minimum)) { + if (value < minimum) + errors_.push_back(Error(path, FormatErrorMessage( + kNumberMinimum, base::DoubleToString(minimum)))); + } + + double maximum = 0; + if (schema->GetDouble(schema::kMaximum, &maximum)) { + if (value > maximum) + errors_.push_back(Error(path, FormatErrorMessage( + kNumberMaximum, base::DoubleToString(maximum)))); + } +} + +bool JSONSchemaValidator::ValidateType(const base::Value* instance, + const std::string& expected_type, + const std::string& path) { + std::string actual_type = GetJSONSchemaType(instance); + if (expected_type == actual_type || + (expected_type == schema::kNumber && actual_type == schema::kInteger)) { + return true; + } else if (expected_type == schema::kInteger && + actual_type == schema::kNumber) { + errors_.push_back(Error(path, kInvalidTypeIntegerNumber)); + return false; + } else { + errors_.push_back(Error(path, FormatErrorMessage( + kInvalidType, expected_type, actual_type))); + return false; + } +} + +bool JSONSchemaValidator::SchemaAllowsAnyAdditionalItems( + const base::DictionaryValue* schema, + const base::DictionaryValue** additional_properties_schema) { + // If the validator allows additional properties globally, and this schema + // doesn't override, then we can exit early. + schema->GetDictionary(schema::kAdditionalProperties, + additional_properties_schema); + + if (*additional_properties_schema) { + std::string additional_properties_type(schema::kAny); + CHECK((*additional_properties_schema)->GetString( + schema::kType, &additional_properties_type)); + return additional_properties_type == schema::kAny; + } else { + return default_allow_additional_properties_; + } +} diff --git a/components/json_schema/json_schema_validator.h b/components/json_schema/json_schema_validator.h new file mode 100644 index 0000000..4584a9d --- /dev/null +++ b/components/json_schema/json_schema_validator.h @@ -0,0 +1,235 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_VALIDATOR_H_ +#define COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_VALIDATOR_H_ + +#include <map> +#include <string> +#include <vector> + +#include "base/basictypes.h" +#include "base/memory/scoped_ptr.h" + +namespace base { +class DictionaryValue; +class ListValue; +class StringValue; +class Value; +} + +//============================================================================== +// This class implements a subset of JSON Schema. +// See: http://www.json.com/json-schema-proposal/ for more details. +// +// There is also an older JavaScript implementation of the same functionality in +// chrome/renderer/resources/json_schema.js. +// +// The following features of JSON Schema are not implemented: +// - requires +// - unique +// - disallow +// - union types (but replaced with 'choices') +// - number.maxDecimal +// - string.pattern +// +// The following properties are not applicable to the interface exposed by +// this class: +// - options +// - readonly +// - title +// - description +// - format +// - default +// - transient +// - hidden +// +// There are also these departures from the JSON Schema proposal: +// - null counts as 'unspecified' for optional values +// - added the 'choices' property, to allow specifying a list of possible types +// for a value +// - by default an "object" typed schema does not allow additional properties. +// if present, "additionalProperties" is to be a schema against which all +// additional properties will be validated. +//============================================================================== +class JSONSchemaValidator { + public: + // Details about a validation error. + struct Error { + Error(); + + explicit Error(const std::string& message); + + Error(const std::string& path, const std::string& message); + + // The path to the location of the error in the JSON structure. + std::string path; + + // An english message describing the error. + std::string message; + }; + + // Error messages. + static const char kUnknownTypeReference[]; + static const char kInvalidChoice[]; + static const char kInvalidEnum[]; + static const char kObjectPropertyIsRequired[]; + static const char kUnexpectedProperty[]; + static const char kArrayMinItems[]; + static const char kArrayMaxItems[]; + static const char kArrayItemRequired[]; + static const char kStringMinLength[]; + static const char kStringMaxLength[]; + static const char kStringPattern[]; + static const char kNumberMinimum[]; + static const char kNumberMaximum[]; + static const char kInvalidType[]; + static const char kInvalidTypeIntegerNumber[]; + + // Classifies a Value as one of the JSON schema primitive types. + static std::string GetJSONSchemaType(const base::Value* value); + + // Utility methods to format error messages. The first method can have one + // wildcard represented by '*', which is replaced with s1. The second method + // can have two, which are replaced by s1 and s2. + static std::string FormatErrorMessage(const std::string& format, + const std::string& s1); + static std::string FormatErrorMessage(const std::string& format, + const std::string& s1, + const std::string& s2); + + // Verifies if |schema| is a valid JSON v3 schema. When this validation passes + // then |schema| is valid JSON that can be parsed into a DictionaryValue, + // and that DictionaryValue can be used to build a JSONSchemaValidator. + // Returns the parsed DictionaryValue when |schema| validated, otherwise + // returns NULL. In that case, |error| contains an error description. + static scoped_ptr<base::DictionaryValue> IsValidSchema( + const std::string& schema, + std::string* error); + + // Creates a validator for the specified schema. + // + // NOTE: This constructor assumes that |schema| is well formed and valid. + // Errors will result in CHECK at runtime; this constructor should not be used + // with untrusted schemas. + explicit JSONSchemaValidator(base::DictionaryValue* schema); + + // Creates a validator for the specified schema and user-defined types. Each + // type must be a valid JSONSchema type description with an additional "id" + // field. Schema objects in |schema| can refer to these types with the "$ref" + // property. + // + // NOTE: This constructor assumes that |schema| and |types| are well-formed + // and valid. Errors will result in CHECK at runtime; this constructor should + // not be used with untrusted schemas. + JSONSchemaValidator(base::DictionaryValue* schema, base::ListValue* types); + + ~JSONSchemaValidator(); + + // Whether the validator allows additional items for objects and lists, beyond + // those defined by their schema, by default. + // + // This setting defaults to false: all items in an instance list or object + // must be defined by the corresponding schema. + // + // This setting can be overridden on individual object and list schemas by + // setting the "additionalProperties" field. + bool default_allow_additional_properties() const { + return default_allow_additional_properties_; + } + + void set_default_allow_additional_properties(bool val) { + default_allow_additional_properties_ = val; + } + + // Returns any errors from the last call to to Validate(). + const std::vector<Error>& errors() const { + return errors_; + } + + // Validates a JSON value. Returns true if the instance is valid, false + // otherwise. If false is returned any errors are available from the errors() + // getter. + bool Validate(const base::Value* instance); + + private: + typedef std::map<std::string, const base::DictionaryValue*> TypeMap; + + // Each of the below methods handle a subset of the validation process. The + // path paramater is the path to |instance| from the root of the instance tree + // and is used in error messages. + + // Validates any instance node against any schema node. This is called for + // every node in the instance tree, and it just decides which of the more + // detailed methods to call. + void Validate(const base::Value* instance, + const base::DictionaryValue* schema, + const std::string& path); + + // Validates a node against a list of possible schemas. If any one of the + // schemas match, the node is valid. + void ValidateChoices(const base::Value* instance, + const base::ListValue* choices, + const std::string& path); + + // Validates a node against a list of exact primitive values, eg 42, "foobar". + void ValidateEnum(const base::Value* instance, + const base::ListValue* choices, + const std::string& path); + + // Validates a JSON object against an object schema node. + void ValidateObject(const base::DictionaryValue* instance, + const base::DictionaryValue* schema, + const std::string& path); + + // Validates a JSON array against an array schema node. + void ValidateArray(const base::ListValue* instance, + const base::DictionaryValue* schema, + const std::string& path); + + // Validates a JSON array against an array schema node configured to be a + // tuple. In a tuple, there is one schema node for each item expected in the + // array. + void ValidateTuple(const base::ListValue* instance, + const base::DictionaryValue* schema, + const std::string& path); + + // Validate a JSON string against a string schema node. + void ValidateString(const base::Value* instance, + const base::DictionaryValue* schema, + const std::string& path); + + // Validate a JSON number against a number schema node. + void ValidateNumber(const base::Value* instance, + const base::DictionaryValue* schema, + const std::string& path); + + // Validates that the JSON node |instance| has |expected_type|. + bool ValidateType(const base::Value* instance, + const std::string& expected_type, + const std::string& path); + + // Returns true if |schema| will allow additional items of any type. + bool SchemaAllowsAnyAdditionalItems( + const base::DictionaryValue* schema, + const base::DictionaryValue** addition_items_schema); + + // The root schema node. + base::DictionaryValue* schema_root_; + + // Map of user-defined name to type. + TypeMap types_; + + // Whether we allow additional properties on objects by default. This can be + // overridden by the allow_additional_properties flag on an Object schema. + bool default_allow_additional_properties_; + + // Errors accumulated since the last call to Validate(). + std::vector<Error> errors_; + + + DISALLOW_COPY_AND_ASSIGN(JSONSchemaValidator); +}; + +#endif // COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_VALIDATOR_H_ diff --git a/components/json_schema/json_schema_validator_unittest.cc b/components/json_schema/json_schema_validator_unittest.cc new file mode 100644 index 0000000..4844ed1 --- /dev/null +++ b/components/json_schema/json_schema_validator_unittest.cc @@ -0,0 +1,129 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/values.h" +#include "components/json_schema/json_schema_validator.h" +#include "components/json_schema/json_schema_validator_unittest_base.h" +#include "testing/gtest/include/gtest/gtest.h" + +class JSONSchemaValidatorCPPTest : public JSONSchemaValidatorTestBase { + public: + JSONSchemaValidatorCPPTest() + : JSONSchemaValidatorTestBase(JSONSchemaValidatorTestBase::CPP) { + } + + protected: + virtual void ExpectValid(const std::string& test_source, + base::Value* instance, + base::DictionaryValue* schema, + base::ListValue* types) OVERRIDE { + JSONSchemaValidator validator(schema, types); + if (validator.Validate(instance)) + return; + + for (size_t i = 0; i < validator.errors().size(); ++i) { + ADD_FAILURE() << test_source << ": " + << validator.errors()[i].path << ": " + << validator.errors()[i].message; + } + } + + virtual void ExpectNotValid( + const std::string& test_source, + base::Value* instance, base::DictionaryValue* schema, + base::ListValue* types, + const std::string& expected_error_path, + const std::string& expected_error_message) OVERRIDE { + JSONSchemaValidator validator(schema, types); + if (validator.Validate(instance)) { + ADD_FAILURE() << test_source; + return; + } + + ASSERT_EQ(1u, validator.errors().size()) << test_source; + EXPECT_EQ(expected_error_path, validator.errors()[0].path) << test_source; + EXPECT_EQ(expected_error_message, validator.errors()[0].message) + << test_source; + } +}; + +TEST_F(JSONSchemaValidatorCPPTest, Test) { + RunTests(); +} + +TEST(JSONSchemaValidator, IsValidSchema) { + std::string error; + EXPECT_FALSE(JSONSchemaValidator::IsValidSchema("", &error)); + EXPECT_FALSE(JSONSchemaValidator::IsValidSchema("\0", &error)); + EXPECT_FALSE(JSONSchemaValidator::IsValidSchema("string", &error)); + EXPECT_FALSE(JSONSchemaValidator::IsValidSchema("\"string\"", &error)); + EXPECT_FALSE(JSONSchemaValidator::IsValidSchema("[]", &error)); + EXPECT_FALSE(JSONSchemaValidator::IsValidSchema("{}", &error)); + EXPECT_FALSE(JSONSchemaValidator::IsValidSchema( + "{ \"type\": 123 }", &error)); + EXPECT_FALSE(JSONSchemaValidator::IsValidSchema( + "{ \"type\": \"invalid\" }", &error)); + EXPECT_FALSE(JSONSchemaValidator::IsValidSchema( + "{" + " \"type\": \"object\"," + " \"properties\": []" // Invalid properties type. + "}", &error)); + EXPECT_FALSE(JSONSchemaValidator::IsValidSchema( + "{" + " \"type\": \"string\"," + " \"maxLength\": -1" // Must be >= 0. + "}", &error)); + EXPECT_FALSE(JSONSchemaValidator::IsValidSchema( + "{" + " \"type\": \"string\"," + " \"enum\": [ {} ]," // "enum" must contain simple values. + "}", &error)); + EXPECT_FALSE(JSONSchemaValidator::IsValidSchema( + "{" + " \"type\": \"array\"," + " \"items\": [ 123 ]," // "items" must contain a schema or schemas. + "}", &error)); + EXPECT_TRUE(JSONSchemaValidator::IsValidSchema( + "{ \"type\": \"object\" }", &error)) << error; + EXPECT_TRUE(JSONSchemaValidator::IsValidSchema( + "{ \"type\": [\"object\", \"array\"] }", &error)) << error; + EXPECT_TRUE(JSONSchemaValidator::IsValidSchema( + "{" + " \"type\": [\"object\", \"array\"]," + " \"properties\": {" + " \"string-property\": {" + " \"type\": \"string\"," + " \"minLength\": 1," + " \"maxLength\": 100," + " \"title\": \"The String Policy\"," + " \"description\": \"This policy controls the String widget.\"" + " }," + " \"integer-property\": {" + " \"type\": \"number\"," + " \"minimum\": 1000.0," + " \"maximum\": 9999.0" + " }," + " \"enum-property\": {" + " \"type\": \"integer\"," + " \"enum\": [0, 1, 10, 100]" + " }," + " \"items-property\": {" + " \"type\": \"array\"," + " \"items\": {" + " \"type\": \"string\"" + " }" + " }," + " \"items-list-property\": {" + " \"type\": \"array\"," + " \"items\": [" + " { \"type\": \"string\" }," + " { \"type\": \"integer\" }" + " ]" + " }" + " }," + " \"additionalProperties\": {" + " \"type\": \"any\"" + " }" + "}", &error)) << error; +} diff --git a/components/json_schema/json_schema_validator_unittest_base.cc b/components/json_schema/json_schema_validator_unittest_base.cc new file mode 100644 index 0000000..2e936a2 --- /dev/null +++ b/components/json_schema/json_schema_validator_unittest_base.cc @@ -0,0 +1,730 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/json_schema/json_schema_validator_unittest_base.h" + +#include <cfloat> +#include <cmath> +#include <limits> + +#include "base/base_paths.h" +#include "base/file_util.h" +#include "base/json/json_file_value_serializer.h" +#include "base/logging.h" +#include "base/memory/scoped_ptr.h" +#include "base/path_service.h" +#include "base/strings/stringprintf.h" +#include "base/values.h" +#include "components/json_schema/json_schema_constants.h" +#include "components/json_schema/json_schema_validator.h" + +namespace schema = json_schema_constants; + +namespace { + +#define TEST_SOURCE base::StringPrintf("%s:%i", __FILE__, __LINE__) + +base::Value* LoadValue(const std::string& filename) { + base::FilePath path; + PathService::Get(base::DIR_SOURCE_ROOT, &path); + path = path.AppendASCII("components") + .AppendASCII("test") + .AppendASCII("data") + .AppendASCII("json_schema") + .AppendASCII(filename); + EXPECT_TRUE(base::PathExists(path)); + + std::string error_message; + JSONFileValueSerializer serializer(path); + base::Value* result = serializer.Deserialize(NULL, &error_message); + if (!result) + ADD_FAILURE() << "Could not parse JSON: " << error_message; + return result; +} + +base::Value* LoadValue(const std::string& filename, base::Value::Type type) { + scoped_ptr<base::Value> result(LoadValue(filename)); + if (!result.get()) + return NULL; + if (!result->IsType(type)) { + ADD_FAILURE() << "Expected type " << type << ", got: " << result->GetType(); + return NULL; + } + return result.release(); +} + +base::ListValue* LoadList(const std::string& filename) { + return static_cast<base::ListValue*>( + LoadValue(filename, base::Value::TYPE_LIST)); +} + +base::DictionaryValue* LoadDictionary(const std::string& filename) { + return static_cast<base::DictionaryValue*>( + LoadValue(filename, base::Value::TYPE_DICTIONARY)); +} + +} // namespace + + +JSONSchemaValidatorTestBase::JSONSchemaValidatorTestBase( + JSONSchemaValidatorTestBase::ValidatorType type) + : type_(type) { +} + +void JSONSchemaValidatorTestBase::RunTests() { + TestComplex(); + TestStringPattern(); + TestEnum(); + TestChoices(); + TestExtends(); + TestObject(); + TestTypeReference(); + TestArrayTuple(); + TestArrayNonTuple(); + TestString(); + TestNumber(); + TestTypeClassifier(); + TestTypes(); +} + +void JSONSchemaValidatorTestBase::TestComplex() { + scoped_ptr<base::DictionaryValue> schema( + LoadDictionary("complex_schema.json")); + scoped_ptr<base::ListValue> instance(LoadList("complex_instance.json")); + + ASSERT_TRUE(schema.get()); + ASSERT_TRUE(instance.get()); + + ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); + instance->Remove(instance->GetSize() - 1, NULL); + ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); + instance->Append(new base::DictionaryValue()); + ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "1", + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kInvalidType, + schema::kNumber, + schema::kObject)); + instance->Remove(instance->GetSize() - 1, NULL); + + base::DictionaryValue* item = NULL; + ASSERT_TRUE(instance->GetDictionary(0, &item)); + item->SetString("url", "xxxxxxxxxxx"); + + ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, + "0.url", + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kStringMaxLength, "10")); +} + +void JSONSchemaValidatorTestBase::TestStringPattern() { + // Regex patterns not supported in CPP validator. + if (type_ == CPP) + return; + + scoped_ptr<base::DictionaryValue> schema(new base::DictionaryValue()); + schema->SetString(schema::kType, schema::kString); + schema->SetString(schema::kPattern, "foo+"); + + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::StringValue("foo")).get(), + schema.get(), NULL); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::StringValue("foooooo")).get(), + schema.get(), NULL); + ExpectNotValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::StringValue("bar")).get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kStringPattern, "foo+")); +} + +void JSONSchemaValidatorTestBase::TestEnum() { + scoped_ptr<base::DictionaryValue> schema(LoadDictionary("enum_schema.json")); + + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::StringValue("foo")).get(), + schema.get(), NULL); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(42)).get(), + schema.get(), NULL); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(false)).get(), + schema.get(), NULL); + + ExpectNotValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::StringValue("42")).get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::kInvalidEnum); + ExpectNotValid(TEST_SOURCE, + scoped_ptr<base::Value>(base::Value::CreateNullValue()).get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::kInvalidEnum); +} + +void JSONSchemaValidatorTestBase::TestChoices() { + scoped_ptr<base::DictionaryValue> schema( + LoadDictionary("choices_schema.json")); + + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(base::Value::CreateNullValue()).get(), + schema.get(), NULL); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(42)).get(), + schema.get(), NULL); + + scoped_ptr<base::DictionaryValue> instance(new base::DictionaryValue()); + instance->SetString("foo", "bar"); + ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); + + ExpectNotValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::StringValue("foo")).get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::kInvalidChoice); + ExpectNotValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::ListValue()).get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::kInvalidChoice); + + instance->SetInteger("foo", 42); + ExpectNotValid(TEST_SOURCE, + instance.get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::kInvalidChoice); +} + +void JSONSchemaValidatorTestBase::TestExtends() { + // TODO(aa): JS only +} + +void JSONSchemaValidatorTestBase::TestObject() { + scoped_ptr<base::DictionaryValue> schema(new base::DictionaryValue()); + schema->SetString(schema::kType, schema::kObject); + schema->SetString("properties.foo.type", schema::kString); + schema->SetString("properties.bar.type", schema::kInteger); + + scoped_ptr<base::DictionaryValue> instance(new base::DictionaryValue()); + instance->SetString("foo", "foo"); + instance->SetInteger("bar", 42); + + ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); + + instance->SetBoolean("extra", true); + ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, + "extra", JSONSchemaValidator::kUnexpectedProperty); + + instance->Remove("extra", NULL); + instance->Remove("bar", NULL); + ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "bar", + JSONSchemaValidator::kObjectPropertyIsRequired); + + instance->SetString("bar", "42"); + ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "bar", + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kInvalidType, + schema::kInteger, + schema::kString)); + + base::DictionaryValue* additional_properties = new base::DictionaryValue(); + additional_properties->SetString(schema::kType, schema::kAny); + schema->Set(schema::kAdditionalProperties, additional_properties); + + instance->SetInteger("bar", 42); + instance->SetBoolean("extra", true); + ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); + + instance->SetString("extra", "foo"); + ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); + + additional_properties->SetString(schema::kType, schema::kBoolean); + instance->SetBoolean("extra", true); + ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); + + instance->SetString("extra", "foo"); + ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, + "extra", JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kInvalidType, + schema::kBoolean, + schema::kString)); + + base::DictionaryValue* properties = NULL; + base::DictionaryValue* bar_property = NULL; + ASSERT_TRUE(schema->GetDictionary(schema::kProperties, &properties)); + ASSERT_TRUE(properties->GetDictionary("bar", &bar_property)); + + bar_property->SetBoolean(schema::kOptional, true); + instance->Remove("extra", NULL); + ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); + instance->Remove("bar", NULL); + ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); + instance->Set("bar", base::Value::CreateNullValue()); + ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, + "bar", JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kInvalidType, + schema::kInteger, + schema::kNull)); + instance->SetString("bar", "42"); + ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, + "bar", JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kInvalidType, + schema::kInteger, + schema::kString)); +} + +void JSONSchemaValidatorTestBase::TestTypeReference() { + scoped_ptr<base::ListValue> types(LoadList("reference_types.json")); + ASSERT_TRUE(types.get()); + + scoped_ptr<base::DictionaryValue> schema(new base::DictionaryValue()); + schema->SetString(schema::kType, schema::kObject); + schema->SetString("properties.foo.type", schema::kString); + schema->SetString("properties.bar.$ref", "Max10Int"); + schema->SetString("properties.baz.$ref", "MinLengthString"); + + scoped_ptr<base::DictionaryValue> schema_inline(new base::DictionaryValue()); + schema_inline->SetString(schema::kType, schema::kObject); + schema_inline->SetString("properties.foo.type", schema::kString); + schema_inline->SetString("properties.bar.id", "NegativeInt"); + schema_inline->SetString("properties.bar.type", schema::kInteger); + schema_inline->SetInteger("properties.bar.maximum", 0); + schema_inline->SetString("properties.baz.$ref", "NegativeInt"); + + scoped_ptr<base::DictionaryValue> instance(new base::DictionaryValue()); + instance->SetString("foo", "foo"); + instance->SetInteger("bar", 4); + instance->SetString("baz", "ab"); + + scoped_ptr<base::DictionaryValue> instance_inline( + new base::DictionaryValue()); + instance_inline->SetString("foo", "foo"); + instance_inline->SetInteger("bar", -4); + instance_inline->SetInteger("baz", -2); + + ExpectValid(TEST_SOURCE, instance.get(), schema.get(), types.get()); + ExpectValid(TEST_SOURCE, instance_inline.get(), schema_inline.get(), NULL); + + // Validation failure, but successful schema reference. + instance->SetString("baz", "a"); + ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), types.get(), + "baz", JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kStringMinLength, "2")); + + instance_inline->SetInteger("bar", 20); + ExpectNotValid(TEST_SOURCE, instance_inline.get(), schema_inline.get(), NULL, + "bar", JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kNumberMaximum, "0")); + + // Remove MinLengthString type. + types->Remove(types->GetSize() - 1, NULL); + instance->SetString("baz", "ab"); + ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), types.get(), + "bar", JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kUnknownTypeReference, + "Max10Int")); + + // Remove internal type "NegativeInt". + schema_inline->Remove("properties.bar", NULL); + instance_inline->Remove("bar", NULL); + ExpectNotValid(TEST_SOURCE, instance_inline.get(), schema_inline.get(), NULL, + "baz", JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kUnknownTypeReference, + "NegativeInt")); +} + +void JSONSchemaValidatorTestBase::TestArrayTuple() { + scoped_ptr<base::DictionaryValue> schema( + LoadDictionary("array_tuple_schema.json")); + ASSERT_TRUE(schema.get()); + + scoped_ptr<base::ListValue> instance(new base::ListValue()); + instance->Append(new base::StringValue("42")); + instance->Append(new base::FundamentalValue(42)); + + ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); + + instance->Append(new base::StringValue("anything")); + ExpectNotValid(TEST_SOURCE, + instance.get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kArrayMaxItems, "2")); + + instance->Remove(1, NULL); + instance->Remove(1, NULL); + ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "1", + JSONSchemaValidator::kArrayItemRequired); + + instance->Set(0, new base::FundamentalValue(42)); + instance->Append(new base::FundamentalValue(42)); + ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "0", + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kInvalidType, + schema::kString, + schema::kInteger)); + + base::DictionaryValue* additional_properties = new base::DictionaryValue(); + additional_properties->SetString(schema::kType, schema::kAny); + schema->Set(schema::kAdditionalProperties, additional_properties); + instance->Set(0, new base::StringValue("42")); + instance->Append(new base::StringValue("anything")); + ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); + instance->Set(2, new base::ListValue()); + ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); + + additional_properties->SetString(schema::kType, schema::kBoolean); + ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "2", + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kInvalidType, + schema::kBoolean, + schema::kArray)); + instance->Set(2, new base::FundamentalValue(false)); + ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); + + base::ListValue* items_schema = NULL; + base::DictionaryValue* item0_schema = NULL; + ASSERT_TRUE(schema->GetList(schema::kItems, &items_schema)); + ASSERT_TRUE(items_schema->GetDictionary(0, &item0_schema)); + item0_schema->SetBoolean(schema::kOptional, true); + instance->Remove(2, NULL); + ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); + // TODO(aa): I think this is inconsistent with the handling of NULL+optional + // for objects. + instance->Set(0, base::Value::CreateNullValue()); + ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); + instance->Set(0, new base::FundamentalValue(42)); + ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "0", + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kInvalidType, + schema::kString, + schema::kInteger)); +} + +void JSONSchemaValidatorTestBase::TestArrayNonTuple() { + scoped_ptr<base::DictionaryValue> schema(new base::DictionaryValue()); + schema->SetString(schema::kType, schema::kArray); + schema->SetString("items.type", schema::kString); + schema->SetInteger(schema::kMinItems, 2); + schema->SetInteger(schema::kMaxItems, 3); + + scoped_ptr<base::ListValue> instance(new base::ListValue()); + instance->Append(new base::StringValue("x")); + instance->Append(new base::StringValue("x")); + + ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); + instance->Append(new base::StringValue("x")); + ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); + + instance->Append(new base::StringValue("x")); + ExpectNotValid(TEST_SOURCE, + instance.get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kArrayMaxItems, "3")); + instance->Remove(1, NULL); + instance->Remove(1, NULL); + instance->Remove(1, NULL); + ExpectNotValid(TEST_SOURCE, + instance.get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kArrayMinItems, "2")); + + instance->Remove(1, NULL); + instance->Append(new base::FundamentalValue(42)); + ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "1", + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kInvalidType, + schema::kString, + schema::kInteger)); +} + +void JSONSchemaValidatorTestBase::TestString() { + scoped_ptr<base::DictionaryValue> schema(new base::DictionaryValue()); + schema->SetString(schema::kType, schema::kString); + schema->SetInteger(schema::kMinLength, 1); + schema->SetInteger(schema::kMaxLength, 10); + + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::StringValue("x")).get(), + schema.get(), NULL); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>( + new base::StringValue("xxxxxxxxxx")).get(), + schema.get(), NULL); + + ExpectNotValid( + TEST_SOURCE, + scoped_ptr<base::Value>(new base::StringValue(std::string())).get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kStringMinLength, "1")); + ExpectNotValid( + TEST_SOURCE, + scoped_ptr<base::Value>(new base::StringValue("xxxxxxxxxxx")).get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kStringMaxLength, "10")); +} + +void JSONSchemaValidatorTestBase::TestNumber() { + scoped_ptr<base::DictionaryValue> schema(new base::DictionaryValue()); + schema->SetString(schema::kType, schema::kNumber); + schema->SetInteger(schema::kMinimum, 1); + schema->SetInteger(schema::kMaximum, 100); + schema->SetInteger("maxDecimal", 2); + + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(1)).get(), + schema.get(), NULL); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(50)).get(), + schema.get(), NULL); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(100)).get(), + schema.get(), NULL); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(88.88)).get(), + schema.get(), NULL); + + ExpectNotValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(0.5)).get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kNumberMinimum, "1")); + ExpectNotValid( + TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(100.1)).get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kNumberMaximum, "100")); +} + +void JSONSchemaValidatorTestBase::TestTypeClassifier() { + EXPECT_EQ(std::string(schema::kBoolean), + JSONSchemaValidator::GetJSONSchemaType( + scoped_ptr<base::Value>( + new base::FundamentalValue(true)).get())); + EXPECT_EQ(std::string(schema::kBoolean), + JSONSchemaValidator::GetJSONSchemaType( + scoped_ptr<base::Value>( + new base::FundamentalValue(false)).get())); + + // It doesn't matter whether the C++ type is 'integer' or 'real'. If the + // number is integral and within the representable range of integers in + // double, it's classified as 'integer'. + EXPECT_EQ(std::string(schema::kInteger), + JSONSchemaValidator::GetJSONSchemaType( + scoped_ptr<base::Value>(new base::FundamentalValue(42)).get())); + EXPECT_EQ(std::string(schema::kInteger), + JSONSchemaValidator::GetJSONSchemaType( + scoped_ptr<base::Value>(new base::FundamentalValue(0)).get())); + EXPECT_EQ(std::string(schema::kInteger), + JSONSchemaValidator::GetJSONSchemaType( + scoped_ptr<base::Value>(new base::FundamentalValue(42)).get())); + EXPECT_EQ(std::string(schema::kInteger), + JSONSchemaValidator::GetJSONSchemaType(scoped_ptr<base::Value>( + new base::FundamentalValue(pow(2.0, DBL_MANT_DIG))).get())); + EXPECT_EQ(std::string(schema::kInteger), + JSONSchemaValidator::GetJSONSchemaType(scoped_ptr<base::Value>( + new base::FundamentalValue(pow(-2.0, DBL_MANT_DIG))).get())); + + // "number" is only used for non-integral numbers, or numbers beyond what + // double can accurately represent. + EXPECT_EQ(std::string(schema::kNumber), + JSONSchemaValidator::GetJSONSchemaType( + scoped_ptr<base::Value>( + new base::FundamentalValue(88.8)).get())); + EXPECT_EQ(std::string(schema::kNumber), + JSONSchemaValidator::GetJSONSchemaType(scoped_ptr<base::Value>( + new base::FundamentalValue(pow(2.0, DBL_MANT_DIG) * 2)).get())); + EXPECT_EQ(std::string(schema::kNumber), + JSONSchemaValidator::GetJSONSchemaType(scoped_ptr<base::Value>( + new base::FundamentalValue( + pow(-2.0, DBL_MANT_DIG) * 2)).get())); + + EXPECT_EQ(std::string(schema::kString), + JSONSchemaValidator::GetJSONSchemaType( + scoped_ptr<base::Value>(new base::StringValue("foo")).get())); + EXPECT_EQ(std::string(schema::kArray), + JSONSchemaValidator::GetJSONSchemaType( + scoped_ptr<base::Value>(new base::ListValue()).get())); + EXPECT_EQ(std::string(schema::kObject), + JSONSchemaValidator::GetJSONSchemaType( + scoped_ptr<base::Value>(new base::DictionaryValue()).get())); + EXPECT_EQ(std::string(schema::kNull), + JSONSchemaValidator::GetJSONSchemaType( + scoped_ptr<base::Value>(base::Value::CreateNullValue()).get())); +} + +void JSONSchemaValidatorTestBase::TestTypes() { + scoped_ptr<base::DictionaryValue> schema(new base::DictionaryValue()); + + // valid + schema->SetString(schema::kType, schema::kObject); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::DictionaryValue()).get(), + schema.get(), NULL); + + schema->SetString(schema::kType, schema::kArray); + ExpectValid(TEST_SOURCE, scoped_ptr<base::Value>(new base::ListValue()).get(), + schema.get(), NULL); + + schema->SetString(schema::kType, schema::kString); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::StringValue("foobar")).get(), + schema.get(), NULL); + + schema->SetString(schema::kType, schema::kNumber); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(88.8)).get(), + schema.get(), NULL); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(42)).get(), + schema.get(), NULL); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(42)).get(), + schema.get(), NULL); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(0)).get(), + schema.get(), NULL); + + schema->SetString(schema::kType, schema::kInteger); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(42)).get(), + schema.get(), NULL); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(42)).get(), + schema.get(), NULL); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(0)).get(), + schema.get(), NULL); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>( + new base::FundamentalValue(pow(2.0, DBL_MANT_DIG))).get(), + schema.get(), NULL); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>( + new base::FundamentalValue(pow(-2.0, DBL_MANT_DIG))).get(), + schema.get(), NULL); + + schema->SetString(schema::kType, schema::kBoolean); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(false)).get(), + schema.get(), NULL); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(true)).get(), + schema.get(), NULL); + + schema->SetString(schema::kType, schema::kNull); + ExpectValid(TEST_SOURCE, + scoped_ptr<base::Value>(base::Value::CreateNullValue()).get(), + schema.get(), NULL); + + // not valid + schema->SetString(schema::kType, schema::kObject); + ExpectNotValid( + TEST_SOURCE, + scoped_ptr<base::Value>(new base::ListValue()).get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kInvalidType, schema::kObject, schema::kArray)); + + schema->SetString(schema::kType, schema::kObject); + ExpectNotValid( + TEST_SOURCE, + scoped_ptr<base::Value>(base::Value::CreateNullValue()).get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kInvalidType, schema::kObject, schema::kNull)); + + schema->SetString(schema::kType, schema::kArray); + ExpectNotValid( + TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(42)).get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kInvalidType, schema::kArray, schema::kInteger)); + + schema->SetString(schema::kType, schema::kString); + ExpectNotValid( + TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(42)).get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::FormatErrorMessage(JSONSchemaValidator::kInvalidType, + schema::kString, + schema::kInteger)); + + schema->SetString(schema::kType, schema::kNumber); + ExpectNotValid( + TEST_SOURCE, + scoped_ptr<base::Value>(new base::StringValue("42")).get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kInvalidType, schema::kNumber, schema::kString)); + + schema->SetString(schema::kType, schema::kInteger); + ExpectNotValid( + TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(88.8)).get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::kInvalidTypeIntegerNumber); + + schema->SetString(schema::kType, schema::kBoolean); + ExpectNotValid( + TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(1)).get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::FormatErrorMessage(JSONSchemaValidator::kInvalidType, + schema::kBoolean, + schema::kInteger)); + + schema->SetString(schema::kType, schema::kNull); + ExpectNotValid( + TEST_SOURCE, + scoped_ptr<base::Value>(new base::FundamentalValue(false)).get(), + schema.get(), + NULL, + std::string(), + JSONSchemaValidator::FormatErrorMessage( + JSONSchemaValidator::kInvalidType, schema::kNull, schema::kBoolean)); +} diff --git a/components/json_schema/json_schema_validator_unittest_base.h b/components/json_schema/json_schema_validator_unittest_base.h new file mode 100644 index 0000000..7b4854e --- /dev/null +++ b/components/json_schema/json_schema_validator_unittest_base.h @@ -0,0 +1,63 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_VALIDATOR_UNITTEST_BASE_H_ +#define COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_VALIDATOR_UNITTEST_BASE_H_ + +#include "testing/gtest/include/gtest/gtest.h" + +namespace base { +class DictionaryValue; +class ListValue; +class Value; +} + +// Base class for unit tests for JSONSchemaValidator. There is currently only +// one implementation, JSONSchemaValidatorCPPTest. +// +// TODO(aa): Refactor chrome/test/data/json_schema_test.js into +// JSONSchemaValidatorJSTest that inherits from this. +class JSONSchemaValidatorTestBase : public testing::Test { + public: + enum ValidatorType { + CPP = 1, + JS = 2 + }; + + explicit JSONSchemaValidatorTestBase(ValidatorType type); + + void RunTests(); + + protected: + virtual void ExpectValid(const std::string& test_source, + base::Value* instance, + base::DictionaryValue* schema, + base::ListValue* types) = 0; + + virtual void ExpectNotValid(const std::string& test_source, + base::Value* instance, + base::DictionaryValue* schema, + base::ListValue* types, + const std::string& expected_error_path, + const std::string& expected_error_message) = 0; + + private: + void TestComplex(); + void TestStringPattern(); + void TestEnum(); + void TestChoices(); + void TestExtends(); + void TestObject(); + void TestTypeReference(); + void TestArrayTuple(); + void TestArrayNonTuple(); + void TestString(); + void TestNumber(); + void TestTypeClassifier(); + void TestTypes(); + + ValidatorType type_; +}; + +#endif // COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_VALIDATOR_UNITTEST_BASE_H_ diff --git a/components/test/data/json_schema/array_tuple_schema.json b/components/test/data/json_schema/array_tuple_schema.json new file mode 100644 index 0000000..a9bea68 --- /dev/null +++ b/components/test/data/json_schema/array_tuple_schema.json @@ -0,0 +1,11 @@ +{ + "type": "array", + "items": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] +} diff --git a/components/test/data/json_schema/choices_schema.json b/components/test/data/json_schema/choices_schema.json new file mode 100644 index 0000000..bd0f1a5 --- /dev/null +++ b/components/test/data/json_schema/choices_schema.json @@ -0,0 +1,7 @@ +{ + "choices": [ + { "type": "null" }, + { "type": "integer", "minimum": 42, "maximum": 43 }, + { "type": "object", "properties": { "foo": { "type": "string" } } } + ] +} diff --git a/components/test/data/json_schema/complex_instance.json b/components/test/data/json_schema/complex_instance.json new file mode 100644 index 0000000..1fb193b --- /dev/null +++ b/components/test/data/json_schema/complex_instance.json @@ -0,0 +1,9 @@ +[ + { + "id": 42, + "url": "google.com", + "index": 2, + "selected": true + }, + 88.8 +] diff --git a/components/test/data/json_schema/complex_schema.json b/components/test/data/json_schema/complex_schema.json new file mode 100644 index 0000000..bf0d6b8 --- /dev/null +++ b/components/test/data/json_schema/complex_schema.json @@ -0,0 +1,33 @@ +{ + "type": "array", + "items": [ + { + "type": "object", + "properties": { + "id": { + "type": "integer", + "minimum": 1 + }, + "url": { + "type": "string", + "maxLength": 10, + "optional": true + }, + "index": { + "type": "integer", + "minimum": 0, + "optional": true + }, + "selected": { + "type": "boolean", + "optional": true + } + } + }, + { + "type": "number", + "optional": true + } + ] +} + diff --git a/components/test/data/json_schema/enum_schema.json b/components/test/data/json_schema/enum_schema.json new file mode 100644 index 0000000..ae0c12a --- /dev/null +++ b/components/test/data/json_schema/enum_schema.json @@ -0,0 +1,3 @@ +{ + "enum": ["foo", 42, false] +} diff --git a/components/test/data/json_schema/reference_types.json b/components/test/data/json_schema/reference_types.json new file mode 100644 index 0000000..8f77334 --- /dev/null +++ b/components/test/data/json_schema/reference_types.json @@ -0,0 +1,12 @@ +[ + { + "id": "MinLengthString", + "type": "string", + "minLength": 2 + }, + { + "id": "Max10Int", + "type": "integer", + "maximum": 10 + } +] |