def test_payload_build(self):
     type = PayloadType.UNK
     event = PayloadEvent.UNK
     data = "test_data"
     role = "test_role"
     p = Payload(data, event, type, role)
     x = build_payload(p.content())
     y = self.param_association(x, data, type, event, role)
     self.assertEqual(x.content(), y.content())
     print("Build: DICT :Passed")
     y = build_payload(json.dumps(x.content()))
     self.assertEqual(x.content(), y.content())
     print("Build: JSON :Passed")
     p = Payload(data, event, type)
     self.assertEqual(BLANK_FIELD, p.role)
     print("Build: Default Role :Passed")
    def data_handler(self, payload: Payload, delegation_event_whitelist=None):
        if delegation_event_whitelist is None:
            delegation_event_whitelist = []
        notify_all = payload.role == WILDCARD
        correct_payload = payload.role == ROLE
        is_request = payload.type in REQUEST_TYPES
        white_listed = payload.event in delegation_event_whitelist

        # 1. Determines if the payload is intended for the current unit
        if not correct_payload and is_request and not white_listed:

            # 2 If the current payload is NOT intended for the current unit
            #   it will be delegated, and hopefully send it to the appropriate
            #   unit.
            if IS_DELEGATOR and payload.role is not BLANK_FIELD:
                # 2.1 If delegation is enabled, it then gets the ip address of the intended
                #     unit and sends the payload, if the wildcard has been specified then all
                #     the units will be notified

                addresses = PiDiscovery.get_ip_addresses(payload.role)
                transactions = []
                res_payload = PayloadEventMessages.ADDRESS_NOT_FOUND.value
                for address in addresses:
                    client = LANClient(address, self.port, timeout=5, ignore_errors=True)
                    print("\t%s\n\t|\t\tRelaying -> %s:%s" % (print_payload(payload), address, self.port))
                    res_payload = client.send(payload)
                    transactions.append((res_payload.data, res_payload.event.name))

                if len(transactions) > 1:
                    payload.data = transactions
                    payload.type = PayloadType.RSP
                    return payload
                return res_payload

            else:
                # 2.2 If delegation is disabled, and the role can't be handled, then
                #     a error response will be sent telling the client 'Wrong Node'.
                if notify_all:
                    return self.process_payload(payload)
                return PayloadEventMessages.WRONG_NODE

        return self.process_payload(payload)