summaryrefslogtreecommitdiffstats
path: root/toolkit/modules/tests/xpcshell/test_JsonSchema.js
blob: b3a09049ac459b86eb1ad770819af09213c5b570 (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
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

const { JsonSchema } = ChromeUtils.importESModule(
  "resource://gre/modules/JsonSchema.sys.mjs"
);

add_task(function test_basicSchema() {
  info("Testing validation of a basic schema");
  const schema = {
    type: "object",
    properties: {
      id: { type: "number" },
    },
    required: ["id"],
  };

  const validator = new JsonSchema.Validator(schema);

  Assert.deepEqual(
    JsonSchema.validate({ id: 123 }, schema),
    { valid: true, errors: [] },
    "Validation of basic schemas with validate()"
  );

  Assert.deepEqual(
    validator.validate({ id: 123 }, schema),
    { valid: true, errors: [] },
    "Validation of basic schemas with Validator"
  );

  Assert.ok(
    !JsonSchema.validate({}, schema).valid,
    "Validation of basic schemas with validate()"
  );
  Assert.ok(
    !validator.validate({}).valid,
    "Validation of basic schemas with Validator"
  );
});

add_task(function test_mozUrlFormat() {
  info("Testing custom string format 'moz-url-format'");
  const schema = {
    type: "string",
    format: "moz-url-format",
  };

  {
    const obj = "https://www.mozilla.org/%LOCALE%/";
    Assert.deepEqual(
      JsonSchema.validate(obj, schema),
      { valid: true, errors: [] },
      "Substitution of a valid variable validates"
    );
  }

  {
    const obj = "https://mozilla.org/%BOGUS%/";

    Assert.equal(
      Services.urlFormatter.formatURL(obj),
      obj,
      "BOGUS is an invalid variable for the URL formatter service"
    );

    Assert.ok(
      !JsonSchema.validate(obj, { type: "string", format: "uri" }).valid,
      "A moz-url-format string does not validate as a URI"
    );

    Assert.deepEqual(
      JsonSchema.validate(obj, schema),
      {
        valid: false,
        errors: [
          {
            instanceLocation: "#",
            keyword: "format",
            keywordLocation: "#/format",
            error: `String does not match format "moz-url-format".`,
          },
        ],
      },
      "Substitution of an invalid variable does not validate"
    );
  }
});