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

/**
 * Tests to ensure that icons for application provided engines are correctly
 * loaded from remote settings.
 */

"use strict";

// A skeleton configuration that gets filled in from TESTS during `add_setup`.
let CONFIG = [
  {
    recordType: "defaultEngines",
    globalDefault: "engine_no_icon",
    specificDefaults: [],
  },
  {
    recordType: "engineOrders",
    orders: [],
  },
];

let TESTS = [
  {
    engineId: "engine_no_icon",
    expectedIcon: null,
  },
  {
    engineId: "engine_exact_match",
    icons: [
      {
        filename: "remoteIcon.ico",
        engineIdentifiers: ["engine_exact_match"],
        imageSize: 16,
      },
    ],
    expectedIcon: "remoteIcon.ico",
  },
  {
    engineId: "engine_begins_with",
    icons: [
      {
        filename: "remoteIcon.ico",
        engineIdentifiers: ["engine_begins*"],
        imageSize: 16,
      },
    ],
    expectedIcon: "remoteIcon.ico",
  },
  {
    engineId: "engine_non_default_sized_icon",
    icons: [
      {
        filename: "remoteIcon.ico",
        engineIdentifiers: ["engine_non_default_sized_icon"],
        imageSize: 32,
      },
    ],
    expectedIcon: "remoteIcon.ico",
  },
  {
    engineId: "engine_multiple_icons",
    icons: [
      {
        filename: "bigIcon.ico",
        engineIdentifiers: ["engine_multiple_icons"],
        imageSize: 16,
      },
      {
        filename: "remoteIcon.ico",
        engineIdentifiers: ["engine_multiple_icons"],
        imageSize: 32,
      },
    ],
    expectedIcon: "bigIcon.ico",
  },
];

async function getFileDataBuffer(filename) {
  let data = await IOUtils.read(
    PathUtils.join(do_get_cwd().path, "data", filename)
  );
  return new TextEncoder().encode(data).buffer;
}

async function mockRecordWithAttachment({
  filename,
  engineIdentifiers,
  imageSize,
}) {
  let buffer = await getFileDataBuffer(filename);

  let stream = Cc["@mozilla.org/io/arraybuffer-input-stream;1"].createInstance(
    Ci.nsIArrayBufferInputStream
  );
  stream.setData(buffer, 0, buffer.byteLength);

  // Generate a hash.
  let hasher = Cc["@mozilla.org/security/hash;1"].createInstance(
    Ci.nsICryptoHash
  );
  hasher.init(Ci.nsICryptoHash.SHA256);
  hasher.updateFromStream(stream, -1);
  let hash = hasher.finish(false);
  hash = Array.from(hash, (_, i) =>
    ("0" + hash.charCodeAt(i).toString(16)).slice(-2)
  ).join("");

  let record = {
    id: Services.uuid.generateUUID().toString(),
    engineIdentifiers,
    imageSize,
    attachment: {
      hash,
      location: `main-workspace/search-config-icons/${filename}`,
      filename,
      size: buffer.byteLength,
      mimetype: "application/json",
    },
  };

  let attachment = {
    record,
    blob: new Blob([buffer]),
  };

  return { record, attachment };
}

async function insertRecordIntoCollection(client, db, item) {
  let { record, attachment } = await mockRecordWithAttachment(item);
  await db.create(record);
  await client.attachments.cacheImpl.set(record.id, attachment);
  await db.importChanges({}, Date.now());
}

add_setup(async function () {
  let client = RemoteSettings("search-config-icons");
  let db = client.db;

  await db.clear();

  for (let test of TESTS) {
    CONFIG.push({
      identifier: test.engineId,
      recordType: "engine",
      base: {
        name: test.engineId + " name",
        urls: {
          search: {
            base: "https://example.com/" + test.engineId,
            searchTermParamName: "q",
          },
        },
      },
      variants: [{ environment: { allRegionsAndLocales: true } }],
    });

    if ("icons" in test) {
      for (let icon of test.icons) {
        await insertRecordIntoCollection(client, db, {
          ...icon,
          id: test.engineId,
        });
      }
    }
  }

  await SearchTestUtils.useTestEngines("simple-engines", null, CONFIG);
  await Services.search.init();
});

for (let test of TESTS) {
  add_task(async function () {
    info("Testing engine: " + test.engineId);

    let engine = Services.search.getEngineByName(test.engineId + " name");
    if (test.expectedIcon) {
      let engineIconURL = await engine.getIconURL(16);
      Assert.notEqual(
        engineIconURL,
        null,
        "Should have an icon URL for the engine."
      );

      let response = await fetch(engineIconURL);
      let buffer = new Uint8Array(await response.arrayBuffer());

      let expectedBuffer = new Uint8Array(
        await getFileDataBuffer(test.expectedIcon)
      );

      Assert.equal(
        buffer.length,
        expectedBuffer.length,
        "Should have received matching buffer lengths for the expected icon"
      );
      Assert.ok(
        buffer.every((value, index) => value === expectedBuffer[index]),
        "Should have received matching data for the expected icon"
      );
    } else {
      Assert.equal(
        await engine.getIconURL(),
        null,
        "Should not have an icon URL for the engine."
      );
    }
  });
}