test_ws.py 9.16 KB
Newer Older
1 2 3
# coding: utf8
from __future__ import unicode_literals

4
from hypothesis import assume, given, strategies, settings
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
from twisted.test import proto_helpers

from asgiref.inmemory import ChannelLayer
from daphne.http_protocol import HTTPFactory
from daphne.tests import http_strategies, testcases, factories


class WebSocketConnection(object):
    """
    Helper class that makes it easier to test Dahpne's WebSocket support.
    """

    def __init__(self):
        self.last_message = None

        self.channel_layer = ChannelLayer()
        self.factory = HTTPFactory(self.channel_layer, send_channel="test!")
        self.proto = self.factory.buildProtocol(('127.0.0.1', 0))
        self.transport = proto_helpers.StringTransport()
        self.proto.makeConnection(self.transport)

    def receive(self, request):
        """
        Low-level method to let Daphne handle HTTP/WebSocket data
        """
        self.proto.dataReceived(request)
        _, self.last_message = self.channel_layer.receive(['websocket.connect'])
        return self.last_message

    def send(self, content):
        """
        Method to respond with a channel message
        """
        if self.last_message is None:
            # Auto-connect for convenience.
            self.connect()
        self.factory.dispatch_reply(self.last_message['reply_channel'], content)
        response = self.transport.value()
        self.transport.clear()
        return response

    def connect(self, path='/', params=None, headers=None):
        """
        High-level method to perform the WebSocket handshake
        """
        request = factories.build_websocket_upgrade(path, params, headers or [])
        message = self.receive(request)
        return message


class TestHandshake(testcases.ASGIWebSocketTestCase):
    """
    Tests for the WebSocket handshake
    """

    def test_minimal(self):
        message = WebSocketConnection().connect()
        self.assert_valid_websocket_connect_message(message)

    @given(
        path=http_strategies.http_path(),
        params=http_strategies.query_params(),
        headers=http_strategies.headers(),
    )
69
    @settings(perform_health_check=False)
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 233 234 235 236 237 238 239 240 241 242 243 244 245 246
    def test_connection(self, path, params, headers):
        message = WebSocketConnection().connect(path, params, headers)
        self.assert_valid_websocket_connect_message(message, path, params, headers)


class TestSendCloseAccept(testcases.ASGIWebSocketTestCase):
    """
    Tests that, essentially, try to translate the send/close/accept section of the spec into code.
    """

    def test_empty_accept(self):
        response = WebSocketConnection().send({'accept': True})
        self.assert_websocket_upgrade(response)

    @given(text=http_strategies.http_body())
    def test_accept_and_text(self, text):
        response = WebSocketConnection().send({'accept': True, 'text': text})
        self.assert_websocket_upgrade(response, text.encode('ascii'))

    @given(data=http_strategies.binary_payload())
    def test_accept_and_bytes(self, data):
        response = WebSocketConnection().send({'accept': True, 'bytes': data})
        self.assert_websocket_upgrade(response, data)

    def test_accept_false(self):
        response = WebSocketConnection().send({'accept': False})
        self.assert_websocket_denied(response)

    def test_accept_false_with_text(self):
        """
        Tests that even if text is given, the connection is denied.

        We can't easily use Hypothesis to generate data for this test because it's
        hard to detect absence of the body if e.g. Hypothesis would generate a 'GET'
        """
        text = 'foobar'
        response = WebSocketConnection().send({'accept': False, 'text': text})
        self.assert_websocket_denied(response)
        self.assertNotIn(text.encode('ascii'), response)

    def test_accept_false_with_bytes(self):
        """
        Tests that even if data is given, the connection is denied.

        We can't easily use Hypothesis to generate data for this test because it's
        hard to detect absence of the body if e.g. Hypothesis would generate a 'GET'
        """
        data = b'foobar'
        response = WebSocketConnection().send({'accept': False, 'bytes': data})
        self.assert_websocket_denied(response)
        self.assertNotIn(data, response)

    @given(text=http_strategies.http_body())
    def test_just_text(self, text):
        assume(len(text) > 0)
        # If content is sent, accept=True is implied.
        response = WebSocketConnection().send({'text': text})
        self.assert_websocket_upgrade(response, text.encode('ascii'))

    @given(data=http_strategies.binary_payload())
    def test_just_bytes(self, data):
        assume(len(data) > 0)
        # If content is sent, accept=True is implied.
        response = WebSocketConnection().send({'bytes': data})
        self.assert_websocket_upgrade(response, data)

    def test_close_boolean(self):
        response = WebSocketConnection().send({'close': True})
        self.assert_websocket_denied(response)

    @given(number=strategies.integers(min_value=1))
    def test_close_integer(self, number):
        response = WebSocketConnection().send({'close': number})
        self.assert_websocket_denied(response)

    @given(text=http_strategies.http_body())
    def test_close_with_text(self, text):
        assume(len(text) > 0)
        response = WebSocketConnection().send({'close': True, 'text': text})
        self.assert_websocket_upgrade(response, text.encode('ascii'), expect_close=True)

    @given(data=http_strategies.binary_payload())
    def test_close_with_data(self, data):
        assume(len(data) > 0)
        response = WebSocketConnection().send({'close': True, 'bytes': data})
        self.assert_websocket_upgrade(response, data, expect_close=True)


class TestWebSocketProtocol(testcases.ASGIWebSocketTestCase):
    """
    Tests that the WebSocket protocol class correctly generates and parses messages.
    """

    def setUp(self):
        self.connection = WebSocketConnection()

    def test_basic(self):
        # Send a simple request to the protocol and get the resulting message off
        # of the channel layer.
        message = self.connection.receive(
            b"GET /chat HTTP/1.1\r\n"
            b"Host: somewhere.com\r\n"
            b"Upgrade: websocket\r\n"
            b"Connection: Upgrade\r\n"
            b"Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n"
            b"Sec-WebSocket-Protocol: chat, superchat\r\n"
            b"Sec-WebSocket-Version: 13\r\n"
            b"Origin: http://example.com\r\n"
            b"\r\n"
        )
        self.assertEqual(message['path'], "/chat")
        self.assertEqual(message['query_string'], b"")
        self.assertEqual(
            sorted(message['headers']),
            [(b'connection', b'Upgrade'),
             (b'host', b'somewhere.com'),
             (b'origin', b'http://example.com'),
             (b'sec-websocket-key', b'x3JJHMbDL1EzLkh9GBhXDw=='),
             (b'sec-websocket-protocol', b'chat, superchat'),
             (b'sec-websocket-version', b'13'),
             (b'upgrade', b'websocket')]
        )
        self.assert_valid_websocket_connect_message(message, '/chat')

        # Accept the connection
        response = self.connection.send({'accept': True})
        self.assert_websocket_upgrade(response)

        # Send some text
        response = self.connection.send({'text': "Hello World!"})
        self.assertEqual(response, b"\x81\x0cHello World!")

        # Send some bytes
        response = self.connection.send({'bytes': b"\xaa\xbb\xcc\xdd"})
        self.assertEqual(response, b"\x82\x04\xaa\xbb\xcc\xdd")

        # Close the connection
        response = self.connection.send({'close': True})
        self.assertEqual(response, b"\x88\x02\x03\xe8")

    def test_connection_with_file_origin_is_accepted(self):
        message = self.connection.receive(
            b"GET /chat HTTP/1.1\r\n"
            b"Host: somewhere.com\r\n"
            b"Upgrade: websocket\r\n"
            b"Connection: Upgrade\r\n"
            b"Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n"
            b"Sec-WebSocket-Protocol: chat, superchat\r\n"
            b"Sec-WebSocket-Version: 13\r\n"
            b"Origin: file://\r\n"
            b"\r\n"
        )
        self.assertIn((b'origin', b'file://'), message['headers'])
        self.assert_valid_websocket_connect_message(message, '/chat')

        # Accept the connection
        response = self.connection.send({'accept': True})
        self.assert_websocket_upgrade(response)

    def test_connection_with_no_origin_is_accepted(self):
        message = self.connection.receive(
            b"GET /chat HTTP/1.1\r\n"
            b"Host: somewhere.com\r\n"
            b"Upgrade: websocket\r\n"
            b"Connection: Upgrade\r\n"
            b"Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n"
            b"Sec-WebSocket-Protocol: chat, superchat\r\n"
            b"Sec-WebSocket-Version: 13\r\n"
            b"\r\n"
        )

        self.assertNotIn(b'origin', [header_tuple[0] for header_tuple in message['headers']])
        self.assert_valid_websocket_connect_message(message, '/chat')

        # Accept the connection
        response = self.connection.send({'accept': True})
        self.assert_websocket_upgrade(response)