chromium/third_party/blink/web_tests/http/tests/websocket/fragmented-binary-frames.html

<!DOCTYPE html>
<html>
<head>
<script src="/js-test-resources/js-test.js"></script>
</head>
<body>
<div id="description"></div>
<div id="console"></div>
<script>
description("WebSocket: Receive fragmented binary messages.");

window.jsTestIsAsync = true;

function createHelloWorldValue()
{
    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 createEmptyValue()
{
    return new ArrayBuffer(0);
}

// Create an ArrayBuffer containing all distinct bytes ("\x00" to "\xFF").
function createAllBytesValue()
{
    var array = new Uint8Array(256);
    for (var i = 0; i < 256; ++i)
        array[i] = i;
    return array.buffer;
}

var ws = new WebSocket("ws://127.0.0.1:8880/fragmented-binary-frames");
shouldBeEqualToString("ws.binaryType", "blob");

var closeEvent;
var receivedMessages = [];
var expectedValues = [createHelloWorldValue(), createHelloWorldValue(), createEmptyValue(), createAllBytesValue()];

ws.onmessage = function(event)
{
    receivedMessages.push(event.data);
};

ws.onclose = function(event)
{
    closeEvent = event;

    shouldEvaluateTo("receivedMessages.length", expectedValues.length);
    check(0);
};

var responseType;

function check(index)
{
    if (index == expectedValues.length) {
        finishJSTest();
        return;
    }

    debug("Checking message #" + index + ".");
    responseType = '' + receivedMessages[index];
    shouldBeEqualToString("responseType", "[object 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)
    {
        testFailed("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);
    shouldEvaluateTo("actualArray.length", expectedArray.length);
    // 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]) {
            testFailed("Value mismatch: actualArray[" + i + "] = " + actualArray[i] + ", expectedArray[" + i + "] = " + expectedArray[i]);
            return;
        }
    }
    testPassed("Passed: Message #" + testIndex + ".");
}

</script>
</body>
</html>