Ejemplo n.º 1
0
    def test_too_short_limit(self):
        """Test a too short limit.

        This case is marginal.
        """
        message = "few characters"

        with self.assertRaises(AssertionError) as error:
            truncate_message(message, limit=2)

        self.assertEqual(str(error.exception), "Limit too short")
Ejemplo n.º 2
0
    def create_player_error(self, playlist_entry_id, message):
        """Report an error to the server

        Args:
            playlist_entry_id (int): ID of the playlist entry. Must not be
                `None`.
            message (str): error message.

        Raises:
            AssertError: if `playlist_entry_id` is `None`.
        """
        assert playlist_entry_id is not None, "Entry with ID None is invalid"

        logger.debug(
            "Telling the server that playlist entry %i cannot be played",
            playlist_entry_id,
        )

        self.post(
            endpoint="playlist/player/errors/",
            data={
                "playlist_entry_id": playlist_entry_id,
                "error_message": truncate_message(message, 255),
            },
            message_on_error="Unable to send player error to server",
        )
Ejemplo n.º 3
0
    def test_small_message(self):
        """Test a small message is completelly displayed."""
        message = "few characters"
        message_displayed = truncate_message(message, limit=50)

        self.assertLessEqual(len(message_displayed), 50)
        self.assertEqual(message_displayed, "few characters")
Ejemplo n.º 4
0
    def test_long_message(self):
        """Test a long message is cut."""
        message = "few characters"
        message_displayed = truncate_message(message, limit=5)

        self.assertLessEqual(len(message_displayed), 5)
        self.assertEqual(message_displayed, "fe...")
Ejemplo n.º 5
0
        def on_error(response):
            # manage failed connection response
            if response.status_code == 400:
                return AuthenticationError(
                    "Login to server failed, check the config file")

            # manage any other error
            return AuthenticationError(
                "Unable to authenticate to the server, error {code}: {message}"
                .format(code=response.status_code,
                        message=truncate_message(response.text)))
Ejemplo n.º 6
0
    def on_message(self, message):
        """Callback when a message is received.

        It will call the method which name corresponds to the event type, if
        possible. Methods must have the name `receive_<name of the event type
        here>`, the type must be indicated in the `type` key of the message.
        The content of the message must be in the `data` key.

        Any error is logged.

        Args:
            message (str): A JSON text of the event.
        """
        # convert the message to an event object
        try:
            event = json.loads(message)

        # if the message is not in JSON format, assume this is an error
        except json.JSONDecodeError:
            logger.error("Unexpected message from the server: '%s'",
                         truncate_message(message))
            return

        # get the type of the message
        try:
            message_type = event["type"]

        except KeyError:
            logger.error("Event of no type received")
            return

        # attempt to call the corresponding method
        method_name = "receive_{}".format(message_type)
        try:
            getattr(self, method_name)(event.get("data"))

        except AttributeError:
            logger.error("Event of unknown type received '%s'", message_type)
Ejemplo n.º 7
0
    def send_request_raw(self,
                         method,
                         endpoint,
                         *args,
                         message_on_error="",
                         function_on_error=None,
                         **kwargs):
        """Generic method to send requests to the server.

        It takes care of errors and raises exceptions.

        Args:
            method (str): Name of the HTTP method to use.
            endpoint (str): Endpoint to send the request to. Will be added to
                the end of the server URL.
            message_on_error (str): Message to display in logs in case of
                error. It should describe what the request was about.
            function_on_error (function): Fuction called if the request is not
                successful, it will receive the response and must return an
                exception that will be raised. If not provided, a basic error
                management is done.
            Extra arguments are passed to requests' get/post/put/patch/delete
                methods.

        Returns:
            requests.models.Response: Response object.

        Raises:
            MethodError: If the method is not supported.
            ResponseRequestError: For any error when communicating with the server.
            ResponseInvalidError: If the response has an error code different
                to 2**.
        """
        # handle method function
        if not hasattr(requests, method):
            raise MethodError("Method {} not supported".format(method))

        send_method = getattr(requests, method)

        # handle message on error
        if not message_on_error:
            message_on_error = "Unable to request the server"

        # forge URL
        url = furl(self.server_url).add(path=endpoint).url
        logger.debug("Sending %s request to %s", method.upper(), url)

        try:
            # send request to the server
            response = send_method(url, *args, **kwargs)

        except requests.exceptions.RequestException as error:
            # handle connection error
            logger.error("%s, communication error", message_on_error)
            raise ResponseRequestError(
                "Error when communicating with the server: {}".format(
                    error)) from error

        # return here if the request was made without error
        if response.ok:
            return response

        # otherwise call custom error management function
        if function_on_error:
            raise function_on_error(response)

        # otherwise manage error generically
        logger.error(message_on_error)
        logger.debug("Error %i: %s", response.status_code,
                     truncate_message(response.text))

        raise ResponseInvalidError(
            "Error {} when communicationg with the server: {}".format(
                response.status_code, response.text))