summaryrefslogtreecommitdiffstats
path: root/browser/components/newtab/test/browser/browser_asrouter_bug1761522.js
blob: 13f5ac9b9cff1d47ef1c504892a22b91a76ab177 (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
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

const { ASRouter, MessageLoaderUtils } = ChromeUtils.import(
  "resource://activity-stream/lib/ASRouter.jsm"
);
const { PanelTestProvider } = ChromeUtils.importESModule(
  "resource://activity-stream/lib/PanelTestProvider.sys.mjs"
);
const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js");
const { RemoteL10n } = ChromeUtils.importESModule(
  "resource://activity-stream/lib/RemoteL10n.sys.mjs"
);
const { RemoteSettings } = ChromeUtils.importESModule(
  "resource://services-settings/remote-settings.sys.mjs"
);

// This pref is used to override the Remote Settings server URL in tests.
// See SERVER_URL in services/settings/Utils.jsm for more details.
const RS_SERVER_PREF = "services.settings.server";

const FLUENT_CONTENT = "asrouter-test-string = Test Test Test\n";

async function serveRemoteSettings() {
  const server = new HttpServer();
  server.start(-1);

  const baseURL = `http://localhost:${server.identity.primaryPort}/`;
  const attachmentUuid = crypto.randomUUID();
  const attachment = new TextEncoder().encode(FLUENT_CONTENT);

  // Serve an index so RS knows where to fetch images from.
  server.registerPathHandler("/v1/", (request, response) => {
    response.write(
      JSON.stringify({
        capabilities: {
          attachments: {
            base_url: `${baseURL}cdn`,
          },
        },
      })
    );
  });

  // Serve the ms-language-packs record for cfr-v1-ja-JP-mac, pointing to an attachment.
  server.registerPathHandler(
    "/v1/buckets/main/collections/ms-language-packs/records/cfr-v1-ja-JP-mac",
    (request, response) => {
      response.setStatusLine(null, 200, "OK");
      response.setHeader(
        "Content-type",
        "application/json; charset=utf-8",
        false
      );
      response.write(
        JSON.stringify({
          permissions: {},
          data: {
            attachment: {
              hash: "f9aead2693c4ff95c2764df72b43fdf5b3490ed06414588843848f991136040b",
              size: attachment.buffer.byteLength,
              filename: "asrouter.ftl",
              location: `main-workspace/ms-language-packs/${attachmentUuid}`,
            },
            id: "cfr-v1-ja-JP-mac",
            last_modified: Date.now(),
          },
        })
      );
    }
  );

  // Serve the attachment for ms-language-packs/cfr-va-ja-JP-mac.
  server.registerPathHandler(
    `/cdn/main-workspace/ms-language-packs/${attachmentUuid}`,
    (request, response) => {
      const stream = Cc[
        "@mozilla.org/io/arraybuffer-input-stream;1"
      ].createInstance(Ci.nsIArrayBufferInputStream);
      stream.setData(attachment.buffer, 0, attachment.buffer.byteLength);

      response.setStatusLine(null, 200, "OK");
      response.setHeader("Content-type", "application/octet-stream");
      response.bodyOutputStream.writeFrom(stream, attachment.buffer.byteLength);
    }
  );

  // Serve the list of changed collections. cfr must have changed, otherwise we
  // won't attempt to fetch the cfr records (and then won't fetch
  // ms-language-packs).
  server.registerPathHandler(
    "/v1/buckets/monitor/collections/changes/changeset",
    (request, response) => {
      const now = Date.now();
      response.setStatusLine(null, 200, "OK");
      response.setHeader(
        "Content-type",
        "application/json; charset=utf-8",
        false
      );
      response.write(
        JSON.stringify({
          timestamp: now,
          changes: [
            {
              host: `localhost:${server.identity.primaryPort}`,
              last_modified: now,
              bucket: "main",
              collection: "cfr",
            },
          ],
          metadata: {},
        })
      );
    }
  );

  const message = await PanelTestProvider.getMessages().then(msgs =>
    msgs.find(msg => msg.id === "PERSONALIZED_CFR_MESSAGE")
  );

  // Serve the "changed" cfr entries. If there are no changes, then ASRouter
  // won't re-fetch ms-language-packs.
  server.registerPathHandler(
    "/v1/buckets/main/collections/cfr/changeset",
    (request, response) => {
      const now = Date.now();
      response.setStatusLine(null, 200, "OK");
      response.setHeader(
        "Content-type",
        "application/json; charset=utf-8",
        false
      );
      response.write(
        JSON.stringify({
          timestamp: now,
          changes: [message],
          metadata: {},
        })
      );
    }
  );

  await SpecialPowers.pushPrefEnv({
    set: [[RS_SERVER_PREF, `${baseURL}v1`]],
  });

  return async () => {
    await new Promise(resolve => server.stop(() => resolve()));
    await SpecialPowers.popPrefEnv();
  };
}

add_task(async function test_asrouter() {
  const MS_LANGUAGE_PACKS_DIR = PathUtils.join(
    PathUtils.localProfileDir,
    "settings",
    "main",
    "ms-language-packs"
  );
  const sandbox = sinon.createSandbox();
  const stop = await serveRemoteSettings();
  await SpecialPowers.pushPrefEnv({
    set: [
      [
        "browser.newtabpage.activity-stream.asrouter.providers.cfr",
        JSON.stringify({
          id: "cfr",
          enabled: true,
          type: "remote-settings",
          collection: "cfr",
          updateCyleInMs: 3600000,
        }),
      ],
    ],
  });
  const localeService = Services.locale;
  RemoteSettings("cfr").verifySignature = false;

  registerCleanupFunction(async () => {
    RemoteSettings("cfr").verifySignature = true;
    Services.locale = localeService;
    await SpecialPowers.popPrefEnv();
    await stop();
    sandbox.restore();
    await IOUtils.remove(MS_LANGUAGE_PACKS_DIR, { recursive: true });
    RemoteL10n.reloadL10n();
  });

  // We can't stub Services.locale.appLocaleAsBCP47 directly because its an
  // XPCOM_Native object.
  const fakeLocaleService = new Proxy(localeService, {
    get(obj, prop) {
      if (prop === "appLocaleAsBCP47") {
        return "ja-JP-macos";
      }
      return obj[prop];
    },
  });

  const localeSpy = sandbox.spy(MessageLoaderUtils, "locale", ["get"]);
  Services.locale = fakeLocaleService;

  const cfrProvider = ASRouter.state.providers.find(p => p.id === "cfr");
  await ASRouter.loadMessagesFromAllProviders([cfrProvider]);

  Assert.equal(
    Services.locale.appLocaleAsBCP47,
    "ja-JP-macos",
    "Locale service returns ja-JP-macos"
  );
  Assert.ok(localeSpy.get.called, "MessageLoaderUtils.locale getter called");
  Assert.ok(
    localeSpy.get.alwaysReturned("ja-JP-mac"),
    "MessageLoaderUtils.locale getter returned expected locale ja-JP-mac"
  );

  const path = PathUtils.join(
    MS_LANGUAGE_PACKS_DIR,
    "browser",
    "newtab",
    "asrouter.ftl"
  );
  Assert.ok(await IOUtils.exists(path), "asrouter.ftl was downloaded");
  Assert.equal(
    await IOUtils.readUTF8(path),
    FLUENT_CONTENT,
    "asrouter.ftl content matches expected"
  );
});