Verified Commit a3f802e2 authored by Jakob Moser's avatar Jakob Moser
Browse files

Throw proper errors for invalid packages

parent f86ba3fb
Loading
Loading
Loading
Loading
+1 −1
Original line number Diff line number Diff line
class PacketDecodeError(Exception):
    pass  # TODO
    """Could not decode a given package into a particular message."""
+27 −1
Original line number Diff line number Diff line
@@ -4,6 +4,7 @@ from typing import Self
from uuid import UUID

from poolpay.model.messages.Message import Message
from poolpay.model.messages.PacketDecodeError import PacketDecodeError
from poolpay.wire.Packet import Packet


@@ -32,10 +33,35 @@ class UpdateBalanceMessage(Message):

        :raises PacketDecodeError: If the given packet can not be decoded as such a message.
        """
        try:
            expected_keys = {"uuid", "action", "person"}

            if packet.keys() != expected_keys:
                raise KeyError(
                    f"Expected exactly the keys {expected_keys}, but got: {set(packet.keys())}"
                )

            if not isinstance(packet["action"], dict):
                raise TypeError('packet["action"] must be a dictionary')

            if packet["action"].get("type") != "update_balance":
                raise ValueError('packet["action"]["type"] must be "update_balance"')

            if not isinstance(packet["action"].get("by_amount_cents"), int):
                raise TypeError('packet["action"]["by_amount_cents"] must be an int')

            if not isinstance(packet["person"], dict):
                raise TypeError('packet["person"] must be a dictionary')

            if not isinstance(packet["person"].get("full_name"), str):
                raise TypeError('packet["person"]["full_name"] must be a str')

        # TODO Throw error on fail
            return cls(
                uuid=UUID(packet["uuid"]),
                by_amount_cents=packet["action"]["by_amount_cents"],
                person_full_name=packet["person"]["full_name"],
            )
        except (TypeError, ValueError, KeyError) as e:
            raise PacketDecodeError(
                "Could not decode given packet as UpdateBalanceMessage"
            ) from e