summaryrefslogtreecommitdiffstats
path: root/tools/json_schema_compiler
diff options
context:
space:
mode:
authormtytel@chromium.org <mtytel@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98>2012-07-16 21:47:24 +0000
committermtytel@chromium.org <mtytel@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98>2012-07-16 21:47:24 +0000
commitb741e8f6ccf1c6bdc5f4e98bd6751b085b7f7bbc (patch)
tree23087398a8a4e52beffc2c79d5af40595a9491d6 /tools/json_schema_compiler
parente275ae44b030d87722c700bb4ce94e82709b74fb (diff)
downloadchromium_src-b741e8f6ccf1c6bdc5f4e98bd6751b085b7f7bbc.zip
chromium_src-b741e8f6ccf1c6bdc5f4e98bd6751b085b7f7bbc.tar.gz
chromium_src-b741e8f6ccf1c6bdc5f4e98bd6751b085b7f7bbc.tar.bz2
JSON Schema Compiler: Add event compilation and allow multiple parameters to callbacks
Compiles events to objects that look similar to this: namespace OnObjectFired { struct SomeObject { ~SomeObject(); SomeObject(); enum State { STATE_FOO, STATE_BAR, STATE_BAZ, }; static scoped_ptr<Value> CreateEnumValue(State state); State state; // Returns a new DictionaryValue representing the serialized form of this // SomeObject object. Passes ownership to caller. scoped_ptr<DictionaryValue> ToValue() const; private: DISALLOW_COPY_AND_ASSIGN(SomeObject); }; Value* Create(const SomeObject& some_object); }; BUG=133757, 135237 TEST= Review URL: https://chromiumcodereview.appspot.com/10701012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146899 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'tools/json_schema_compiler')
-rw-r--r--tools/json_schema_compiler/cc_generator.py85
-rw-r--r--tools/json_schema_compiler/cpp_type_generator.py19
-rwxr-xr-xtools/json_schema_compiler/cpp_type_generator_test.py28
-rw-r--r--tools/json_schema_compiler/h_generator.py82
-rw-r--r--tools/json_schema_compiler/model.py69
-rwxr-xr-xtools/json_schema_compiler/model_test.py2
-rw-r--r--tools/json_schema_compiler/schema_bundle_generator.py7
-rw-r--r--tools/json_schema_compiler/test/additional_properties_unittest.cc20
-rw-r--r--tools/json_schema_compiler/test/any.json13
-rw-r--r--tools/json_schema_compiler/test/arrays_unittest.cc41
-rw-r--r--tools/json_schema_compiler/test/callbacks.json71
-rw-r--r--tools/json_schema_compiler/test/callbacks_unittest.cc35
-rw-r--r--tools/json_schema_compiler/test/choices.json29
-rw-r--r--tools/json_schema_compiler/test/choices_unittest.cc26
-rw-r--r--tools/json_schema_compiler/test/crossref_unittest.cc7
-rw-r--r--tools/json_schema_compiler/test/enums.json72
-rw-r--r--tools/json_schema_compiler/test/enums_unittest.cc56
-rw-r--r--tools/json_schema_compiler/test/forbidden.json39
-rw-r--r--tools/json_schema_compiler/test/functions_on_types_unittest.cc13
-rw-r--r--tools/json_schema_compiler/test/idl_schemas_unittest.cc21
-rw-r--r--tools/json_schema_compiler/test/json_schema_compiler_tests.gyp1
-rw-r--r--tools/json_schema_compiler/test/objects.json79
-rw-r--r--tools/json_schema_compiler/test/objects_unittest.cc31
-rw-r--r--tools/json_schema_compiler/test/simple_api.json35
-rw-r--r--tools/json_schema_compiler/test/simple_api_unittest.cc62
25 files changed, 737 insertions, 206 deletions
diff --git a/tools/json_schema_compiler/cc_generator.py b/tools/json_schema_compiler/cc_generator.py
index 99e0eb3..d21e160 100644
--- a/tools/json_schema_compiler/cc_generator.py
+++ b/tools/json_schema_compiler/cc_generator.py
@@ -80,11 +80,21 @@ class CCGenerator(object):
cpp_util.Classname(function.name), function))
.Append()
)
+ if self._namespace.events:
+ (c.Append('//')
+ .Append('// Events')
+ .Append('//')
+ .Append()
+ )
+ for event in self._namespace.events.values():
+ (c.Concat(self._GenerateCreateCallbackArguments(
+ cpp_util.Classname(event.name), event))
+ .Append()
+ )
(c.Concat(self._cpp_type_generator.GetNamespaceEnd())
.Concat(self._cpp_type_generator.GetRootNamespaceEnd())
.Append()
)
- # TODO(calamity): Events
return c
def _GenerateType(self, cpp_namespace, type_):
@@ -274,9 +284,10 @@ class CCGenerator(object):
.Append()
)
- # Result::Create function
+ # Results::Create function
if function.callback:
- c.Concat(self._GenerateFunctionResultCreate(cpp_namespace, function))
+ c.Concat(self._GenerateCreateCallbackArguments(
+ "%s::Results" % cpp_namespace, function.callback))
c.Substitute({'cpp_namespace': cpp_namespace})
@@ -509,7 +520,7 @@ class CCGenerator(object):
elif prop.type_ == PropertyType.CHOICES:
type_var = '%(dst)s->%(name)s_type'
c.Sblock('switch (%(value_var)s->GetType()) {')
- for choice in self._cpp_type_generator.GetExpandedChoicesInParams([prop]):
+ for choice in self._cpp_type_generator.ExpandParams([prop]):
(c.Sblock('case %s: {' % cpp_util.GetValueType(
self._cpp_type_generator.GetReferencedProperty(choice).type_))
.Concat(self._GeneratePopulatePropertyFromValue(
@@ -603,7 +614,7 @@ class CCGenerator(object):
def _GeneratePropertyFunctions(self, param_namespace, params):
"""Generate the functions for structures generated by a property such as
- CreateEnumValue for ENUMs and Populate/ToValue for Params/Result objects.
+ CreateEnumValue for ENUMs and Populate/ToValue for Params/Results objects.
"""
c = Code()
for param in params:
@@ -623,47 +634,45 @@ class CCGenerator(object):
c.Append()
return c
- def _GenerateFunctionResultCreate(self, cpp_namespace, function):
- """Generate function to create a Result given the return value.
+ def _GenerateCreateCallbackArguments(self, function_scope, callback):
+ """Generate all functions to create Value parameters for a callback.
- E.g for function "Bar", generate Bar::Result::Create
+ E.g for function "Bar", generate Bar::Results::Create
+ E.g for event "Baz", generate Baz::Create
+
+ function_scope: the function scope path, e.g. Foo::Bar for the function
+ Foo::Bar::Baz().
+ callback: the Function object we are creating callback arguments for.
"""
c = Code()
- params = function.callback.params
-
- if not params:
- (c.Append('base::Value* %s::Result::Create() {' % cpp_namespace)
- .Append(' return base::Value::CreateNullValue();')
- .Append('}')
+ params = callback.params
+ expanded_params = self._cpp_type_generator.ExpandParams(params)
+ c.Concat(self._GeneratePropertyFunctions(function_scope, expanded_params))
+
+ param_lists = self._cpp_type_generator.GetAllPossibleParameterLists(params)
+ for param_list in param_lists:
+ (c.Sblock('scoped_ptr<base::ListValue> %(function_scope)s::'
+ 'Create(%(declaration_list)s) {')
+ .Append('scoped_ptr<base::ListValue> create_results('
+ 'new base::ListValue());')
)
- else:
- expanded_params = self._cpp_type_generator.GetExpandedChoicesInParams(
- params)
- c.Concat(self._GeneratePropertyFunctions(
- cpp_namespace + '::Result', expanded_params))
-
- # If there is a single parameter, this is straightforward. However, if
- # the callback parameter is of 'choices', this generates a Create method
- # for each choice. This works because only 1 choice can be returned at a
- # time.
- for param in expanded_params:
- if param.type_ == PropertyType.ANY:
- # Generation of base::Value* Create(base::Value*) is redundant.
- continue
+ declaration_list = []
+ for param in param_list:
# We treat this argument as 'required' to avoid wrapping it in a
# scoped_ptr if it's optional.
param_copy = param.Copy()
param_copy.optional = False
- c.Sblock('base::Value* %(cpp_namespace)s::Result::Create('
- 'const %(arg)s) {')
- c.Append('return %s;' %
- self._CreateValueFromProperty(param_copy, param_copy.unix_name))
- c.Eblock('}')
- c.Substitute({
- 'cpp_namespace': cpp_namespace,
- 'arg': cpp_util.GetParameterDeclaration(
- param_copy, self._cpp_type_generator.GetType(param_copy))
- })
+ c.Append('create_results->Append(%s);' %
+ self._CreateValueFromProperty(param_copy, param_copy.unix_name))
+ declaration_list.append("const %s" % cpp_util.GetParameterDeclaration(
+ param_copy, self._cpp_type_generator.GetType(param_copy)))
+
+ c.Append('return create_results.Pass();')
+ c.Eblock('}')
+ c.Substitute({
+ 'function_scope': function_scope,
+ 'declaration_list': ', '.join(declaration_list)
+ })
return c
diff --git a/tools/json_schema_compiler/cpp_type_generator.py b/tools/json_schema_compiler/cpp_type_generator.py
index 28967b0..5b54bae 100644
--- a/tools/json_schema_compiler/cpp_type_generator.py
+++ b/tools/json_schema_compiler/cpp_type_generator.py
@@ -35,22 +35,31 @@ class CppTypeGenerator(object):
self._type_namespaces[type_] = namespace
self._cpp_namespaces[namespace] = cpp_namespace
- def GetExpandedChoicesInParams(self, params):
+ def ExpandParams(self, params):
"""Returns the given parameters with PropertyType.CHOICES parameters
- expanded so that each choice is a separate parameter and sets a unix_name
- for each choice.
+ expanded so that each choice is a separate parameter.
"""
expanded = []
for param in params:
if param.type_ == PropertyType.CHOICES:
for choice in param.choices.values():
- choice.unix_name = (
- param.unix_name + '_' + choice.type_.name.lower())
expanded.append(choice)
else:
expanded.append(param)
return expanded
+ def GetAllPossibleParameterLists(self, params):
+ """Returns all possible parameter lists for the given set of parameters.
+ Every combination of arguments passed to any of the PropertyType.CHOICES
+ parameters will have a corresponding parameter list returned here.
+ """
+ if not params:
+ return [[]]
+ partial_parameter_lists = self.GetAllPossibleParameterLists(params[1:])
+ return [[param] + partial_list
+ for param in self.ExpandParams(params[:1])
+ for partial_list in partial_parameter_lists]
+
def GetCppNamespaceName(self, namespace):
"""Gets the mapped C++ namespace name for the given namespace relative to
the root namespace.
diff --git a/tools/json_schema_compiler/cpp_type_generator_test.py b/tools/json_schema_compiler/cpp_type_generator_test.py
index 7c74fad..a9408fa 100755
--- a/tools/json_schema_compiler/cpp_type_generator_test.py
+++ b/tools/json_schema_compiler/cpp_type_generator_test.py
@@ -11,6 +11,10 @@ import unittest
class CppTypeGeneratorTest(unittest.TestCase):
def setUp(self):
self.model = model.Model()
+ self.forbidden_json = CachedLoad('test/forbidden.json')
+ self.model.AddNamespace(self.forbidden_json[0],
+ 'path/to/forbidden.json')
+ self.forbidden = self.model.namespaces.get('forbidden')
self.permissions_json = CachedLoad('test/permissions.json')
self.model.AddNamespace(self.permissions_json[0],
'path/to/permissions.json')
@@ -214,15 +218,33 @@ class CppTypeGeneratorTest(unittest.TestCase):
'} // extensions',
manager.GetRootNamespaceEnd().Render())
- def testExpandChoicesInParams(self):
+ def testExpandParams(self):
manager = CppTypeGenerator('extensions', self.tabs,
self.tabs.unix_name)
props = self.tabs.functions['move'].params
self.assertEquals(2, len(props))
- self.assertEquals(3, len(manager.GetExpandedChoicesInParams(props)))
self.assertEquals(['move_properties', 'tab_ids_array', 'tab_ids_integer'],
- sorted([x.unix_name for x in manager.GetExpandedChoicesInParams(props)])
+ sorted([x.unix_name for x in manager.ExpandParams(props)])
)
+ def testGetAllPossibleParameterLists(self):
+ manager = CppTypeGenerator('extensions', self.tabs,
+ self.tabs.unix_name)
+ props = self.forbidden.functions['forbiddenParameters'].params
+ self.assertEquals(4, len(props))
+ param_lists = manager.GetAllPossibleParameterLists(props)
+ expected_lists = [
+ ['first_choice_array', 'first_string',
+ 'second_choice_array', 'second_string'],
+ ['first_choice_array', 'first_string',
+ 'second_choice_integer', 'second_string'],
+ ['first_choice_integer', 'first_string',
+ 'second_choice_array', 'second_string'],
+ ['first_choice_integer', 'first_string',
+ 'second_choice_integer', 'second_string']]
+ result_lists = sorted([[param.unix_name for param in param_list]
+ for param_list in param_lists])
+ self.assertEquals(expected_lists, result_lists)
+
if __name__ == '__main__':
unittest.main()
diff --git a/tools/json_schema_compiler/h_generator.py b/tools/json_schema_compiler/h_generator.py
index 30a357d..5f59ffb 100644
--- a/tools/json_schema_compiler/h_generator.py
+++ b/tools/json_schema_compiler/h_generator.py
@@ -89,6 +89,16 @@ class HGenerator(object):
(c.Concat(self._GenerateFunction(function))
.Append()
)
+ if self._namespace.events:
+ (c.Append('//')
+ .Append('// Events')
+ .Append('//')
+ .Append()
+ )
+ for event in self._namespace.events.values():
+ (c.Concat(self._GenerateEvent(event))
+ .Append()
+ )
(c.Concat(self._cpp_type_generator.GetNamespaceEnd())
.Concat(self._cpp_type_generator.GetRootNamespaceEnd())
.Append()
@@ -143,7 +153,8 @@ class HGenerator(object):
enum_name = self._cpp_type_generator.GetChoicesEnumType(prop)
c.Append('%s %s_type;' % (enum_name, prop.unix_name))
c.Append()
- for prop in self._cpp_type_generator.GetExpandedChoicesInParams(props):
+
+ for prop in self._cpp_type_generator.ExpandParams(props):
if prop.description:
c.Comment(prop.description)
c.Append('%s %s;' % (
@@ -209,8 +220,18 @@ class HGenerator(object):
c.Substitute({'classname': classname})
return c
+ def _GenerateEvent(self, event):
+ """Generates the namespaces for an event.
+ """
+ c = Code()
+ (c.Sblock('namespace %s {' % cpp_util.Classname(event.name))
+ .Concat(self._GenerateCreateCallbackArguments(event))
+ .Eblock('};')
+ )
+ return c
+
def _GenerateFunction(self, function):
- """Generates the structs for a function.
+ """Generates the namespaces and structs for a function.
"""
c = Code()
(c.Sblock('namespace %s {' % cpp_util.Classname(function.name))
@@ -218,7 +239,7 @@ class HGenerator(object):
.Append()
)
if function.callback:
- (c.Concat(self._GenerateFunctionResult(function))
+ (c.Concat(self._GenerateFunctionResults(function.callback))
.Append()
)
c.Eblock('};')
@@ -226,7 +247,7 @@ class HGenerator(object):
return c
def _GenerateFunctionParams(self, function):
- """Generates the struct for passing parameters into a function.
+ """Generates the struct for passing parameters from JSON to a function.
"""
c = Code()
@@ -272,36 +293,41 @@ class HGenerator(object):
enum_name,
prop,
prop.enum_values))
- c.Append('static scoped_ptr<base::Value> CreateEnumValue(%s %s);' %
- (enum_name, prop.unix_name))
+ create_enum_value = ('scoped_ptr<base::Value> CreateEnumValue(%s %s);' %
+ (enum_name, prop.unix_name))
+ # If the property is from the UI then we're in a struct so this function
+ # should be static. If it's from the client, then we're just in a
+ # namespace so we can't have the static keyword.
+ if prop.from_json:
+ create_enum_value = 'static ' + create_enum_value
+ c.Append(create_enum_value)
return c
- def _GenerateFunctionResult(self, function):
- """Generates functions for passing a function's result back.
+ def _GenerateCreateCallbackArguments(self, function):
+ """Generates functions for passing paramaters to a callback.
"""
c = Code()
+ params = function.params
+ c.Concat(self._GeneratePropertyStructures(params))
- c.Sblock('namespace Result {')
- params = function.callback.params
- if not params:
- c.Append('base::Value* Create();')
- else:
- c.Concat(self._GeneratePropertyStructures(params))
-
- # If there is a single parameter, this is straightforward. However, if
- # the callback parameter is of 'choices', this generates a Create method
- # for each choice. This works because only 1 choice can be returned at a
- # time.
- for param in self._cpp_type_generator.GetExpandedChoicesInParams(params):
+ param_lists = self._cpp_type_generator.GetAllPossibleParameterLists(params)
+ for param_list in param_lists:
+ declaration_list = []
+ for param in param_list:
if param.description:
c.Comment(param.description)
- if param.type_ == PropertyType.ANY:
- c.Comment("base::Value* Result::Create(base::Value*) not generated "
- "because it's redundant.")
- continue
- c.Append('base::Value* Create(const %s);' %
- cpp_util.GetParameterDeclaration(
- param, self._cpp_type_generator.GetType(param)))
- c.Eblock('};')
+ declaration_list.append('const %s' % cpp_util.GetParameterDeclaration(
+ param, self._cpp_type_generator.GetType(param)))
+ c.Append('scoped_ptr<base::ListValue> Create(%s);' %
+ ', '.join(declaration_list))
+ return c
+ def _GenerateFunctionResults(self, callback):
+ """Generates namespace for passing a function's result back.
+ """
+ c = Code()
+ (c.Sblock('namespace Results {')
+ .Concat(self._GenerateCreateCallbackArguments(callback))
+ .Eblock('};')
+ )
return c
diff --git a/tools/json_schema_compiler/model.py b/tools/json_schema_compiler/model.py
index bb3fe0e..828481f 100644
--- a/tools/json_schema_compiler/model.py
+++ b/tools/json_schema_compiler/model.py
@@ -42,6 +42,7 @@ class Namespace(object):
- |source_file_filename| the filename component of |source_file|
- |types| a map of type names to their model.Type
- |functions| a map of function names to their model.Function
+ - |events| a map of event names to their model.Function
- |properties| a map of property names to their model.Property
"""
def __init__(self, json, source_file):
@@ -52,6 +53,7 @@ class Namespace(object):
self.parent = None
_AddTypes(self, json)
_AddFunctions(self, json)
+ _AddEvents(self, json)
_AddProperties(self, json)
class Type(object):
@@ -102,29 +104,6 @@ class Type(object):
additional_properties,
is_additional_properties=True)
-class Callback(object):
- """A callback parameter to a Function.
-
- Properties:
- - |params| the parameters to this callback.
- """
- def __init__(self, parent, json):
- params = json['parameters']
- self.parent = parent
- self.description = json.get('description')
- self.optional = json.get('optional', False)
- self.params = []
- if len(params) == 0:
- return
- elif len(params) == 1:
- param = params[0]
- self.params.append(Property(self, param['name'], param,
- from_client=True))
- else:
- raise ParseException(
- self,
- "Callbacks can have at most a single parameter")
-
class Function(object):
"""A Function defined in the API.
@@ -136,21 +115,21 @@ class Function(object):
- |callback| the callback parameter to the function. There should be exactly
one
"""
- def __init__(self, parent, json):
+ def __init__(self, parent, json, from_json=False, from_client=False):
self.name = json['name']
self.params = []
self.description = json.get('description')
self.callback = None
self.parent = parent
self.nocompile = json.get('nocompile')
- for param in json['parameters']:
+ for param in json.get('parameters', []):
if param.get('type') == 'function':
if self.callback:
raise ParseException(self, self.name + " has more than one callback")
- self.callback = Callback(self, param)
+ self.callback = Function(self, param, from_client=True)
else:
self.params.append(Property(self, param['name'], param,
- from_json=True))
+ from_json=from_json, from_client=from_client))
class Property(object):
"""A property of a type OR a parameter to a function.
@@ -167,18 +146,15 @@ class Property(object):
- |item_type| a model.Property representing the type of each element in an
ARRAY
- |properties| the properties of an OBJECT parameter
+ - |from_client| indicates that instances of the Type can originate from the
+ users of generated code, such as top-level types and function results
+ - |from_json| indicates that instances of the Type can originate from the
+ JSON (as described by the schema), such as top-level types and function
+ parameters
"""
def __init__(self, parent, name, json, is_additional_properties=False,
from_json=False, from_client=False):
- """
- Parameters:
- - |from_json| indicates that instances of the Type can originate from the
- JSON (as described by the schema), such as top-level types and function
- parameters
- - |from_client| indicates that instances of the Type can originate from the
- users of generated code, such as top-level types and function results
- """
self.name = name
self._unix_name = UnixName(self.name)
self._unix_name_used = False
@@ -187,6 +163,8 @@ class Property(object):
self.has_value = False
self.description = json.get('description')
self.parent = parent
+ self.from_json = from_json
+ self.from_client = from_client
_AddProperties(self, json)
if is_additional_properties:
self.type_ = PropertyType.ADDITIONAL_PROPERTIES
@@ -220,8 +198,6 @@ class Property(object):
elif json_type == 'object':
self.type_ = PropertyType.OBJECT
# These members are read when this OBJECT Property is used as a Type
- self.from_json = from_json
- self.from_client = from_client
type_ = Type(self, self.name, json)
# self.properties will already have some value from |_AddProperties|.
self.properties.update(type_.properties)
@@ -231,7 +207,7 @@ class Property(object):
else:
raise ParseException(self, 'type ' + json_type + ' not recognized')
elif 'choices' in json:
- if not json['choices']:
+ if not json['choices'] or len(json['choices']) == 0:
raise ParseException(self, 'Choices has no choices')
self.choices = {}
self.type_ = PropertyType.CHOICES
@@ -239,9 +215,7 @@ class Property(object):
choice = Property(self, self.name, choice_json,
from_json=from_json,
from_client=from_client)
- # A choice gets its unix_name set in
- # cpp_type_generator.GetExpandedChoicesInParams
- choice._unix_name = None
+ choice.unix_name = UnixName(self.name + choice.type_.name)
# The existence of any single choice is optional
choice.optional = True
self.choices[choice.type_] = choice
@@ -344,13 +318,22 @@ def _AddTypes(model, json):
model.types[type_.name] = type_
def _AddFunctions(model, json):
- """Adds Function objects to |model| contained in the 'types' field of |json|.
+ """Adds Function objects to |model| contained in the 'functions' field of
+ |json|.
"""
model.functions = {}
for function_json in json.get('functions', []):
- function = Function(model, function_json)
+ function = Function(model, function_json, from_json=True)
model.functions[function.name] = function
+def _AddEvents(model, json):
+ """Adds Function objects to |model| contained in the 'events' field of |json|.
+ """
+ model.events = {}
+ for event_json in json.get('events', []):
+ event = Function(model, event_json, from_client=True)
+ model.events[event.name] = event
+
def _AddProperties(model, json, from_json=False, from_client=False):
"""Adds model.Property objects to |model| contained in the 'properties' field
of |json|.
diff --git a/tools/json_schema_compiler/model_test.py b/tools/json_schema_compiler/model_test.py
index 1eb855c..880ae8d 100755
--- a/tools/json_schema_compiler/model_test.py
+++ b/tools/json_schema_compiler/model_test.py
@@ -78,8 +78,6 @@ class ModelTest(unittest.TestCase):
def testPropertyUnixName(self):
param = self.tabs.functions['move'].params[0]
self.assertEquals('tab_ids', param.unix_name)
- self.assertRaises(AttributeError,
- param.choices[model.PropertyType.INTEGER].GetUnixName)
param.choices[model.PropertyType.INTEGER].unix_name = 'asdf'
param.choices[model.PropertyType.INTEGER].unix_name = 'tab_ids_integer'
self.assertEquals('tab_ids_integer',
diff --git a/tools/json_schema_compiler/schema_bundle_generator.py b/tools/json_schema_compiler/schema_bundle_generator.py
index 08cc4a8..759bbb8 100644
--- a/tools/json_schema_compiler/schema_bundle_generator.py
+++ b/tools/json_schema_compiler/schema_bundle_generator.py
@@ -77,15 +77,14 @@ class SchemaBundleGenerator(object):
c.Append("public:")
c.Sblock("static void RegisterAll(ExtensionFunctionRegistry* registry) {")
for namespace in self._model.namespaces.values():
+ namespace_name = self.CapitalizeFirstLetter(namespace.name.replace(
+ "experimental.", ""))
for function in namespace.functions.values():
if function.nocompile:
continue
- namespace_name = self.CapitalizeFirstLetter(namespace.name.replace(
- "experimental.", ""))
function_name = namespace_name + self.CapitalizeFirstLetter(
function.name)
- c.Append("registry->RegisterFunction<%sFunction>();" % (
- function_name))
+ c.Append("registry->RegisterFunction<%sFunction>();" % function_name)
c.Eblock("}")
c.Eblock("};")
c.Append()
diff --git a/tools/json_schema_compiler/test/additional_properties_unittest.cc b/tools/json_schema_compiler/test/additional_properties_unittest.cc
index ef0ab29..4c3d720 100644
--- a/tools/json_schema_compiler/test/additional_properties_unittest.cc
+++ b/tools/json_schema_compiler/test/additional_properties_unittest.cc
@@ -48,17 +48,15 @@ TEST(JsonSchemaCompilerAdditionalPropertiesTest,
TEST(JsonSchemaCompilerAdditionalPropertiesTest,
ReturnAdditionalPropertiesResultCreate) {
- scoped_ptr<DictionaryValue> result_object_value(new DictionaryValue());
- result_object_value->SetString("key", "value");
- scoped_ptr<ReturnAdditionalProperties::Result::ResultObject> result_object(
- new ReturnAdditionalProperties::Result::ResultObject());
- result_object->integer = 5;
- result_object->additional_properties.MergeDictionary(
- result_object_value.get());
- scoped_ptr<Value> result(
- ReturnAdditionalProperties::Result::Create(*result_object));
+ DictionaryValue additional;
+ additional.SetString("key", "value");
+ ReturnAdditionalProperties::Results::ResultObject result_object;
+ result_object.integer = 5;
+ result_object.additional_properties.MergeDictionary(&additional);
+ scoped_ptr<ListValue> results =
+ ReturnAdditionalProperties::Results::Create(result_object);
DictionaryValue* result_dict = NULL;
- EXPECT_TRUE(result->GetAsDictionary(&result_dict));
+ EXPECT_TRUE(results->GetDictionary(0, &result_dict));
Value* int_temp_value_out = NULL;
int int_temp = 0;
@@ -67,5 +65,5 @@ TEST(JsonSchemaCompilerAdditionalPropertiesTest,
EXPECT_TRUE(int_temp_value->GetAsInteger(&int_temp));
EXPECT_EQ(5, int_temp);
- EXPECT_TRUE(result_dict->Equals(result_object_value.get()));
+ EXPECT_TRUE(result_dict->Equals(&additional));
}
diff --git a/tools/json_schema_compiler/test/any.json b/tools/json_schema_compiler/test/any.json
index 02243bb..55da4a6 100644
--- a/tools/json_schema_compiler/test/any.json
+++ b/tools/json_schema_compiler/test/any.json
@@ -49,6 +49,19 @@
}
]
}
+ ],
+ "events": [
+ {
+ "name": "onAnyFired",
+ "type": "function",
+ "description": "Fired when anything is ready.",
+ "parameters": [
+ {
+ "name": "something",
+ "type": "any"
+ }
+ ]
+ }
]
}
]
diff --git a/tools/json_schema_compiler/test/arrays_unittest.cc b/tools/json_schema_compiler/test/arrays_unittest.cc
index 0709677..c6d1e06 100644
--- a/tools/json_schema_compiler/test/arrays_unittest.cc
+++ b/tools/json_schema_compiler/test/arrays_unittest.cc
@@ -194,15 +194,14 @@ TEST(JsonSchemaCompilerArrayTest, ReturnIntegerArrayResultCreate) {
std::vector<int> integers;
integers.push_back(1);
integers.push_back(2);
- scoped_ptr<Value> result(ReturnIntegerArray::Result::Create(integers));
- ListValue* list = NULL;
- EXPECT_TRUE(result->GetAsList(&list));
- int temp;
- ASSERT_EQ(2u, list->GetSize());
- EXPECT_TRUE(list->GetInteger(0, &temp));
- EXPECT_EQ(1, temp);
- EXPECT_TRUE(list->GetInteger(1, &temp));
- EXPECT_EQ(2, temp);
+ scoped_ptr<ListValue> results = ReturnIntegerArray::Results::Create(integers);
+
+ ListValue expected;
+ ListValue* expected_argument = new ListValue();
+ expected_argument->Append(Value::CreateIntegerValue(1));
+ expected_argument->Append(Value::CreateIntegerValue(2));
+ expected.Append(expected_argument);
+ EXPECT_TRUE(results->Equals(&expected));
}
TEST(JsonSchemaCompilerArrayTest, ReturnRefArrayResultCreate) {
@@ -211,16 +210,16 @@ TEST(JsonSchemaCompilerArrayTest, ReturnRefArrayResultCreate) {
items.push_back(linked_ptr<Item>(new Item()));
items[0]->val = 1;
items[1]->val = 2;
- scoped_ptr<Value> result(ReturnRefArray::Result::Create(items));
- ListValue* list = NULL;
- EXPECT_TRUE(result->GetAsList(&list));
- ASSERT_EQ(2u, list->GetSize());
- DictionaryValue* item_value = NULL;
- int temp;
- EXPECT_TRUE(list->GetDictionary(0, &item_value));
- EXPECT_TRUE(item_value->GetInteger("val", &temp));
- EXPECT_EQ(1, temp);
- EXPECT_TRUE(list->GetDictionary(1, &item_value));
- EXPECT_TRUE(item_value->GetInteger("val", &temp));
- EXPECT_EQ(2, temp);
+ scoped_ptr<ListValue> results = ReturnRefArray::Results::Create(items);
+
+ ListValue expected;
+ ListValue* expected_argument = new ListValue();
+ DictionaryValue* first = new DictionaryValue();
+ first->SetInteger("val", 1);
+ expected_argument->Append(first);
+ DictionaryValue* second = new DictionaryValue();
+ second->SetInteger("val", 2);
+ expected_argument->Append(second);
+ expected.Append(expected_argument);
+ EXPECT_TRUE(results->Equals(&expected));
}
diff --git a/tools/json_schema_compiler/test/callbacks.json b/tools/json_schema_compiler/test/callbacks.json
new file mode 100644
index 0000000..06455b9
--- /dev/null
+++ b/tools/json_schema_compiler/test/callbacks.json
@@ -0,0 +1,71 @@
+[
+ {
+ "namespace": "callbacks",
+ "types": [],
+ "functions": [
+ {
+ "name": "returnsNothing",
+ "type": "function",
+ "description": "Takes nothing. Returns nothing.",
+ "parameters": [
+ {
+ "name": "callback",
+ "type": "function",
+ "parameters": []
+ }
+ ]
+ },
+ {
+ "name": "returnsObject",
+ "description": "Returns an object.",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "callback",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "someObject",
+ "type": "object",
+ "properties": {
+ "state": {
+ "type": "string",
+ "enum": ["foo", "bar", "baz"]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "returnsMultiple",
+ "description": "Returns an object.",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "callback",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "someInteger",
+ "type": "integer"
+ },
+ {
+ "name": "someObject",
+ "type": "object",
+ "properties": {
+ "state": {
+ "type": "string",
+ "enum": ["foo", "bar", "baz"]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+]
+
diff --git a/tools/json_schema_compiler/test/callbacks_unittest.cc b/tools/json_schema_compiler/test/callbacks_unittest.cc
new file mode 100644
index 0000000..163a6c0
--- /dev/null
+++ b/tools/json_schema_compiler/test/callbacks_unittest.cc
@@ -0,0 +1,35 @@
+// Copyright (c) 2012 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 "tools/json_schema_compiler/test/callbacks.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+
+using namespace test::api::callbacks;
+
+TEST(JsonSchemaCompilerCallbacksTest, ReturnsObjectResultCreate) {
+ ReturnsObject::Results::SomeObject some_object;
+ some_object.state = ReturnsObject::Results::SomeObject::STATE_FOO;
+ scoped_ptr<ListValue> results = ReturnsObject::Results::Create(some_object);
+
+ DictionaryValue* expected_dict = new DictionaryValue();
+ expected_dict->SetString("state", "foo");
+ ListValue expected;
+ expected.Append(expected_dict);
+ EXPECT_TRUE(results->Equals(&expected));
+}
+
+TEST(JsonSchemaCompilerCallbacksTest, ReturnsMultipleResultCreate) {
+ ReturnsMultiple::Results::SomeObject some_object;
+ some_object.state = ReturnsMultiple::Results::SomeObject::STATE_FOO;
+ scoped_ptr<ListValue> results =
+ ReturnsMultiple::Results::Create(5, some_object);
+
+ DictionaryValue* expected_dict = new DictionaryValue();
+ expected_dict->SetString("state", "foo");
+ ListValue expected;
+ expected.Append(Value::CreateIntegerValue(5));
+ expected.Append(expected_dict);
+ EXPECT_TRUE(results->Equals(&expected));
+}
diff --git a/tools/json_schema_compiler/test/choices.json b/tools/json_schema_compiler/test/choices.json
index 6a13eb5..e53ac13 100644
--- a/tools/json_schema_compiler/test/choices.json
+++ b/tools/json_schema_compiler/test/choices.json
@@ -95,6 +95,35 @@
]
}
]
+ },
+ {
+ "name": "returnMultipleChoices",
+ "type": "function",
+ "description": "Gives back two values where each is an integer or a list of integers.",
+ "parameters": [
+ {
+ "name": "callback",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "firstResult",
+ "choices": [
+ {"type": "array", "items": {"type": "integer", "minimum": 0}},
+ {"type": "integer"}
+ ],
+ "description": "Some integers."
+ },
+ {
+ "name": "secondResult",
+ "choices": [
+ {"type": "array", "items": {"type": "integer", "minimum": 0}},
+ {"type": "integer"}
+ ],
+ "description": "Some integers."
+ }
+ ]
+ }
+ ]
}
]
}
diff --git a/tools/json_schema_compiler/test/choices_unittest.cc b/tools/json_schema_compiler/test/choices_unittest.cc
index dcdfd77..ce5a0ee 100644
--- a/tools/json_schema_compiler/test/choices_unittest.cc
+++ b/tools/json_schema_compiler/test/choices_unittest.cc
@@ -116,20 +116,20 @@ TEST(JsonSchemaCompilerChoicesTest, ReturnChoices) {
std::vector<int> integers;
integers.push_back(1);
integers.push_back(2);
- scoped_ptr<Value> array_result(ReturnChoices::Result::Create(integers));
- ListValue* list = NULL;
- EXPECT_TRUE(array_result->GetAsList(&list));
- EXPECT_EQ((size_t) 2, list->GetSize());
- int temp;
- EXPECT_TRUE(list->GetInteger(0, &temp));
- EXPECT_EQ(1, temp);
- EXPECT_TRUE(list->GetInteger(1, &temp));
- EXPECT_EQ(2, temp);
+ scoped_ptr<ListValue> array_results =
+ ReturnChoices::Results::Create(integers);
+
+ ListValue expected;
+ ListValue* expected_argument = new ListValue();
+ expected_argument->Append(Value::CreateIntegerValue(1));
+ expected_argument->Append(Value::CreateIntegerValue(2));
+ expected.Append(expected_argument);
+ EXPECT_TRUE(array_results->Equals(&expected));
}
{
- scoped_ptr<Value> single_result(ReturnChoices::Result::Create(5));
- int temp;
- EXPECT_TRUE(single_result->GetAsInteger(&temp));
- EXPECT_EQ(5, temp);
+ scoped_ptr<ListValue> integer_results = ReturnChoices::Results::Create(5);
+ ListValue expected;
+ expected.Append(Value::CreateIntegerValue(5));
+ EXPECT_TRUE(integer_results->Equals(&expected));
}
}
diff --git a/tools/json_schema_compiler/test/crossref_unittest.cc b/tools/json_schema_compiler/test/crossref_unittest.cc
index cf7189e..d2747fd 100644
--- a/tools/json_schema_compiler/test/crossref_unittest.cc
+++ b/tools/json_schema_compiler/test/crossref_unittest.cc
@@ -60,8 +60,11 @@ TEST(JsonSchemaCompilerCrossrefTest, GetTestType) {
new test::api::simple_api::TestType());
EXPECT_TRUE(
test::api::simple_api::TestType::Populate(*value, test_type.get()));
- scoped_ptr<Value> result(GetTestType::Result::Create(*test_type));
- EXPECT_TRUE(value->Equals(result.get()));
+
+ scoped_ptr<ListValue> results = GetTestType::Results::Create(*test_type);
+ DictionaryValue* result_dict = NULL;
+ results->GetDictionary(0, &result_dict);
+ EXPECT_TRUE(value->Equals(result_dict));
}
TEST(JsonSchemaCompilerCrossrefTest, TestTypeInObjectParamsCreate) {
diff --git a/tools/json_schema_compiler/test/enums.json b/tools/json_schema_compiler/test/enums.json
index 51e1fd41..ae6be004 100644
--- a/tools/json_schema_compiler/test/enums.json
+++ b/tools/json_schema_compiler/test/enums.json
@@ -43,6 +43,47 @@
]
},
{
+ "name": "returnsEnum",
+ "type": "function",
+ "description": "Returns an enum through the callback",
+ "parameters": [
+ {
+ "name": "callback",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "state",
+ "type": "string",
+ "enum": ["foo", "bar", "baz"]
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "returnsTwoEnums",
+ "type": "function",
+ "description": "Returns two enums through the callback",
+ "parameters": [
+ {
+ "name": "callback",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "firstState",
+ "type": "string",
+ "enum": ["foo", "bar", "baz"]
+ },
+ {
+ "name": "secondState",
+ "type": "string",
+ "enum": ["spam", "ham", "eggs"]
+ }
+ ]
+ }
+ ]
+ },
+ {
"name": "takesOptionalEnum",
"type": "function",
"description": "Takes an enum as its parameter.",
@@ -84,6 +125,37 @@
}
]
}
+ ],
+ "events": [
+ {
+ "name": "onEnumFired",
+ "type": "function",
+ "description": "Fired when an enum is ready.",
+ "parameters": [
+ {
+ "name": "someEnum",
+ "type": "string",
+ "enum": ["foo", "bar", "baz"]
+ }
+ ]
+ },
+ {
+ "name": "onTwoEnumsFired",
+ "type": "function",
+ "description": "Fired when two enums are ready.",
+ "parameters": [
+ {
+ "name": "firstEnum",
+ "type": "string",
+ "enum": ["foo", "bar", "baz"]
+ },
+ {
+ "name": "secondEnum",
+ "type": "string",
+ "enum": ["spam", "ham", "eggs"]
+ }
+ ]
+ }
]
}
]
diff --git a/tools/json_schema_compiler/test/enums_unittest.cc b/tools/json_schema_compiler/test/enums_unittest.cc
index 14eece2..6037874 100644
--- a/tools/json_schema_compiler/test/enums_unittest.cc
+++ b/tools/json_schema_compiler/test/enums_unittest.cc
@@ -25,6 +25,34 @@ TEST(JsonSchemaCompilerEnumsTest, EnumTypePopulate) {
}
}
+TEST(JsonSchemaCompilerEnumsTest, ReturnsEnumCreate) {
+ {
+ ReturnsEnum::Results::State state = ReturnsEnum::Results::STATE_FOO;
+ scoped_ptr<Value> result = ReturnsEnum::Results::CreateEnumValue(state);
+ scoped_ptr<Value> expected(Value::CreateStringValue("foo"));
+ EXPECT_TRUE(result->Equals(expected.get()));
+ }
+ {
+ ReturnsEnum::Results::State state = ReturnsEnum::Results::STATE_FOO;
+ scoped_ptr<ListValue> results = ReturnsEnum::Results::Create(state);
+ ListValue expected;
+ expected.Append(Value::CreateStringValue("foo"));
+ EXPECT_TRUE(results->Equals(&expected));
+ }
+}
+
+TEST(JsonSchemaCompilerEnumsTest, ReturnsTwoEnumsCreate) {
+ {
+ scoped_ptr<ListValue> results = ReturnsTwoEnums::Results::Create(
+ ReturnsTwoEnums::Results::FIRST_STATE_FOO,
+ ReturnsTwoEnums::Results::SECOND_STATE_HAM);
+ ListValue expected;
+ expected.Append(Value::CreateStringValue("foo"));
+ expected.Append(Value::CreateStringValue("ham"));
+ EXPECT_TRUE(results->Equals(&expected));
+ }
+}
+
TEST(JsonSchemaCompilerEnumsTest, OptionalEnumTypePopulate) {
{
scoped_ptr<OptionalEnumType> enum_type(new OptionalEnumType());
@@ -129,3 +157,31 @@ TEST(JsonSchemaCompilerEnumsTest, TakesMultipleOptionalEnumsParamsCreate) {
EXPECT_FALSE(params.get());
}
}
+
+TEST(JsonSchemaCompilerEnumsTest, OnEnumFiredCreate) {
+ {
+ OnEnumFired::SomeEnum some_enum = OnEnumFired::SOME_ENUM_FOO;
+ scoped_ptr<Value> result(OnEnumFired::CreateEnumValue(some_enum));
+ scoped_ptr<Value> expected(Value::CreateStringValue("foo"));
+ EXPECT_TRUE(result->Equals(expected.get()));
+ }
+ {
+ OnEnumFired::SomeEnum some_enum = OnEnumFired::SOME_ENUM_FOO;
+ scoped_ptr<ListValue> results(OnEnumFired::Create(some_enum));
+ ListValue expected;
+ expected.Append(Value::CreateStringValue("foo"));
+ EXPECT_TRUE(results->Equals(&expected));
+ }
+}
+
+TEST(JsonSchemaCompilerEnumsTest, OnTwoEnumsFiredCreate) {
+ {
+ scoped_ptr<Value> results(OnTwoEnumsFired::Create(
+ OnTwoEnumsFired::FIRST_ENUM_FOO,
+ OnTwoEnumsFired::SECOND_ENUM_HAM));
+ ListValue expected;
+ expected.Append(Value::CreateStringValue("foo"));
+ expected.Append(Value::CreateStringValue("ham"));
+ EXPECT_TRUE(results->Equals(&expected));
+ }
+}
diff --git a/tools/json_schema_compiler/test/forbidden.json b/tools/json_schema_compiler/test/forbidden.json
new file mode 100644
index 0000000..c7978aa
--- /dev/null
+++ b/tools/json_schema_compiler/test/forbidden.json
@@ -0,0 +1,39 @@
+[
+ {
+ "namespace": "forbidden",
+ "types": [],
+ "functions": [
+ {
+ "name": "forbiddenParameters",
+ "type": "function",
+ "description": "Don't do this at home. Accepts multiple choices and values",
+ "parameters": [
+ {
+ "name": "firstChoice",
+ "description": "a choice between int and array",
+ "choices": [
+ {"type": "integer", "minimum": 0},
+ {"type": "array", "items": {"type": "integer"}}
+ ]
+ },
+ {
+ "type": "string",
+ "name": "firstString"
+ },
+ {
+ "name": "secondChoice",
+ "description": "a choice between int and array",
+ "choices": [
+ {"type": "integer", "minimum": 0},
+ {"type": "array", "items": {"type": "integer"}}
+ ]
+ },
+ {
+ "type": "string",
+ "name": "secondString"
+ }
+ ]
+ }
+ ]
+ }
+]
diff --git a/tools/json_schema_compiler/test/functions_on_types_unittest.cc b/tools/json_schema_compiler/test/functions_on_types_unittest.cc
index 0694cb3..73a3cf2 100644
--- a/tools/json_schema_compiler/test/functions_on_types_unittest.cc
+++ b/tools/json_schema_compiler/test/functions_on_types_unittest.cc
@@ -48,12 +48,13 @@ TEST(JsonSchemaCompilerFunctionsOnTypesTest, StorageAreaGetParamsCreate) {
}
TEST(JsonSchemaCompilerFunctionsOnTypesTest, StorageAreaGetResultCreate) {
- scoped_ptr<StorageArea::Get::Result::Items> items(
- new StorageArea::Get::Result::Items());
- items->additional_properties.SetDouble("asdf", 0.1);
- items->additional_properties.SetString("sdfg", "zxcv");
- scoped_ptr<Value> result_value(StorageArea::Get::Result::Create(*items));
- EXPECT_TRUE(result_value->Equals(&items->additional_properties));
+ StorageArea::Get::Results::Items items;
+ items.additional_properties.SetDouble("asdf", 0.1);
+ items.additional_properties.SetString("sdfg", "zxcv");
+ scoped_ptr<ListValue> results = StorageArea::Get::Results::Create(items);
+ DictionaryValue* item_result = NULL;
+ results->GetDictionary(0, &item_result);
+ EXPECT_TRUE(item_result->Equals(&items.additional_properties));
}
TEST(JsonSchemaCompilerFunctionsOnTypesTest, ChromeSettingGetParamsCreate) {
diff --git a/tools/json_schema_compiler/test/idl_schemas_unittest.cc b/tools/json_schema_compiler/test/idl_schemas_unittest.cc
index 4969a9b..8afb59c 100644
--- a/tools/json_schema_compiler/test/idl_schemas_unittest.cc
+++ b/tools/json_schema_compiler/test/idl_schemas_unittest.cc
@@ -54,15 +54,20 @@ TEST(IdlCompiler, Basics) {
// Test functions that take a callback function as a parameter, with varying
// callback signatures.
- scoped_ptr<Value> f4_result(Function4::Result::Create());
- EXPECT_TRUE(f4_result->IsType(Value::TYPE_NULL));
-
- scoped_ptr<Value> f5_result(Function5::Result::Create(13));
- EXPECT_TRUE(f5_result->IsType(Value::TYPE_INTEGER));
-
- scoped_ptr<Value> f6_result(Function6::Result::Create(a));
+ scoped_ptr<ListValue> f4_results = Function4::Results::Create();
+ ListValue expected;
+ EXPECT_TRUE(f4_results->Equals(&expected));
+
+ scoped_ptr<ListValue> f5_results(Function5::Results::Create(13));
+ Value* f5_result_int = NULL;
+ ASSERT_TRUE(f5_results->Get(0, &f5_result_int));
+ EXPECT_TRUE(f5_result_int->IsType(Value::TYPE_INTEGER));
+
+ scoped_ptr<ListValue> f6_results(Function6::Results::Create(a));
+ Value* f6_result_dict = NULL;
+ ASSERT_TRUE(f6_results->Get(0, &f6_result_dict));
MyType1 c;
- EXPECT_TRUE(MyType1::Populate(*f6_result, &c));
+ EXPECT_TRUE(MyType1::Populate(*f6_result_dict, &c));
EXPECT_EQ(a.x, c.x);
EXPECT_EQ(a.y, c.y);
}
diff --git a/tools/json_schema_compiler/test/json_schema_compiler_tests.gyp b/tools/json_schema_compiler/test/json_schema_compiler_tests.gyp
index f48809c..f881b29 100644
--- a/tools/json_schema_compiler/test/json_schema_compiler_tests.gyp
+++ b/tools/json_schema_compiler/test/json_schema_compiler_tests.gyp
@@ -13,6 +13,7 @@
'any.json',
'additional_properties.json',
'arrays.json',
+ 'callbacks.json',
'choices.json',
'crossref.json',
'enums.json',
diff --git a/tools/json_schema_compiler/test/objects.json b/tools/json_schema_compiler/test/objects.json
index 8fb20b4..00a7f53 100644
--- a/tools/json_schema_compiler/test/objects.json
+++ b/tools/json_schema_compiler/test/objects.json
@@ -53,6 +53,85 @@
]
}
]
+ },
+ {
+ "name": "returnsTwoObjects",
+ "description": "Return two objects.",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "callback",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "firstInfo",
+ "type": "object",
+ "properties": {
+ "state": {
+ "type": "string",
+ "enum": ["foo", "bar", "baz"]
+ }
+ }
+ },
+ {
+ "name": "secondInfo",
+ "type": "object",
+ "properties": {
+ "state": {
+ "type": "string",
+ "enum": ["spam", "ham", "eggs"]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "events": [
+ {
+ "name": "onObjectFired",
+ "type": "function",
+ "description": "Fired when an object is ready.",
+ "parameters": [
+ {
+ "name": "someObject",
+ "type": "object",
+ "properties": {
+ "state": {
+ "type": "string",
+ "enum": ["foo", "bar", "baz"]
+ }
+ }
+ }
+ ]
+ },
+ {
+ "name": "onTwoObjectsFired",
+ "type": "function",
+ "description": "Fired when two objects are ready.",
+ "parameters": [
+ {
+ "name": "firstObject",
+ "type": "object",
+ "properties": {
+ "state": {
+ "type": "string",
+ "enum": ["foo", "bar", "baz"]
+ }
+ }
+ },
+ {
+ "name": "secondObject",
+ "type": "object",
+ "properties": {
+ "state": {
+ "type": "string",
+ "enum": ["spam", "ham", "eggs"]
+ }
+ }
+ }
+ ]
}
]
}
diff --git a/tools/json_schema_compiler/test/objects_unittest.cc b/tools/json_schema_compiler/test/objects_unittest.cc
index b0ed54f..95c3f0d 100644
--- a/tools/json_schema_compiler/test/objects_unittest.cc
+++ b/tools/json_schema_compiler/test/objects_unittest.cc
@@ -46,14 +46,25 @@ TEST(JsonSchemaCompilerObjectsTest, ObjectParamParamsCreate) {
}
TEST(JsonSchemaCompilerObjectsTest, ReturnsObjectResultCreate) {
- scoped_ptr<ReturnsObject::Result::Info> info(
- new ReturnsObject::Result::Info());
- info->state = ReturnsObject::Result::Info::STATE_FOO;
- scoped_ptr<Value> result_value(
- ReturnsObject::Result::Create(*info));
- DictionaryValue* result_dict = NULL;
- EXPECT_TRUE(result_value->GetAsDictionary(&result_dict));
- std::string state;
- EXPECT_TRUE(result_dict->GetString("state", &state));
- EXPECT_EQ("foo", state);
+ ReturnsObject::Results::Info info;
+ info.state = ReturnsObject::Results::Info::STATE_FOO;
+ scoped_ptr<ListValue> results = ReturnsObject::Results::Create(info);
+
+ DictionaryValue expected;
+ expected.SetString("state", "foo");
+ DictionaryValue* result = NULL;
+ ASSERT_TRUE(results->GetDictionary(0, &result));
+ ASSERT_TRUE(result->Equals(&expected));
+}
+
+TEST(JsonSchemaCompilerObjectsTest, OnObjectFiredCreate) {
+ OnObjectFired::SomeObject object;
+ object.state = OnObjectFired::SomeObject::STATE_BAR;
+ scoped_ptr<ListValue> results(OnObjectFired::Create(object));
+
+ DictionaryValue expected;
+ expected.SetString("state", "bar");
+ DictionaryValue* result = NULL;
+ ASSERT_TRUE(results->GetDictionary(0, &result));
+ ASSERT_TRUE(result->Equals(&expected));
}
diff --git a/tools/json_schema_compiler/test/simple_api.json b/tools/json_schema_compiler/test/simple_api.json
index 068432d..82d77b8 100644
--- a/tools/json_schema_compiler/test/simple_api.json
+++ b/tools/json_schema_compiler/test/simple_api.json
@@ -122,6 +122,41 @@
}
]
}
+ ],
+ "events": [
+ {
+ "name": "onIntegerFired",
+ "type": "function",
+ "description": "Fired when an integer is ready.",
+ "parameters": [
+ {
+ "name": "someInteger",
+ "type": "integer"
+ }
+ ]
+ },
+ {
+ "name": "onStringFired",
+ "type": "function",
+ "description": "Fired when a string is ready.",
+ "parameters": [
+ {
+ "name": "someString",
+ "type": "string"
+ }
+ ]
+ },
+ {
+ "name": "onTestTypeFired",
+ "type": "function",
+ "description": "Fired when a TestType is ready.",
+ "parameters": [
+ {
+ "name": "someTestType",
+ "$ref": "TestType"
+ }
+ ]
+ }
]
}
]
diff --git a/tools/json_schema_compiler/test/simple_api_unittest.cc b/tools/json_schema_compiler/test/simple_api_unittest.cc
index accf32e..bce1838 100644
--- a/tools/json_schema_compiler/test/simple_api_unittest.cc
+++ b/tools/json_schema_compiler/test/simple_api_unittest.cc
@@ -22,10 +22,10 @@ static scoped_ptr<DictionaryValue> CreateTestTypeDictionary() {
} // namespace
TEST(JsonSchemaCompilerSimpleTest, IncrementIntegerResultCreate) {
- scoped_ptr<Value> result(IncrementInteger::Result::Create(5));
- int temp = 0;
- EXPECT_TRUE(result->GetAsInteger(&temp));
- EXPECT_EQ(5, temp);
+ scoped_ptr<ListValue> results = IncrementInteger::Results::Create(5);
+ ListValue expected;
+ expected.Append(Value::CreateIntegerValue(5));
+ EXPECT_TRUE(results->Equals(&expected));
}
TEST(JsonSchemaCompilerSimpleTest, IncrementIntegerParamsCreate) {
@@ -108,9 +108,9 @@ TEST(JsonSchemaCompilerSimpleTest, OptionalBeforeRequired) {
}
TEST(JsonSchemaCompilerSimpleTest, NoParamsResultCreate) {
- scoped_ptr<Value> result(OptionalString::Result::Create());
- scoped_ptr<Value> expected(Value::CreateNullValue());
- EXPECT_TRUE(Value::Equals(result.get(), expected.get()));
+ scoped_ptr<ListValue> results = OptionalString::Results::Create();
+ ListValue expected;
+ EXPECT_TRUE(results->Equals(&expected));
}
TEST(JsonSchemaCompilerSimpleTest, TestTypePopulate) {
@@ -133,10 +133,48 @@ TEST(JsonSchemaCompilerSimpleTest, TestTypePopulate) {
}
TEST(JsonSchemaCompilerSimpleTest, GetTestType) {
- scoped_ptr<DictionaryValue> value = CreateTestTypeDictionary();
- scoped_ptr<TestType> test_type(new TestType());
- EXPECT_TRUE(TestType::Populate(*value, test_type.get()));
- scoped_ptr<Value> result(GetTestType::Result::Create(*test_type));
- EXPECT_TRUE(value->Equals(result.get()));
+ {
+ scoped_ptr<DictionaryValue> value = CreateTestTypeDictionary();
+ scoped_ptr<TestType> test_type(new TestType());
+ EXPECT_TRUE(TestType::Populate(*value, test_type.get()));
+ scoped_ptr<ListValue> results = GetTestType::Results::Create(*test_type);
+
+ DictionaryValue* result = NULL;
+ results->GetDictionary(0, &result);
+ EXPECT_TRUE(result->Equals(value.get()));
+ }
}
+TEST(JsonSchemaCompilerSimpleTest, OnIntegerFiredCreate) {
+ {
+ scoped_ptr<ListValue> results(OnIntegerFired::Create(5));
+ ListValue expected;
+ expected.Append(Value::CreateIntegerValue(5));
+ EXPECT_TRUE(results->Equals(&expected));
+ }
+}
+
+TEST(JsonSchemaCompilerSimpleTest, OnStringFiredCreate) {
+ {
+ scoped_ptr<ListValue> results(OnStringFired::Create("yo dawg"));
+ ListValue expected;
+ expected.Append(Value::CreateStringValue("yo dawg"));
+ EXPECT_TRUE(results->Equals(&expected));
+ }
+}
+
+TEST(JsonSchemaCompilerSimpleTest, OnTestTypeFiredCreate) {
+ {
+ TestType some_test_type;
+ scoped_ptr<DictionaryValue> expected = CreateTestTypeDictionary();
+ ASSERT_TRUE(expected->GetDouble("number", &some_test_type.number));
+ ASSERT_TRUE(expected->GetString("string", &some_test_type.string));
+ ASSERT_TRUE(expected->GetInteger("integer", &some_test_type.integer));
+ ASSERT_TRUE(expected->GetBoolean("boolean", &some_test_type.boolean));
+
+ scoped_ptr<ListValue> results(OnTestTypeFired::Create(some_test_type));
+ DictionaryValue* result = NULL;
+ results->GetDictionary(0, &result);
+ EXPECT_TRUE(result->Equals(expected.get()));
+ }
+}