- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / test / data / extensions / api_test / sockets_udp / api / background.js
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // net/tools/testserver/testserver.py is picky about the format of what it
6 // calls its "echo" messages. One might go so far as to mutter to oneself that
7 // it isn't an echo server at all.
8 //
9 // The response is based on the request but obfuscated using a random key.
10 const request = "0100000005320000005hello";
11 var expectedResponsePattern = /0100000005320000005.{11}/;
12
13 const socket = chrome.sockets.udp;
14 var address;
15 var bytesSent = 0;
16 var dataAsString;
17 var dataRead = [];
18 var port = -1;
19 var socketId = 0;
20 var succeeded = false;
21 var waitCount = 0;
22
23 // Many thanks to Dennis for his StackOverflow answer: http://goo.gl/UDanx
24 // Since amended to handle BlobBuilder deprecation.
25 function string2ArrayBuffer(string, callback) {
26   var blob = new Blob([string]);
27   var f = new FileReader();
28   f.onload = function(e) {
29     callback(e.target.result);
30   };
31   f.readAsArrayBuffer(blob);
32 }
33
34 function arrayBuffer2String(buf, callback) {
35   var blob = new Blob([new Uint8Array(buf)]);
36   var f = new FileReader();
37   f.onload = function(e) {
38     callback(e.target.result);
39   };
40   f.readAsText(blob);
41 }
42
43 ///////////////////////////////////////////////////////////////////////////////
44 // Test socket creation
45 //
46
47 var testSocketCreation = function() {
48   function onCreate(createInfo) {
49     function onGetInfo(info) {
50       if (info.localAddress || info.localPort) {
51         chrome.test.fail('Unconnected socket should not have local binding');
52       }
53
54       chrome.test.assertEq(createInfo.socketId, info.socketId);
55       chrome.test.assertEq(false, info.persistent);
56
57       socket.close(createInfo.socketId, function() {
58         socket.getInfo(createInfo.socketId, function(info) {
59           chrome.test.assertEq(undefined, info);
60           chrome.test.succeed();
61         });
62       });
63     }
64
65     chrome.test.assertTrue(createInfo.socketId > 0);
66
67     // Obtaining socket information before a connect() call should be safe, but
68     // return empty values.
69     socket.getInfo(createInfo.socketId, onGetInfo);
70   }
71
72   socket.create({}, onCreate);
73 };
74
75 ///////////////////////////////////////////////////////////////////////////////
76 // Test socket send/receive
77 //
78
79 function waitForBlockingOperation() {
80   if (++waitCount < 10) {
81     setTimeout(waitForBlockingOperation, 1000);
82   } else {
83     // We weren't able to succeed in the given time.
84     chrome.test.fail("Operations didn't complete after " + waitCount + " " +
85                      "seconds. Response so far was <" + dataAsString + ">.");
86   }
87 }
88
89 var testSending = function() {
90   dataRead = "";
91   succeeded = false;
92   waitCount = 0;
93
94   setTimeout(waitForBlockingOperation, 1000);
95   socket.create({}, function (socketInfo) {
96     console.log("socket created");
97     socketId = socketInfo.socketId;
98     chrome.test.assertTrue(socketId > 0, "failed to create socket");
99     socket.bind(socketId, "0.0.0.0", 0, function (result) {
100       console.log("socket bound to local host");
101       chrome.test.assertEq(0, result,
102                            "Connect or bind failed with error " + result);
103       if (result == 0) {
104         socket.getInfo(socketId, function (result) {
105           console.log("got socket info");
106           chrome.test.assertTrue(
107               !!result.localAddress,
108               "Bound socket should always have local address");
109           chrome.test.assertTrue(
110               !!result.localPort,
111               "Bound socket should always have local port");
112
113           string2ArrayBuffer(request, function(arrayBuffer) {
114             socket.onReceiveError.addListener(function (info) {
115               chrome.test.fail("Socket receive error:" + info.result);
116             });
117             socket.onReceive.addListener(function (info) {
118               console.log(
119                   "received bytes from echo server: " + info.data.byteLength);
120               if (socketId == info.socketId) {
121                 arrayBuffer2String(info.data, function(s) {
122                     dataAsString = s;  // save this for error reporting
123                     var match = !!s.match(expectedResponsePattern);
124                     chrome.test.assertTrue(
125                         match, "Received data does not match.");
126                     succeeded = true;
127                     chrome.test.succeed();
128                 });
129               }
130             });
131             console.log(
132                 "sending bytes to echo server: " + arrayBuffer.byteLength);
133             socket.send(socketId, arrayBuffer, address, port,
134                 function(sendInfo) {
135               chrome.test.assertEq(0, sendInfo.resultCode);
136               chrome.test.assertEq(sendInfo.bytesSent, arrayBuffer.byteLength);
137             });
138           });
139         });
140       }
141     });
142   });
143 };
144
145 ///////////////////////////////////////////////////////////////////////////////
146 // Test driver
147 //
148
149 var onMessageReply = function(message) {
150   var parts = message.split(":");
151   var test_type = parts[0];
152   address = parts[1];
153   port = parseInt(parts[2]);
154   console.log("Running tests, echo server " +
155               address + ":" + port);
156   if (test_type == 'multicast') {
157     console.log("Running multicast tests");
158     chrome.test.runTests([ testMulticast ]);
159   } else {
160     console.log("Running udp tests");
161     chrome.test.runTests([ testSocketCreation, testSending ]);
162   }
163 };
164
165 // Find out which protocol we're supposed to test, and which echo server we
166 // should be using, then kick off the tests.
167 chrome.test.sendMessage("info_please", onMessageReply);