summaryrefslogtreecommitdiffstats
path: root/tools/json_schema_compiler/js_externs_generator_test.py
blob: 6adc20171efcb75b18160694406d75433803c0f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
#!/usr/bin/env python
# Copyright 2015 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.

import idl_schema
import json_parse
from js_externs_generator import JsExternsGenerator
from datetime import datetime
import model
import sys
import unittest

# The contents of a fake idl file.
fake_idl = """
// Copyright 2014 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.

// A totally fake API.
namespace fakeApi {
  enum Greek {
    ALPHA,
    BETA,
    GAMMA,
    DELTA
  };

  dictionary Bar {
    long num;
  };

  dictionary Baz {
    DOMString str;
    long num;
    boolean b;
    Greek letter;
    Greek? optionalLetter;
    long[] arr;
    Bar[]? optionalObjArr;
    Greek[] enumArr;
    any[] anythingGoes;
    Bar obj;
    long? maybe;
    (DOMString or Greek or long[]) choice;
    object plainObj;
  };

  callback VoidCallback = void();

  callback BazGreekCallback = void(Baz baz, Greek greek);

  interface Functions {
    // Does something exciting! And what's more, this is a multiline function
    // comment! It goes onto multiple lines!
    // |baz| : The baz to use.
    static void doSomething(Baz baz, VoidCallback callback);

    // |callback| : The callback which will most assuredly in all cases be
    // called; that is, of course, iff such a callback was provided and is
    // not at all null.
    static void bazGreek(optional BazGreekCallback callback);

    [deprecated="Use a new method."] static DOMString returnString();
  };

  interface Events {
    // Fired when we realize it's a trap!
    static void onTrapDetected(Baz baz);
  };
};
"""

# The output we expect from our fake idl file.
expected_output = ("""// Copyright %s 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.

// This file was generated by:
//   %s.
// NOTE: The format of types has changed. 'FooType' is now
//   'chrome.fakeApi.FooType'.
// Please run the closure compiler before committing changes.
// See https://code.google.com/p/chromium/wiki/ClosureCompilation.

/** @fileoverview Externs generated from namespace: fakeApi */

/**
 * @const
 */
chrome.fakeApi = {};

/**
 * @enum {string}
 * @see https://developer.chrome.com/extensions/fakeApi#type-Greek
 */
chrome.fakeApi.Greek = {
  ALPHA: 'ALPHA',
  BETA: 'BETA',
  GAMMA: 'GAMMA',
  DELTA: 'DELTA',
};

/**
 * @typedef {{
 *   num: number
 * }}
 * @see https://developer.chrome.com/extensions/fakeApi#type-Bar
 */
chrome.fakeApi.Bar;

/**
 * @typedef {{
 *   str: string,
 *   num: number,
 *   b: boolean,
 *   letter: !chrome.fakeApi.Greek,
 *   optionalLetter: (!chrome.fakeApi.Greek|undefined),
 *   arr: !Array<number>,
 *   optionalObjArr: (!Array<!chrome.fakeApi.Bar>|undefined),
 *   enumArr: !Array<!chrome.fakeApi.Greek>,
 *   anythingGoes: !Array<*>,
 *   obj: !chrome.fakeApi.Bar,
 *   maybe: (number|undefined),
 *   choice: (string|!chrome.fakeApi.Greek|!Array<number>),
 *   plainObj: Object
 * }}
 * @see https://developer.chrome.com/extensions/fakeApi#type-Baz
 */
chrome.fakeApi.Baz;

/**
 * Does something exciting! And what's more, this is a multiline function
 * comment! It goes onto multiple lines!
 * @param {!chrome.fakeApi.Baz} baz The baz to use.
 * @param {function():void} callback
 * @see https://developer.chrome.com/extensions/fakeApi#method-doSomething
 */
chrome.fakeApi.doSomething = function(baz, callback) {};

/**
 * @param {function(!chrome.fakeApi.Baz, !chrome.fakeApi.Greek):void=} callback
 *     The callback which will most assuredly in all cases be called; that is,
 *     of course, iff such a callback was provided and is not at all null.
 * @see https://developer.chrome.com/extensions/fakeApi#method-bazGreek
 */
chrome.fakeApi.bazGreek = function(callback) {};

/**
 * @return {string}
 * @deprecated Use a new method.
 * @see https://developer.chrome.com/extensions/fakeApi#method-returnString
 */
chrome.fakeApi.returnString = function() {};

/**
 * Fired when we realize it's a trap!
 * @type {!ChromeEvent}
 * @see https://developer.chrome.com/extensions/fakeApi#event-onTrapDetected
 */
chrome.fakeApi.onTrapDetected;""" % (datetime.now().year, sys.argv[0]))


fake_json = """// Copyright 2014 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.

[
  {
    "namespace": "fakeJson",
    "description": "Fake JSON API Stuff",
    "types": [ {
      "id": "CrazyEnum",
      "type": "string",
      "enum": ["camelCaseEnum", "Non-Characters", "5NumFirst", \
"3Just-plainOld_MEAN"]
    } ],
    "functions": [ {
      "name": "funcWithInlineObj",
      "type": "function",
      "parameters": [
        {
          "type": "object",
          "name": "inlineObj",
          "description": "Evil inline object! With a super duper duper long\
 string description that causes problems!",
          "properties": {
            "foo": {
              "type": "boolean",
              "optional": "true",
              "description": "The foo."
            },
            "bar": {
              "type": "integer",
              "description": "The bar."
            },
            "baz": {
              "type": "object",
              "description": "Inception object.",
              "properties": {
                "depth": {
                  "type": "integer"
                }
              }
            }
          }
        },
        {
          "name": "callback",
          "type": "function",
          "parameters": [
            {
              "type": "object",
              "name": "returnObj",
              "properties": {
                "str": { "type": "string"}
              }
            }
          ],
          "description": "The callback to this heinous method"
        }
      ],
      "returns": {
        "type": "object",
        "properties": {
          "str": { "type": "string" },
          "int": { "type": "number" }
        }
      }
    } ]
  }
]"""

json_expected = ("""// Copyright %s 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.

// This file was generated by:
//   %s.
// NOTE: The format of types has changed. 'FooType' is now
//   'chrome.fakeJson.FooType'.
// Please run the closure compiler before committing changes.
// See https://code.google.com/p/chromium/wiki/ClosureCompilation.

/** @fileoverview Externs generated from namespace: fakeJson */

/**
 * @const
 */
chrome.fakeJson = {};

/**
 * @enum {string}
 * @see https://developer.chrome.com/extensions/fakeJson#type-CrazyEnum
 */
chrome.fakeJson.CrazyEnum = {
  CAMEL_CASE_ENUM: 'camelCaseEnum',
  NON_CHARACTERS: 'Non-Characters',
  _5NUM_FIRST: '5NumFirst',
  _3JUST_PLAIN_OLD_MEAN: '3Just-plainOld_MEAN',
};

/**
 * @param {{
 *   foo: (boolean|undefined),
 *   bar: number,
 *   baz: {
 *     depth: number
 *   }
 * }} inlineObj Evil inline object! With a super duper duper long string
 *     description that causes problems!
 * @param {function({
 *   str: string
 * }):void} callback The callback to this heinous method
 * @return {{
 *   str: string,
 *   int: number
 * }}
 * @see https://developer.chrome.com/extensions/fakeJson#method-funcWithInlineObj
 */
chrome.fakeJson.funcWithInlineObj = function(inlineObj, callback) {};""" %
    (datetime.now().year, sys.argv[0]))


class JsExternGeneratorTest(unittest.TestCase):
  def _GetNamespace(self, fake_content, filename, is_idl):
    """Returns a namespace object for the given content"""
    api_def = (idl_schema.Process(fake_content, filename) if is_idl
        else json_parse.Parse(fake_content))
    m = model.Model()
    return m.AddNamespace(api_def[0], filename)

  def setUp(self):
    self.maxDiff = None # Lets us see the full diff when inequal.

  def testBasic(self):
    namespace = self._GetNamespace(fake_idl, 'fake_api.idl', True)
    self.assertMultiLineEqual(expected_output,
                              JsExternsGenerator().Generate(namespace).Render())

  def testJsonWithInlineObjects(self):
    namespace = self._GetNamespace(fake_json, 'fake_api.json', False)
    self.assertMultiLineEqual(json_expected,
                              JsExternsGenerator().Generate(namespace).Render())


if __name__ == '__main__':
  unittest.main()