def testCloseStatusCode(self):
        """ Test extraction of close frame status code and close reason in WebSocketApp
        """
        def on_close(wsapp, close_status_code, close_msg):
            print("on_close reached")

        app = ws.WebSocketApp('wss://tsock.us1.twilio.com/v3/wsconnect', on_close=on_close)
        closeframe = ws.ABNF(opcode=ws.ABNF.OPCODE_CLOSE, data=b'\x03\xe8no-init-from-client')
        self.assertEqual([1000, 'no-init-from-client'], app._get_close_args(closeframe))

        closeframe = ws.ABNF(opcode=ws.ABNF.OPCODE_CLOSE, data=b'')
        self.assertEqual([None, None], app._get_close_args(closeframe))

        app2 = ws.WebSocketApp('wss://tsock.us1.twilio.com/v3/wsconnect')
        closeframe = ws.ABNF(opcode=ws.ABNF.OPCODE_CLOSE, data=b'')
        self.assertEqual([None, None], app2._get_close_args(closeframe))

        self.assertRaises(ws.WebSocketConnectionClosedException, app.send, data="test if connection is closed")
Beispiel #2
0
    def request(
        self,
        request: Request,
        signed: bool = False,
        timeout: int = DEFAULT_REQUEST_TIMEOUT_SEC,
    ):
        if signed:
            raise ValueError(
                "Client signatures over WebSocket are not supported by CCF")

        if self.ws is None:
            LOG.info("Creating WSS connection")
            try:
                self.ws = websocket.create_connection(
                    f"wss://{self.host}:{self.port}",
                    sslopt={
                        "certfile":
                        self.cert if not self.disable_client_auth else None,
                        "keyfile":
                        self.key if not self.disable_client_auth else None,
                        "ca_certs": self.ca,
                    },
                    timeout=timeout,
                )
            except Exception as exc:
                raise CCFConnectionException from exc

        assert self.ws is not None

        if isinstance(request.body, str):
            payload = request.body.encode()
        elif isinstance(request.body, bytes):
            payload = request.body
        else:
            payload = json.dumps(request.body).encode()
        path = (request.path).encode()
        header = struct.pack("<h", len(path)) + path
        # FIN, no RSV, BIN, UNMASKED every time, because it's all we support right now
        frame = websocket.ABNF(1, 0, 0, 0, websocket.ABNF.OPCODE_BINARY, 0,
                               header + payload)
        self.ws.send_frame(frame)
        out = self.ws.recv_frame().data
        (status_code, ) = struct.unpack("<h", out[:2])
        seqno = unpack_seqno_or_view(out[2:10])
        view = unpack_seqno_or_view(out[10:18])
        global_commit = unpack_seqno_or_view(out[18:26])
        payload = out[26:]
        body = RawResponseBody(payload)
        return Response(status_code,
                        body,
                        seqno,
                        view,
                        global_commit,
                        headers={})
Beispiel #3
0
    def request(
        self,
        request: Request,
        timeout: int = DEFAULT_REQUEST_TIMEOUT_SEC,
    ):

        if self.ws is None:
            LOG.info("Creating WSS connection")
            try:
                sslopt = {"ca_certs": self.ca}
                if self.session_auth:
                    sslopt["certfile"] = self.session_auth.cert
                    sslopt["keyfile"] = self.session_auth.key
                self.ws = websocket.create_connection(
                    f"wss://{self.host}:{self.port}",
                    sslopt=sslopt,
                    timeout=timeout,
                )
            except Exception as exc:
                raise CCFConnectionException from exc

        assert self.ws is not None

        if isinstance(request.body, str):
            payload = request.body.encode()
        elif isinstance(request.body, bytes):
            payload = request.body
        else:
            payload = json.dumps(request.body).encode()
        path = (request.path).encode()
        header = struct.pack("<h", len(path)) + path
        # FIN, no RSV, BIN, UNMASKED every time, because it's all we support right now
        frame = websocket.ABNF(
            1, 0, 0, 0, websocket.ABNF.OPCODE_BINARY, 0, header + payload
        )
        self.ws.send_frame(frame)
        out = self.ws.recv_frame().data
        (status_code,) = struct.unpack("<h", out[:2])
        seqno = unpack_seqno_or_view(out[2:10])
        view = unpack_seqno_or_view(out[10:18])
        payload = out[18:]
        body = RawResponseBody(payload)
        return Response(status_code, body, seqno, view, headers={})
Beispiel #4
0
    def request(self, request, is_signed=False):
        assert not is_signed

        if not self.ws:
            LOG.info("Creating WSS connection")
            try:
                self.ws = websocket.create_connection(
                    f"wss://{self.host}:{self.port}",
                    sslopt={
                        "certfile": self.cert,
                        "keyfile": self.key,
                        "ca_certs": self.ca,
                    },
                    timeout=self.request_timeout,
                )
            except Exception as exc:
                raise CCFConnectionException from exc
        payload = json.dumps(request.params).encode()
        path = ("/" + request.method).encode()
        header = struct.pack("<h", len(path)) + path
        # FIN, no RSV, BIN, UNMASKED every time, because it's all we support right now
        frame = websocket.ABNF(1, 0, 0, 0, websocket.ABNF.OPCODE_BINARY, 0,
                               header + payload)
        self.ws.send_frame(frame)
        out = self.ws.recv_frame().data
        (status, ) = struct.unpack("<h", out[:2])
        (seqno, ) = struct.unpack("<Q", out[2:10])
        (view, ) = struct.unpack("<Q", out[10:18])
        (global_commit, ) = struct.unpack("<Q", out[18:26])
        payload = out[26:]
        if status == 200:
            result = json.loads(payload) if payload else None
            error = None
        else:
            result = None
            error = payload.decode()
        return Response(status,
                        result,
                        error,
                        seqno,
                        view,
                        global_commit,
                        headers={})