summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/webidl-api/test/test_json_schema_parsing.py
blob: 79b59bf928d9a980ef03ff47b7890fc2ff3dcf0d (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
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import json
import os
from textwrap import dedent

import helpers  # Import test helpers module.
import mozunit
import pytest

helpers.setup()

from GenerateWebIDLBindings import APIEvent, APIFunction, APINamespace, APIType, Schemas


def test_parse_simple_single_api_namespace(write_jsonschema_fixtures):
    """
    Test Basic loading and parsing a single API JSONSchema:
    - single line comments outside of the json structure are ignored
    - parse a simple namespace that includes one permission, type,
      function and event
    """
    schema_dir = write_jsonschema_fixtures(
        {
            "test_api.json": dedent(
                """
          // Single line comments added before the JSON data are tolerated
          // and ignored.
          [
            {
              "namespace": "fantasyApi",
              "permissions": ["fantasyPermission"],
              "types": [
                  {
                    "id": "MyType",
                    "type": "string",
                    "choices": ["value1", "value2"]
                  }
              ],
              "functions": [
                {
                  "name": "myMethod",
                  "type": "function",
                  "parameters": [
                    { "name": "fnParam", "type": "string" },
                    { "name": "fnRefParam", "$ref": "MyType" }
                  ]
                }
              ],
              "events": [
                {
                  "name": "onSomeEvent",
                  "type": "function",
                  "parameters": [
                     { "name": "evParam", "type": "string" },
                     { "name": "evRefParam", "$ref": "MyType" }
                  ]
                }
              ]
            }
          ]
        """
            ),
        }
    )

    schemas = Schemas()
    schemas.load_schemas(schema_dir, "toolkit")

    assert schemas.get_all_namespace_names() == ["fantasyApi"]

    apiNs = schemas.api_namespaces["fantasyApi"]
    assert isinstance(apiNs, APINamespace)

    # Properties related to where the JSON schema is coming from
    # (toolkit, browser or mobile schema directories).
    assert apiNs.in_toolkit
    assert not apiNs.in_browser
    assert not apiNs.in_mobile

    # api_path_string is expected to be exactly the namespace name for
    # non-nested API namespaces.
    assert apiNs.api_path_string == "fantasyApi"

    # parse the schema and verify it includes the expected types events and function.
    schemas.parse_schemas()

    assert set(["fantasyPermission"]) == apiNs.permissions
    assert ["MyType"] == list(apiNs.types.keys())
    assert ["myMethod"] == list(apiNs.functions.keys())
    assert ["onSomeEvent"] == list(apiNs.events.keys())

    type_entry = apiNs.types.get("MyType")
    fn_entry = apiNs.functions.get("myMethod")
    ev_entry = apiNs.events.get("onSomeEvent")

    assert isinstance(type_entry, APIType)
    assert isinstance(fn_entry, APIFunction)
    assert isinstance(ev_entry, APIEvent)


def test_parse_error_on_types_without_id_or_extend(
    base_schema, write_jsonschema_fixtures
):
    """
    Test parsing types without id or $extend raise an error while parsing.
    """
    schema_dir = write_jsonschema_fixtures(
        {
            "test_broken_types.json": json.dumps(
                [
                    {
                        **base_schema(),
                        "namespace": "testBrokenTypeAPI",
                        "types": [
                            {
                                # type with no "id2 or "$ref" properties
                            }
                        ],
                    }
                ]
            )
        }
    )

    schemas = Schemas()
    schemas.load_schemas(schema_dir, "toolkit")

    with pytest.raises(
        Exception,
        match=r"Error loading schema type data defined in 'toolkit testBrokenTypeAPI'",
    ):
        schemas.parse_schemas()


def test_parse_ignores_unsupported_types(base_schema, write_jsonschema_fixtures):
    """
    Test parsing types without id or $extend raise an error while parsing.
    """
    schema_dir = write_jsonschema_fixtures(
        {
            "test_broken_types.json": json.dumps(
                [
                    {
                        **base_schema(),
                        "namespace": "testUnsupportedTypesAPI",
                        "types": [
                            {
                                "id": "AnUnsupportedType",
                                "type": "string",
                                "unsupported": True,
                            },
                            {
                                # missing id or $ref shouldn't matter
                                # no parsing error expected.
                                "unsupported": True,
                            },
                            {"id": "ASupportedType", "type": "string"},
                        ],
                    }
                ]
            )
        }
    )

    schemas = Schemas()
    schemas.load_schemas(schema_dir, "toolkit")
    schemas.parse_schemas()
    apiNs = schemas.api_namespaces["testUnsupportedTypesAPI"]
    assert set(apiNs.types.keys()) == set(["ASupportedType"])


def test_parse_error_on_namespace_with_inconsistent_max_manifest_version(
    base_schema, write_jsonschema_fixtures, tmpdir
):
    """
    Test parsing types without id or $extend raise an error while parsing.
    """
    browser_schema_dir = os.path.join(tmpdir, "browser")
    mobile_schema_dir = os.path.join(tmpdir, "mobile")
    os.mkdir(browser_schema_dir)
    os.mkdir(mobile_schema_dir)

    base_namespace_schema = {
        **base_schema(),
        "namespace": "testInconsistentMaxManifestVersion",
    }

    browser_schema = {**base_namespace_schema, "max_manifest_version": 2}
    mobile_schema = {**base_namespace_schema, "max_manifest_version": 3}

    write_jsonschema_fixtures(
        {"test_inconsistent_maxmv.json": json.dumps([browser_schema])},
        browser_schema_dir,
    )

    write_jsonschema_fixtures(
        {"test_inconsistent_maxmv.json": json.dumps([mobile_schema])}, mobile_schema_dir
    )

    schemas = Schemas()
    schemas.load_schemas(browser_schema_dir, "browser")
    schemas.load_schemas(mobile_schema_dir, "mobile")

    with pytest.raises(
        TypeError,
        match=r"Error loading schema data - overwriting existing max_manifest_version value",
    ):
        schemas.parse_schemas()


if __name__ == "__main__":
    mozunit.main()