Bug 676439 - Websocket Binary Message support: tests. r=mcmanus

This commit is contained in:
Jason Duell 2011-12-15 15:19:51 -08:00
parent 519437da29
commit cd5794508e
10 changed files with 667 additions and 2 deletions

View File

@ -45,6 +45,7 @@ include $(DEPTH)/config/autoconf.mk
DIRS += \
chrome \
websocket_hybi \
$(NULL)
MODULE = content

View File

@ -2,6 +2,7 @@ from mod_pywebsocket import msgutil
import time
import sys
import struct
# see the list of tests in test_websocket.html
@ -113,5 +114,23 @@ def web_socket_transfer_data(request):
msgutil.receive_message(request))
msgutil.send_message(request,
msgutil.receive_message(request))
elif request.ws_protocol == "test-44":
rcv = msgutil.receive_message(request)
# check we received correct binary msg
if len(rcv) == 3 \
and ord(rcv[0]) == 5 and ord(rcv[1]) == 0 and ord(rcv[2]) == 7:
# reply with binary msg 0x04
msgutil.send_message(request, struct.pack("cc", chr(0), chr(4)), True, True)
else:
msgutil.send_message(request, "incorrect binary msg received!")
elif request.ws_protocol == "test-45":
rcv = msgutil.receive_message(request)
# check we received correct binary msg
if rcv == "flob":
# send back same blob as binary msg
msgutil.send_message(request, rcv, True, True)
else:
msgutil.send_message(request, "incorrect binary msg received: '" + rcv + "'")
while not request.client_terminated:
msgutil.receive_message(request)

View File

@ -8,7 +8,9 @@
</head>
<body onload="testWebSocket()">
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=472529">Mozilla Bug </a>
<p id="display"></p>
<p id="display">
<input id="fileList" type="file"></input>
</p>
<div id="content">
</div>
<pre id="test">
@ -64,10 +66,13 @@
* 40. negative test for wss:// with no cert
* 41. HSTS
* 42. non-char utf-8 sequences
* 43. Test setting binaryType attribute
* 44. Test sending/receving binary ArrayBuffer
* 45. Test sending/receving binary Blob
*/
var first_test = 1;
var last_test = 42;
var last_test = 45;
var current_test = first_test;
@ -1168,6 +1173,157 @@ function test42()
}
}
function test43()
{
var prots=["test-43"];
var ws = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", prots);
ws.onopen = function(e)
{
ok(true, "test 43 open");
// Test binaryType setting
ws.binaryType = "arraybuffer";
ws.binaryType = "blob";
try {
ws.binaryType = ""; // illegal
ok(false, "allowed ws.binaryType to be set to empty string");
} catch(e) {
ok(true, "prevented ws.binaryType to be set to empty string: " + e);
}
try {
ws.binaryType = "ArrayBuffer"; // illegal
ok(false, "allowed ws.binaryType to be set to 'ArrayBuffer'");
} catch(e) {
ok(true, "prevented ws.binaryType to be set to 'ArrayBuffer' " + e);
}
try {
ws.binaryType = "Blob"; // illegal
ok(false, "allowed ws.binaryType to be set to 'Blob'");
} catch(e) {
ok(true, "prevented ws.binaryType to be set to 'Blob' " + e);
}
try {
ws.binaryType = "mcfoofluu"; // illegal
ok(false, "allowed ws.binaryType to be set to 'mcfoofluu'");
} catch(e) {
ok(true, "prevented ws.binaryType to be set to 'mcfoofluu'");
}
ws.close();
};
ws.onclose = function(e)
{
ok(true, "test 43 close");
doTest(44);
};
}
function test44()
{
var ws = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test-44");
ok(ws.readyState == 0, "bad readyState in test-44!");
ws.binaryType = "arraybuffer";
ws.onopen = function()
{
ok(ws.readyState == 1, "open bad readyState in test-44!");
var buf = new ArrayBuffer(3);
// create byte view
var view = new Uint8Array(buf);
view[0] = 5;
view[1] = 0; // null byte
view[2] = 7;
ws.send(buf);
}
ws.onmessage = function(e)
{
ok(e.data instanceof ArrayBuffer, "Should receive an arraybuffer!");
var view = new Uint8Array(e.data);
ok(view.length == 2 && view[0] == 0 && view[1] ==4, "testing Reply arraybuffer" );
ws.close();
}
ws.onclose = function(e)
{
ok(ws.readyState == 3, "onclose bad readyState in test-44!");
shouldCloseCleanly(e);
doTest(45);
}
}
function createDOMFile(fileName, fileData)
{
// enablePrivilege is picky about where it's called? if I put it in global
// scope at start of <script> it doesn't work...
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
// create File in profile dir
var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]
.getService(Components.interfaces.nsIProperties);
var testFile = dirSvc.get("ProfD", Components.interfaces.nsIFile);
testFile.append(fileName);
var outStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
.createInstance(Components.interfaces.nsIFileOutputStream);
outStream.init(testFile, 0x02 | 0x08 | 0x20, 0666, 0);
outStream.write(fileData, fileData.length);
outStream.close();
// Set filename into DOM <input> field, as if selected by user
var fileList = document.getElementById('fileList');
fileList.value = testFile.path;
// return JS File object, aka Blob
return fileList.files[0];
}
function test45()
{
var blobFile = createDOMFile("testBlobFile", "flob");
var ws = CreateTestWS("ws://mochi.test:8888/tests/content/base/test/file_websocket", "test-45");
ok(ws.readyState == 0, "bad readyState in test-45!");
// ws.binaryType = "blob"; // Don't need to specify: blob is the default
ws.onopen = function()
{
ok(ws.readyState == 1, "open bad readyState in test-45!");
ws.send(blobFile);
}
var test45blob;
ws.onmessage = function(e)
{
test45blob = e.data;
ok(test45blob instanceof Blob, "We should be receiving a Blob");
ws.close();
}
ws.onclose = function(e)
{
ok(ws.readyState == 3, "onclose bad readyState in test-45!");
shouldCloseCleanly(e);
// check blob contents
var reader = new FileReader();
reader.onload = function(event)
{
ok(reader.result == "flob", "response should be 'flob': got '"
+ reader.result + "'");
};
reader.onerror = function(event)
{
testFailed("Failed to read blob: error code = " + reader.error.code);
};
reader.onloadend = function(event)
{
doTest(46);
};
reader.readAsBinaryString(test45blob);
}
}
var ranAllTests = false;

View File

@ -0,0 +1,61 @@
#
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Mozilla Foundation.
# Portions created by the Initial Developer are Copyright (C) 2007
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the terms of
# either of the GNU General Public License Version 2 or later (the "GPL"),
# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH = ../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
relativesrcdir = content/base/test/websocket_hybi
include $(DEPTH)/config/autoconf.mk
include $(topsrcdir)/config/rules.mk
#### MODULE = content
_TEST_FILES = \
test_send-arraybuffer.html \
test_send-blob.html \
file_check-binary-messages_wsh.py \
test_receive-arraybuffer.html \
test_receive-blob.html \
file_binary-frames_wsh.py \
$(NULL)
libs:: $(_TEST_FILES)
$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)

View File

@ -0,0 +1,18 @@
from mod_pywebsocket import common
from mod_pywebsocket import stream
def web_socket_do_extra_handshake(request):
pass
def web_socket_transfer_data(request):
messages_to_send = ['Hello, world!', '', all_distinct_bytes()]
for message in messages_to_send:
# FIXME: Should use better API to send binary messages when pywebsocket supports it.
header = stream.create_header(common.OPCODE_BINARY, len(message), 1, 0, 0, 0, 0)
request.connection.write(header + message)
def all_distinct_bytes():
return ''.join([chr(i) for i in xrange(256)])

View File

@ -0,0 +1,21 @@
from mod_pywebsocket import common
from mod_pywebsocket import msgutil
def web_socket_do_extra_handshake(request):
pass # Always accept.
def web_socket_transfer_data(request):
expected_messages = ['Hello, world!', '', all_distinct_bytes()]
for test_number, expected_message in enumerate(expected_messages):
message = msgutil.receive_message(request)
if type(message) == str and message == expected_message:
msgutil.send_message(request, 'PASS: Message #%d.' % test_number)
else:
msgutil.send_message(request, 'FAIL: Message #%d: Received unexpected message: %r' % (test_number, message))
def all_distinct_bytes():
return ''.join([chr(i) for i in xrange(256)])

View File

@ -0,0 +1,97 @@
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<p id="display"></p>
<div id="content" style="display: none">
</div>
<pre id="test">
<script class="testbody" type="text/javascript">
function debug(msg) {
ok(1, msg);
}
function createArrayBufferContainingHelloWorld()
{
var hello = "Hello, world!";
var array = new Uint8Array(hello.length);
for (var i = 0; i < hello.length; ++i)
array[i] = hello.charCodeAt(i);
return array.buffer;
}
function createEmptyArrayBuffer()
{
return new ArrayBuffer(0);
}
function createArrayBufferContainingAllDistinctBytes()
{
var array = new Uint8Array(256);
for (var i = 0; i < 256; ++i)
array[i] = i;
return array.buffer;
}
var ws = new MozWebSocket("ws://mochi.test:8888/tests/content/base/test/websocket_hybi/file_binary-frames");
ws.binaryType = "arraybuffer";
is(ws.binaryType, "arraybuffer", "should be equal to 'arraybuffer'");
var closeEvent;
var receivedMessages = [];
var expectedValues = [createArrayBufferContainingHelloWorld(), createEmptyArrayBuffer(), createArrayBufferContainingAllDistinctBytes()];
ws.onmessage = function(event)
{
receivedMessages.push(event.data);
};
ws.onclose = function(event)
{
closeEvent = event;
is(receivedMessages.length, expectedValues.length, "lengths not equal");
for (var i = 0; i < expectedValues.length; ++i)
check(i);
SimpleTest.finish();
};
var responseType;
function check(index)
{
debug("Checking message #" + index + ".");
ok(receivedMessages[index] instanceof ArrayBuffer,
"Should receive an arraybuffer!");
checkArrayBuffer(index, receivedMessages[index], expectedValues[index]);
}
var actualArray;
var expectedArray;
function checkArrayBuffer(testIndex, actual, expected)
{
actualArray = new Uint8Array(actual);
expectedArray = new Uint8Array(expected);
is(actualArray.length, expectedArray.length, "lengths not equal");
// Print only the first mismatched byte in order not to flood console.
for (var i = 0; i < expectedArray.length; ++i) {
if (actualArray[i] != expectedArray[i]) {
ok(false, "Value mismatch: actualArray[" + i + "] = " + actualArray[i] + ", expectedArray[" + i + "] = " + expectedArray[i]);
return;
}
}
ok(true, "Passed: Message #" + testIndex + ".");
}
SimpleTest.waitForExplicitFinish();
</script>
</body>
</html>

View File

@ -0,0 +1,110 @@
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<p id="display"></p>
<div id="content" style="display: none">
</div>
<pre id="test">
<script class="testbody" type="text/javascript">
function debug(msg) {
ok(true, msg);
}
function createArrayBufferContainingHelloWorld()
{
var hello = "Hello, world!";
var array = new Uint8Array(hello.length);
for (var i = 0; i < hello.length; ++i)
array[i] = hello.charCodeAt(i);
return array.buffer;
}
function createEmptyArrayBuffer()
{
return new ArrayBuffer(0);
}
function createArrayBufferContainingAllDistinctBytes()
{
var array = new Uint8Array(256);
for (var i = 0; i < 256; ++i)
array[i] = i;
return array.buffer;
}
var ws = new MozWebSocket("ws://mochi.test:8888/tests/content/base/test/websocket_hybi/file_binary-frames");
is(ws.binaryType, "blob", "should be 'blob'");
var closeEvent;
var receivedMessages = [];
var expectedValues = [createArrayBufferContainingHelloWorld(), createEmptyArrayBuffer(), createArrayBufferContainingAllDistinctBytes()];
ws.onmessage = function(event)
{
receivedMessages.push(event.data);
};
ws.onclose = function(event)
{
closeEvent = event;
is(receivedMessages.length, expectedValues.length, "lengths not same");
check(0);
};
var responseType;
function check(index)
{
if (index == expectedValues.length) {
SimpleTest.finish();
return;
}
debug("Checking message #" + index + ".");
ok(receivedMessages[index] instanceof Blob,
"We should be receiving a Blob");
var reader = new FileReader();
reader.readAsArrayBuffer(receivedMessages[index]);
reader.onload = function(event)
{
checkArrayBuffer(index, reader.result, expectedValues[index]);
check(index + 1);
};
reader.onerror = function(event)
{
ok(false, "Failed to read blob: error code = " + reader.error.code);
check(index + 1);
};
}
var actualArray;
var expectedArray;
function checkArrayBuffer(testIndex, actual, expected)
{
actualArray = new Uint8Array(actual);
expectedArray = new Uint8Array(expected);
is(actualArray.length, expectedArray.length, "lengths not same");
// Print only the first mismatched byte in order not to flood console.
for (var i = 0; i < expectedArray.length; ++i) {
if (actualArray[i] != expectedArray[i]) {
ok(false, "Value mismatch: actualArray[" + i + "] = " + actualArray[i] + ", expectedArray[" + i + "] = " + expectedArray[i]);
return;
}
}
ok(true, "Passed: Message #" + testIndex + ".");
}
SimpleTest.waitForExplicitFinish();
</script>
</body>
</html>

View File

@ -0,0 +1,82 @@
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<p id="display"></p>
<div id="content" style="display: none">
</div>
<pre id="test">
<script class="testbody" type="text/javascript">
function debug(msg) {
ok(1, msg);
}
function startsWith(target, prefix)
{
return target.indexOf(prefix) === 0;
}
function createArrayBufferContainingHelloWorld()
{
var hello = "Hello, world!";
var array = new Uint8Array(hello.length);
for (var i = 0; i < hello.length; ++i)
array[i] = hello.charCodeAt(i);
return array.buffer;
}
function createEmptyArrayBuffer()
{
return new ArrayBuffer(0);
}
function createArrayBufferContainingAllDistinctBytes()
{
var array = new Uint8Array(256);
for (var i = 0; i < 256; ++i)
array[i] = i;
return array.buffer;
}
var ws = new MozWebSocket("ws://mochi.test:8888/tests/content/base/test/websocket_hybi/file_check-binary-messages");
var closeEvent;
ws.onopen = function()
{
ok(true, "onopen reached");
ws.send(createArrayBufferContainingHelloWorld());
ws.send(createEmptyArrayBuffer());
ws.send(createArrayBufferContainingAllDistinctBytes());
};
ws.onmessage = function(event)
{
var message = event.data;
if (startsWith(message, "PASS"))
ok(true, message);
else
ok(false, message);
};
ws.onclose = function(event)
{
ok(event.wasClean, "should have closed cleanly");
SimpleTest.finish();
};
ws.onerror = function(event)
{
ok(false, "onerror should not have been called");
};
SimpleTest.waitForExplicitFinish();
</script>
</body>
</html>

View File

@ -0,0 +1,100 @@
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<p id="display">
<input id="fileList" type="file"></input>
</p>
<div id="content" style="display: none">
</div>
<pre id="test">
<script class="testbody" type="text/javascript">
function startsWith(target, prefix)
{
return target.indexOf(prefix) === 0;
}
function createDOMFile(fileName, fileData)
{
// enablePrivilege is picky about where it's called? if I put it in global
// scope at start of <script> it doesn't work...
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
// create File in profile dir
var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]
.getService(Components.interfaces.nsIProperties);
var testFile = dirSvc.get("ProfD", Components.interfaces.nsIFile);
testFile.append(fileName);
var outStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
.createInstance(Components.interfaces.nsIFileOutputStream);
outStream.init(testFile, 0x02 | 0x08 | 0x20, 0666, 0);
if (fileData) {
outStream.write(fileData, fileData.length);
outStream.close();
}
// Set filename into DOM <input> field, as if selected by user
var fileList = document.getElementById('fileList');
fileList.value = testFile.path;
// return JS File object, aka Blob
return fileList.files[0];
}
function createBlobContainingHelloWorld()
{
return createDOMFile("hellofile", "Hello, world!");
}
function createEmptyBlob()
{
return createDOMFile("emptyfile");
}
function createBlobContainingAllDistinctBytes()
{
var array = new Array();
for (var i = 0; i < 256; ++i)
array[i] = i;
// Concatenates chars into a single binary string
binaryString = String.fromCharCode.apply(null, array);
return createDOMFile("allchars", binaryString);
}
var ws = new MozWebSocket("ws://mochi.test:8888/tests/content/base/test/websocket_hybi/file_check-binary-messages");
var closeEvent;
ws.onopen = function()
{
ws.send(createBlobContainingHelloWorld());
ws.send(createEmptyBlob());
ws.send(createBlobContainingAllDistinctBytes());
};
ws.onmessage = function(event)
{
var message = event.data;
if (startsWith(message, "PASS"))
ok(true, message);
else
ok(false, message);
};
ws.onclose = function(event)
{
ok(event.wasClean, "should have closed cleanly");
SimpleTest.finish();
};
SimpleTest.waitForExplicitFinish();
</script>
</body>
</html>