示例#1
0
    def test_core_key_fail_by_incorrect_length(self):
        with self.assertRaises(ValueError) as cm:
            Key(b'+' * (Key.KEY_OCTETS + 1))
        the_exception = cm.exception
        self.assertEqual(the_exception.args[0],
                         "plain_key length is 33, it must be 32.")

        with self.assertRaises(ValueError) as cm:
            Key(b'-' * (Key.KEY_OCTETS - 1))
        the_exception = cm.exception
        self.assertEqual(the_exception.args[0],
                         "plain_key length is 31, it must be 32.")
示例#2
0
    def __init__(self, host=None, port=None):
        '''\
        node を初期化する。
        '''
        threading.Thread.__init__(self)
        self._last_moment = threading.Event()

        self.udp_sock = None
        self.udp_ip = (host, port)
        self.make_udpip()

        self._status = {}
        self.key = Key()
示例#3
0
    def test_core_key_fail_by_not_bytes(self):
        with self.assertRaises(ValueError) as cm:
            Key('0' * Key.KEY_OCTETS)
        the_exception = cm.exception
        self.assertEqual(
            the_exception.args[0],
            "plain_key must be bytes object but it is <class 'str'> object")

        with self.assertRaises(ValueError) as cm:
            Key(32 * Key.KEY_OCTETS)
        the_exception = cm.exception
        self.assertEqual(
            the_exception.args[0],
            "plain_key must be bytes object but it is <class 'int'> object")
示例#4
0
    def test_core_key_key_to_int(self):
        expected_int = 0
        for i in range(Key.KEY_OCTETS):
            expected_int <<= 8
            expected_int += 0x31
        plain_key = b'\x31' * Key.KEY_OCTETS

        self.assertEqual(Key.key_to_int(plain_key), expected_int)
示例#5
0
    def test_core_key_scale_rad_to_math_rad(self):
        scale_rads = (0.0 * pi, 0.5 * pi, 1.0 * pi, 1.0 * pi, 1.5 * pi,
                      1.999 * pi, 2.0 * pi)
        math_rads = (1 / 2 * pi, 0.0, 3 / 2 * pi, 3 / 2 * pi, pi,
                     1.001 / 2 * pi, 0.5 * pi)
        expected_rads = math_rads

        for scale_rad, expected_rad in zip(scale_rads, expected_rads):
            rad = Key.scale_rad_to_math_rad(scale_rad)
            self.assertAlmostEqual(rad, expected_rad, 2)
示例#6
0
    def test_core_key_key_to_scale_rad(self):
        plain_hex = b'\x00' + b'\x00' * (Key.KEY_OCTETS - 1)
        scale_rad = Key.key_to_scale_rad(plain_hex)
        self.assertEqual(scale_rad, 0.0 * 2.0 * pi)

        plain_hex = b'\x40' + b'\x00' * (Key.KEY_OCTETS - 1)
        scale_rad = Key.key_to_scale_rad(plain_hex)
        self.assertEqual(scale_rad, 0.25 * 2.0 * pi)

        plain_hex = b'\x80' + b'\x00' * (Key.KEY_OCTETS - 1)
        scale_rad = Key.key_to_scale_rad(plain_hex)
        self.assertEqual(scale_rad, 0.50 * 2.0 * pi)

        plain_hex = b'\xc0' + b'\x00' * (Key.KEY_OCTETS - 1)
        scale_rad = Key.key_to_scale_rad(plain_hex)
        self.assertEqual(scale_rad, 0.75 * 2.0 * pi)

        plain_hex = b'\xff' * Key.KEY_OCTETS
        scale_rad = Key.key_to_scale_rad(plain_hex)
        self.assertAlmostEqual(scale_rad, 1.999 * pi, 2)
示例#7
0
    def test_core_key_get_rxy(self):
        # key increases from 0x000..000 to 0xfff..fff.
        #
        # oclock turns clock wise.
        # key is on oclock.
        #
        # Therefore key share direction of movement and origin with oclock.
        #
        # This means that key start at zero oclock to at twelve oclock
        # like turning a oclock.
        #
        # PAY ATTENTION TO BELOW.
        #
        # key and clock combine radius.
        # This means that radius move pi/2, 0, 3*pi/2, pi to pi/2.
        #
        # I'll show you above means with below asserts.

        for name, expected_int_rxy in CoreKeyTests.AROUND_THE_CLOCK.items():
            expected_int, expected_rxy = expected_int_rxy

            an_hex = name.replace('key0x', '')
            plain_hex = an_hex + '0' * (Key.KEY_HEXES - 1)
            plain_key = b''
            for hh in re.findall('..', plain_hex):
                octet = int(hh, 16)
                byte = int.to_bytes(octet, 1, 'big')
                plain_key += byte

        # print('plain_key =', plain_key)
        # print('len(plain_key) =', len(plain_key))
            ko = Key(plain_key)
            #  ko means key object.
            # kos means key octets.
            CoreKeyTests.assert_key_initance(self, ko)

            self.assertEqual(int(ko), expected_int)
            for rxy, expected_value in zip(ko.get_rxy(), expected_rxy):
                self.assertAlmostEqual(rxy, expected_value, 3)
示例#8
0
    def __init__(self, **kwargs):
        '''\
        simulator 用 node を初期化する。
        '''

        self.office_addr = (kwargs.get('host', None), kwargs.get('port', None))
        super().__init__(*self.office_addr)

        for attr, value in kwargs.items():
            if attr in ('host', 'port'):
                continue
            setattr(self, attr, value)

        self.key = Key()
        self.status = 'active'

        self.nodes = []
        self.im_ready = threading.Event()
        self.office_door = threading.Lock()
        self.office_addr_assigned = threading.Event()
        self.master_hand_path = get_master_hand_path(SIMULATION_DIR,
                                                     self.start_up_orig)
示例#9
0
    def test_core_key_convert(self):
        octets = b''
        for i in range(Key.KEY_OCTETS):
            octets += int.to_bytes(i * 8, 1, 'big')
        ko = Key(octets)
        CoreKeyTests.assert_key_initance(self, ko)

        self.assertEqual(
            int(ko),
            0x0008101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f0f8)
        self.assertEqual(
            str(ko),
            '0x0008101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f0f8'
        )
示例#10
0
    def test_core_key_key_to_rxy(self):
        for name, expected_int_rxy in CoreKeyTests.AROUND_THE_CLOCK.items():
            expected_int, expected_rxy = expected_int_rxy

            an_hex = name.replace('key0x', '')
            plain_hex = an_hex + '0' * (Key.KEY_HEXES - 1)
            plain_key = b''
            for hh in re.findall('..', plain_hex):
                octet = int(hh, 16)
                byte = int.to_bytes(octet, 1, 'big')
                plain_key += byte

            rxy = Key.key_to_rxy(plain_key)

            self.assertIsInstance(rxy, tuple)
            for rxy, expected_value in zip(rxy, expected_rxy):
                self.assertAlmostEqual(rxy, expected_value, 3)
示例#11
0
    def test_core_key_update(self):
        k = Key()
        CoreKeyTests.assert_key_initance(self, k)

        key0 = k.key
        k.update()
        CoreKeyTests.assert_key_initance(self, k)
        self.assertNotEqual(k.key, key0)

        key_rand = os.urandom(Key.KEY_OCTETS)
        k.update(key_rand)
        CoreKeyTests.assert_key_initance(self, k)
        self.assertEqual(k.key, key_rand)
示例#12
0
    def test_core_key_richcmp_simple(self):
        keyffff = Key(b'\xff' * Key.KEY_OCTETS)
        keyfffe = Key(b'\xff' * (Key.KEY_OCTETS - 1) + b'\xfe')
        key7fff = Key(b'\x7f' + b'\xff' * (Key.KEY_OCTETS - 1))
        key7ffe = Key(b'\x7f' + b'\xff' * (Key.KEY_OCTETS - 2) + b'\xfe')

        key0000 = Key(b'\x00' * Key.KEY_OCTETS)
        key0001 = Key(b'\x00' * (Key.KEY_OCTETS - 1) + b'\x01')
        key8000 = Key(b'\x80' + b'\x00' * (Key.KEY_OCTETS - 1))
        key8001 = Key(b'\x80' + b'\x00' * (Key.KEY_OCTETS - 2) + b'\x01')

        # Greater means Red, Less means Green, Eq means White

        self.assertEqual(key0000, key0000)  # eq     White
        self.assertGreater(key0001, key0000)  # + 1    Red
        self.assertGreater(key7fff, key0000)  # + 7fff Red
        self.assertLess(key8000, key0000)  # + 8000 Green
        self.assertLess(keyffff, key0000)  # - 1    Green

        self.assertEqual(key7fff, key7fff)  # eq
        self.assertGreater(key8000, key7fff)  # + 1
        self.assertGreater(keyfffe, key7fff)  # + 7fff
        self.assertLess(keyffff, key7fff)  # + 8000
        self.assertLess(key7ffe, key7fff)  # -1
        self.assertLess(key0000, key7fff)  # zero

        self.assertEqual(key8000, key8000)  # eq
        self.assertGreater(key8001, key8000)  # + 1
        self.assertGreater(keyffff, key8000)  # + 7fff
        self.assertLess(key0000, key8000)  # + 8000
        self.assertLess(key7fff, key8000)  # -1

        self.assertEqual(keyffff, keyffff)  # eq
        self.assertGreater(key0000, keyffff)  # + 1
        self.assertGreater(key7ffe, keyffff)  # + 7fff
        self.assertLess(key7fff, keyffff)  # + 8000
        self.assertLess(keyfffe, keyffff)  # -1
示例#13
0
class Node(node.Node):

    ATTRS = ('id', 'office_addr', 'key', 'status')

    @classmethod
    def make_node_assets(cls):
        byebye_nodes = threading.Event()
        start_up_orig = make_start_up_orig()
        _queue_darkness = queue.Queue()

        d = {
            'byebye_nodes': byebye_nodes,
            'start_up_orig': start_up_orig,
            '_queue_darkness': _queue_darkness,
        }

        return d

    def __init__(self, **kwargs):
        '''\
        simulator 用 node を初期化する。
        '''

        self.office_addr = (kwargs.get('host', None), kwargs.get('port', None))
        super().__init__(*self.office_addr)

        for attr, value in kwargs.items():
            if attr in ('host', 'port'):
                continue
            setattr(self, attr, value)

        self.key = Key()
        self.status = 'active'

        self.nodes = []
        self.im_ready = threading.Event()
        self.office_door = threading.Lock()
        self.office_addr_assigned = threading.Event()
        self.master_hand_path = get_master_hand_path(SIMULATION_DIR,
                                                     self.start_up_orig)

    def run(self):
        self._open_office()
        et = self.get_elapsed_time()
        d_attrs = self.get_attrs()
        self.put_on_darkness(d_attrs, et)

        self._steal_master_palm()
        self.regist()

        logger.info(f"byebye_nodes.wait()")
        self.byebye_nodes.wait()
        logger.info(f"release_clients()")
        self.release_clients()  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        logger.info(f"node_udp_office.shutdown()")
        self.node_udp_office.shutdown()  # close node office !!!!!!!!!!!!!!!!!!
        self.node_open_office.join()  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

        logger.info(f"byebye_nodes leave !")

    def _open_office(self):
        logger.info(f"")
        node_open_office = NodeOpenOffice(self)
        self.node_open_office = node_open_office
        logger.info(f"{self}.open_office(), node_open_office.start()")
        node_open_office.start()
        # wait a minute
        # to set node_open_office instance
        # to node instance
        # in NodeOpenOffice.run()
        logger.info(f"node_open_office.wait()")
        node_open_office.in_serve_forever.wait()
        self.office_addr_assigned.set()
        logger.info(f"node_open_office={node_open_office}")
        # node.office_addr が決定している。
        return node_open_office

    def get_info(self):
        return f"{':'.join(map(str, self.office_addr))}:{self.key}" + '\n'

    def regist(self):
        logger.info(f"regist(), master_hand_path={self.master_hand_path}")
        os.makedirs(os.path.dirname(self.master_hand_path), exist_ok=True)
        with open(self.master_hand_path, 'a') as master:
            print(self.get_info(), end='', file=master)

    # msg = 'I am Node.'
    # recver_addr = ('localhost', 222)
    # self.sock.sendto(msg, recver_addr)
    # recved_msg, who = self.sock.recvfrom(1024)
        self.im_ready.set()

    def _steal_master_palm(self):
        if not os.path.isfile(self.master_hand_path):
            logger.info(
                f"not found 'master_hand_path={self.master_hand_path}'")
            return None

        logger.info(f"found 'master_hand_path={self.master_hand_path}'")
        with open(self.master_hand_path) as master_palm:
            node_lines = master_palm.read()
        return node_lines

    def _force_shutdown(self):
        self.disappear()

    def set_attrs(self, d={}):
        attrs = d
        for attr, value in attrs.items():
            setattr(self, attr, value)

    def get_attrs(self, keys=()):
        if not keys:
            keys = self.ATTRS
        d = {}
        for key in keys:
            d[key] = getattr(self, key)
        return d

    def put_on_darkness(self, obj, et):
        pds = pickle.dumps(obj)
        tup = (et, pds)
        self._queue_darkness.put(tup)

    def get_elapsed_time(self):
        et = elapsed_time(self.start_up_orig)
        return et

    def appear(self):
        super().appear()

    def disappear(self):
        super().disappear()

    def release_clients(self):
        logger.info(f"{self} clients={self.node_udp_office.clients}")
        for node_office_client in self.node_udp_office.clients:
            node_office_client.byebye()

    def __str__(self):
        return 'Node(id={}, addr={})'.format(self.id, self.udp_ip)

    def update(self, k=b''):
        self.key.update(k)
示例#14
0
    def test_core_key_richcmp_boundary(self):
        key0000 = Key(b'\x00' * Key.KEY_OCTETS)
        keyffff = Key(b'\xff' * Key.KEY_OCTETS)

        key1fff = Key(b'\x1f' + b'\xff' * (Key.KEY_OCTETS - 1))
        key2000 = Key(b'\x20' + b'\x00' * (Key.KEY_OCTETS - 1))
        key2001 = Key(b'\x20' + b'\x00' * (Key.KEY_OCTETS - 2) + b'\x01')

        key5fff = Key(b'\x5f' + b'\xff' * (Key.KEY_OCTETS - 1))
        key6000 = Key(b'\x60' + b'\x00' * (Key.KEY_OCTETS - 1))
        key6001 = Key(b'\x60' + b'\x00' * (Key.KEY_OCTETS - 2) + b'\x01')

        key9fff = Key(b'\x9f' + b'\xff' * (Key.KEY_OCTETS - 1))
        keya000 = Key(b'\xa0' + b'\x00' * (Key.KEY_OCTETS - 1))
        keya001 = Key(b'\xa0' + b'\x00' * (Key.KEY_OCTETS - 2) + b'\x01')

        keydfff = Key(b'\xdf' + b'\xff' * (Key.KEY_OCTETS - 1))
        keye000 = Key(b'\xe0' + b'\x00' * (Key.KEY_OCTETS - 1))
        keye001 = Key(b'\xe0' + b'\x00' * (Key.KEY_OCTETS - 2) + b'\x01')

        # Greater means Red, Less means Green, Eq means White

        self.assertEqual(key2000, key2000)  # eq     White
        self.assertGreater(key2001, key2000)  # + 1    Red
        self.assertGreater(key9fff, key2000)  # + 7fff Red
        self.assertLess(keya000, key2000)  # + 8000 Green
        self.assertLess(key1fff, key2000)  # - 1    Green
        self.assertLess(keyffff, key2000)  # end    Green
        self.assertLess(key0000, key2000)  # zero   Green

        self.assertEqual(key6000, key6000)  # eq     White
        self.assertGreater(key6001, key6000)  # + 1    Red
        self.assertGreater(keydfff, key6000)  # + 7fff Red
        self.assertLess(keye000, key6000)  # + 8000 Green
        self.assertLess(key5fff, key6000)  # - 1    Green
        self.assertLess(keyffff, key6000)  # end    Green
        self.assertLess(key0000, key6000)  # zero   Green

        self.assertEqual(keya000, keya000)  # eq     White
        self.assertGreater(keya001, keya000)  # + 1    Red
        self.assertGreater(key1fff, keya000)  # + 7fff Red
        self.assertLess(key2000, keya000)  # + 8000 Green
        self.assertLess(key9fff, keya000)  # - 1    Green
        self.assertGreater(keyffff, keya000)  # end    Red
        self.assertGreater(key0000, keya000)  # zero   Red

        self.assertEqual(keye000, keye000)  # eq     White
        self.assertGreater(keye001, keye000)  # + 1    Red
        self.assertGreater(key5fff, keye000)  # + 7fff Red
        self.assertLess(key6000, keye000)  # + 8000 Green
        self.assertLess(keydfff, keye000)  # - 1    Green
        self.assertGreater(keyffff, keye000)  # end    Red
        self.assertGreater(key0000, keye000)  # zero   Red
示例#15
0
 def test_core_key_init_by_regular(self):
     k = Key(b'o' * Key.KEY_OCTETS)
     CoreKeyTests.assert_key_initance(self, k)
     self.assertEqual(k.key, b'o' * Key.KEY_OCTETS)
示例#16
0
    def test_core_key_keycmp_boundary(self):
        key0000 = b'\x00' * Key.KEY_OCTETS
        keyffff = b'\xff' * Key.KEY_OCTETS

        key1fff = b'\x1f' + b'\xff' * (Key.KEY_OCTETS - 1)
        key2000 = b'\x20' + b'\x00' * (Key.KEY_OCTETS - 1)
        key2001 = b'\x20' + b'\x00' * (Key.KEY_OCTETS - 2) + b'\x01'

        key5fff = b'\x5f' + b'\xff' * (Key.KEY_OCTETS - 1)
        key6000 = b'\x60' + b'\x00' * (Key.KEY_OCTETS - 1)
        key6001 = b'\x60' + b'\x00' * (Key.KEY_OCTETS - 2) + b'\x01'

        key9fff = b'\x9f' + b'\xff' * (Key.KEY_OCTETS - 1)
        keya000 = b'\xa0' + b'\x00' * (Key.KEY_OCTETS - 1)
        keya001 = b'\xa0' + b'\x00' * (Key.KEY_OCTETS - 2) + b'\x01'

        keydfff = b'\xdf' + b'\xff' * (Key.KEY_OCTETS - 1)
        keye000 = b'\xe0' + b'\x00' * (Key.KEY_OCTETS - 1)
        keye001 = b'\xe0' + b'\x00' * (Key.KEY_OCTETS - 2) + b'\x01'

        self.assertEqual(Key.KEY_OCTETS, 32)
        self.assertEqual(len(key0000), Key.KEY_OCTETS)
        self.assertEqual(len(keyffff), Key.KEY_OCTETS)
        self.assertEqual(len(key1fff), Key.KEY_OCTETS)
        self.assertEqual(len(key2000), Key.KEY_OCTETS)
        self.assertEqual(len(key2001), Key.KEY_OCTETS)
        self.assertEqual(len(key5fff), Key.KEY_OCTETS)
        self.assertEqual(len(key6000), Key.KEY_OCTETS)
        self.assertEqual(len(key6001), Key.KEY_OCTETS)
        self.assertEqual(len(key9fff), Key.KEY_OCTETS)
        self.assertEqual(len(keya000), Key.KEY_OCTETS)
        self.assertEqual(len(keya001), Key.KEY_OCTETS)
        self.assertEqual(len(keydfff), Key.KEY_OCTETS)
        self.assertEqual(len(keye000), Key.KEY_OCTETS)
        self.assertEqual(len(keye001), Key.KEY_OCTETS)

        # Greater means Red, Less means Green, Eq means White

        self.assertEqual(Key.keycmp(key2000, key2000), 0)  # eq     White
        self.assertGreater(Key.keycmp(key2001, key2000), 0)  # + 1    Red
        self.assertGreater(Key.keycmp(key9fff, key2000), 0)  # + 7fff Red
        self.assertLess(Key.keycmp(keya000, key2000), 0)  # + 8000 Green
        self.assertLess(Key.keycmp(key1fff, key2000), 0)  # - 1    Green
        self.assertLess(Key.keycmp(keyffff, key2000), 0)  # end    Green
        self.assertLess(Key.keycmp(key0000, key2000), 0)  # zero   Green

        self.assertEqual(Key.keycmp(key6000, key6000), 0)  # eq     White
        self.assertGreater(Key.keycmp(key6001, key6000), 0)  # + 1    Red
        self.assertGreater(Key.keycmp(keydfff, key6000), 0)  # + 7fff Red
        self.assertLess(Key.keycmp(keye000, key6000), 0)  # + 8000 Green
        self.assertLess(Key.keycmp(key5fff, key6000), 0)  # - 1    Green
        self.assertLess(Key.keycmp(keyffff, key6000), 0)  # end    Green
        self.assertLess(Key.keycmp(key0000, key6000), 0)  # zero   Green

        self.assertEqual(Key.keycmp(keya000, keya000), 0)  # eq     White
        self.assertGreater(Key.keycmp(keya001, keya000), 0)  # + 1    Red
        self.assertGreater(Key.keycmp(key1fff, keya000), 0)  # + 7fff Red
        self.assertLess(Key.keycmp(key2000, keya000), 0)  # + 8000 Green
        self.assertLess(Key.keycmp(key9fff, keya000), 0)  # - 1    Green
        self.assertGreater(Key.keycmp(keyffff, keya000), 0)  # end    Red
        self.assertGreater(Key.keycmp(key0000, keya000), 0)  # zero   Red

        self.assertEqual(Key.keycmp(keye000, keye000), 0)  # eq     White
        self.assertGreater(Key.keycmp(keye001, keye000), 0)  # + 1    Red
        self.assertGreater(Key.keycmp(key5fff, keye000), 0)  # + 7fff Red
        self.assertLess(Key.keycmp(key6000, keye000), 0)  # + 8000 Green
        self.assertLess(Key.keycmp(keydfff, keye000), 0)  # - 1    Green
        self.assertGreater(Key.keycmp(keyffff, keye000), 0)  # end    Red
        self.assertGreater(Key.keycmp(key0000, keye000), 0)  # zero   Red
示例#17
0
    def test_core_key_keycmp_simple(self):
        # b'\xff' * 16
        # int.to_bytes(255, 1, 'big')
        # int.to_bytes(0, 1, 'big')
        keyffff = b'\xff' * Key.KEY_OCTETS
        keyfffe = b'\xff' * (Key.KEY_OCTETS - 1) + b'\xfe'
        key7fff = b'\x7f' + b'\xff' * (Key.KEY_OCTETS - 1)
        key7ffe = b'\x7f' + b'\xff' * (Key.KEY_OCTETS - 2) + b'\xfe'

        key0000 = b'\x00' * Key.KEY_OCTETS
        key0001 = b'\x00' * (Key.KEY_OCTETS - 1) + b'\x01'
        key8000 = b'\x80' + b'\x00' * (Key.KEY_OCTETS - 1)
        key8001 = b'\x80' + b'\x00' * (Key.KEY_OCTETS - 2) + b'\x01'

        self.assertEqual(Key.KEY_OCTETS, 32)
        self.assertEqual(len(keyffff), Key.KEY_OCTETS)
        self.assertEqual(len(keyfffe), Key.KEY_OCTETS)
        self.assertEqual(len(key7fff), Key.KEY_OCTETS)
        self.assertEqual(len(key7ffe), Key.KEY_OCTETS)
        self.assertEqual(len(key0000), Key.KEY_OCTETS)
        self.assertEqual(len(key0001), Key.KEY_OCTETS)
        self.assertEqual(len(key8000), Key.KEY_OCTETS)
        self.assertEqual(len(key8001), Key.KEY_OCTETS)

        # Greater means Red, Less means Green, Eq means White

        self.assertEqual(Key.keycmp(key0000, key0000), 0)  # eq     White
        self.assertGreater(Key.keycmp(key0001, key0000), 0)  # + 1    Red
        self.assertGreater(Key.keycmp(key7fff, key0000), 0)  # + 7fff Red
        self.assertLess(Key.keycmp(key8000, key0000), 0)  # + 8000 Green
        self.assertLess(Key.keycmp(keyffff, key0000), 0)  # - 1    Green

        self.assertEqual(Key.keycmp(key7fff, key7fff), 0)  # eq
        self.assertGreater(Key.keycmp(key8000, key7fff), 0)  # + 1
        self.assertGreater(Key.keycmp(keyfffe, key7fff), 0)  # + 7fff
        self.assertLess(Key.keycmp(keyffff, key7fff), 0)  # + 8000
        self.assertLess(Key.keycmp(key7ffe, key7fff), 0)  # -1
        self.assertLess(Key.keycmp(key0000, key7fff), 0)  # zero

        self.assertEqual(Key.keycmp(key8000, key8000), 0)  # eq
        self.assertGreater(Key.keycmp(key8001, key8000), 0)  # + 1
        self.assertGreater(Key.keycmp(keyffff, key8000), 0)  # + 7fff
        self.assertLess(Key.keycmp(key0000, key8000), 0)  # + 8000
        self.assertLess(Key.keycmp(key7fff, key8000), 0)  # -1

        self.assertEqual(Key.keycmp(keyffff, keyffff), 0)  # eq
        self.assertGreater(Key.keycmp(key0000, keyffff), 0)  # + 1
        self.assertGreater(Key.keycmp(key7ffe, keyffff), 0)  # + 7fff
        self.assertLess(Key.keycmp(key7fff, keyffff), 0)  # + 8000
        self.assertLess(Key.keycmp(keyfffe, keyffff), 0)  # -1
示例#18
0
 def test_core_key_init_by_empty(self):
     k = Key()
     CoreKeyTests.assert_key_initance(self, k)
示例#19
0
    def test_core_key_plain_hex_to_plain_key(self):
        plain_hex = '31' * Key.KEY_OCTETS
        expected = b'\x31' * Key.KEY_OCTETS

        plain_key = Key.plain_hex_to_plain_key(plain_hex)
        self.assertEqual(plain_key, expected)
示例#20
0
class Node(threading.Thread):
    '''Node class'''

    PACKET_SIZE = 2048

    # Node()        <=> node.release()
    # node.appear() <=> node.disappear()

    def __init__(self, host=None, port=None):
        '''\
        node を初期化する。
        '''
        threading.Thread.__init__(self)
        self._last_moment = threading.Event()

        self.udp_sock = None
        self.udp_ip = (host, port)
        self.make_udpip()

        self._status = {}
        self.key = Key()

    def release(self):
        if self.udp_sock:
            self.udp_sock.close()
        # self.udp_sock = None
        # ここで、close() する、udp_sock は、
        # bind() に成功し、有効に利用されていたudp_sockなのだから、
        # udp_sock に None を代入しない。

    def not_ready(self):
        return not all(self.udp_ip)

    def make_udpip(self, host=None, port=None):
        if not hasattr(self, 'udp_ip'):
            self.udp_ip = (None, None)

        if host is not None:
            self.udp_ip = (host, self.udp_ip[1])
        if port is not None:
            self.udp_ip = (self.udp_ip[0], port)

        if self.not_ready():
            return

        self.udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        try:
            self.udp_sock.bind(self.udp_ip)
        except socket.error as raiz:
            self.udp_sock.close()
            self.udp_sock = None
            logger.error('cannot bind({}). reason={}'.format(
                self.udp_ip, raiz.args))

            # print('raiz.args =', raiz.args)
            if raiz.args == (98, 'Address already in use'):
                logger.error(
                    '指定した host(={}), port(={}) は使用済みでした。'.format(*self.udp_ip))
            elif raiz.args == (13, 'Permission denied'):
                pass
        except OverflowError as raiz:
            # getsockaddrarg: port must be 0-65535.
            print('raiz.args =', raiz.args)
            self.udp_sock.close()
            self.udp_sock = None
            logger.error('cannot bind({}). reason={}'.format(
                self.udp_ip, raiz.args))

    def run(self):
        self._last_moment.wait()

    def appear(self):
        self.start()

    def disappear(self):
        '''別れ, envoi'''
        self.release()
        if hasattr(self, '_last_moment'):
            self._last_moment.set()
        self.join()

    def get_status(self, type_='dict'):
        'node の各種情報を表示。'
        self._status['host'] = self.udp_ip[0]
        self._status['port'] = self.udp_ip[1]
        self._status['key'] = self.key.value()
        return self._status