def test_bencode_decoder():
    """ test decoding capabilities of bencode module
    """
    assert decode(b'de') == {}
    assert decode(b'i-41e') == -41
    assert decode(b'd3:foo3:bare') == {b'foo': b'bar'}
    assert decode(b'd3:foo3:bar4:fooo4:bbare') == {
        b'foo': b'bar', b'fooo': b'bbar'}
    with pytest.raises(DecodeError) as exc:
        decode(b'i.123e')
    assert str(exc.value) == 'illegal digit in size'
    assert decode(b'le') == []
    assert decode(b'li1ei2ee') == [1, 2]
    assert decode(b'13:aaaaaaaaaaa\xc5\xbc') == b'aaaaaaaaaaa\xc5\xbc'
Beispiel #2
0
    def from_bytes(cls, packet_bytes):
        """Return a packet from a bytes string"""
        try:
            packet_data = bencode.decode(packet_bytes)
        except bencode.DecodeError as e:
            raise PacketFormatError('packet is badly formated ({!r})'.format(e))

        if not isinstance(packet_data, list):
            raise PacketFormatError('packet must be a list')
        packet_type = packet_data[0]
        if not isinstance(packet_type, int_types):
            raise PacketFormatError('first value must be an integer')
        packet_body = packet_data[1:]
        try:
            packet_cls = cls.registry[packet_type]
        except:
            raise UnknownPacketError("unknown packet type '{}'".format(packet_type))
        return packet_cls.from_body(packet_body)
Beispiel #3
0
 def on_message(self, app, data):
     """a WS message"""
     packet = bencode.decode(data)
     self.on_packet(packet)