예제 #1
0
 def test_handshake(self, mock_connect: mock.Mock,
                    mock_b64encode: mock.Mock) -> None:
     key = b'MySecretKey'
     mock_b64encode.return_value = key
     mock_connect.return_value.recv.return_value = \
         build_websocket_handshake_response(
             WebsocketFrame.key_to_accept(key))
     _ = WebsocketClient(DEFAULT_IPV4_HOSTNAME, DEFAULT_PORT)
     mock_connect.return_value.send.assert_called_with(
         build_websocket_handshake_request(key))
 def test_handshake(self, mock_connect: mock.Mock,
                    mock_b64encode: mock.Mock,
                    mock_gethostbyname: mock.Mock) -> None:
     key = b'MySecretKey'
     mock_b64encode.return_value = key
     mock_gethostbyname.return_value = '127.0.0.1'
     mock_connect.return_value.recv.return_value = \
         build_websocket_handshake_response(
             WebsocketFrame.key_to_accept(key))
     client = WebsocketClient(b'localhost', DEFAULT_PORT)
     mock_connect.return_value.send.assert_not_called()
     client.handshake()
     mock_connect.return_value.send.assert_called_with(
         build_websocket_handshake_request(key))
예제 #3
0
    def test_send_recv_frames_success(
        self,
        mock_connect: mock.Mock,
        mock_selector: mock.Mock,
        mock_b64encode: mock.Mock,
    ) -> None:
        key = b'MySecretKey'
        mock_b64encode.return_value = key
        mock_connect.return_value.recv.side_effect = [
            build_websocket_handshake_response(
                WebsocketFrame.key_to_accept(key), ),
            WebsocketFrame.text(b'world'),
        ]

        def on_message(frame: WebsocketFrame) -> None:
            assert frame.build() == WebsocketFrame.text(b'world')

        client = WebsocketClient(
            b'localhost',
            DEFAULT_PORT,
            on_message=on_message,
        )
        mock_selector.assert_called_once()
        client.handshake()
        client.queue(memoryview(WebsocketFrame.text(b'hello')))
        mock_connect.return_value.send.assert_called_once()
        mock_selector.return_value.select.side_effect = [
            [
                (mock.Mock(), selectors.EVENT_WRITE),
            ],
        ]
        client.run_once()
        self.assertEqual(mock_connect.return_value.send.call_count, 2)
        mock_selector.return_value.select.side_effect = [
            [
                (mock.Mock(), selectors.EVENT_READ),
            ],
        ]
        client.run_once()