summaryrefslogtreecommitdiffstats
path: root/devtools/shared/commands/network/tests/browser_network_command_sendHTTPRequest.js
blob: 1d84a8a668ef1f9ee1d65ea85e4815db83aa95d1 (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
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

// Test the NetworkCommand's sendHTTPRequest

add_task(async function () {
  info("Test NetworkCommand.sendHTTPRequest");
  const tab = await addTab("data:text/html,foo");
  const commands = await CommandsFactory.forTab(tab);

  // We have to ensure TargetCommand is initialized to have access to the top level target
  // from NetworkCommand.sendHTTPRequest
  await commands.targetCommand.startListening();

  const { networkCommand } = commands;

  const httpServer = createTestHTTPServer();
  const onRequest = new Promise(resolve => {
    httpServer.registerPathHandler(
      "/http-request.html",
      (request, response) => {
        response.setStatusLine(request.httpVersion, 200, "OK");
        response.write("Response body");
        resolve(request);
      }
    );
  });
  const url = `http://localhost:${httpServer.identity.primaryPort}/http-request.html`;

  info("Call NetworkCommand.sendHTTPRequest");
  const { resourceCommand } = commands;
  const { onResource } = await resourceCommand.waitForNextResource(
    resourceCommand.TYPES.NETWORK_EVENT
  );
  const { channelId } = await networkCommand.sendHTTPRequest({
    url,
    method: "POST",
    headers: [{ name: "Request", value: "Header" }],
    body: "Hello",
    cause: {
      loadingDocumentUri: "https://example.com",
      stacktraceAvailable: true,
      type: "xhr",
    },
  });
  ok(channelId, "Received a channel id in response");
  const resource = await onResource;
  is(
    resource.resourceId,
    channelId,
    "NETWORK_EVENT resource channelId is the same as the one returned by sendHTTPRequest"
  );

  const request = await onRequest;
  is(request.method, "POST", "Request method is correct");
  is(request.getHeader("Request"), "Header", "The custom header was passed");
  is(fetchRequestBody(request), "Hello", "The request POST's body is correct");

  await commands.destroy();
});

const BinaryInputStream = Components.Constructor(
  "@mozilla.org/binaryinputstream;1",
  "nsIBinaryInputStream",
  "setInputStream"
);

function fetchRequestBody(request) {
  let body = "";
  const bodyStream = new BinaryInputStream(request.bodyInputStream);
  let avail = 0;
  while ((avail = bodyStream.available()) > 0) {
    body += String.fromCharCode.apply(String, bodyStream.readByteArray(avail));
  }
  return body;
}