def test_bytes(self): self.assertEqual(_bencode(b''), b'0:') self.assertEqual(_bencode(b'spam'), b'4:spam') self.assertEqual(_bencode(b'4:spam'), b'6:4:spam') self.assertEqual(_bencode(bytearray(b'spam')), b'4:spam') self.assertEqual(bdecode(b'0:', True), b'') self.assertEqual(bdecode(b'4:spam', True), b'spam') self.assertEqual(bdecode(b'6:4:spam', True), b'4:spam')
def test_mixed(self): self.assertEqual( _bencode([[b'abc', b'127.0.0.1', 1919], [b'def', b'127.0.0.1', 1921]]), b'll3:abc9:127.0.0.1i1919eel3:def9:127.0.0.1i1921eee') self.assertEqual( bdecode(b'll3:abc9:127.0.0.1i1919eel3:def9:127.0.0.1i1921eee', True), [[b'abc', b'127.0.0.1', 1919], [b'def', b'127.0.0.1', 1921]])
def test_str_or_int_keys(self): datagram = decode_datagram(_bencode({ b'0': 0, b'1': b'\n\xbc\xb5&\x9dl\xfc\x1e\x87\xa0\x8e\x92\x0b\xf3\x9f\xe9\xdf\x8e\x92\xfc', b'2': b'111111111111111111111111111111111111111111111111', b'3': b'ping', b'4': [{b'protocolVersion': 1}], b'5': b'should not error' })) self.assertEqual(datagram.packet_type, REQUEST_TYPE) self.assertEqual(b'ping', datagram.method)
def test_optional_field_backwards_compatible(self): datagram = decode_datagram(_bencode({ 0: 0, 1: b'\n\xbc\xb5&\x9dl\xfc\x1e\x87\xa0\x8e\x92\x0b\xf3\x9f\xe9\xdf\x8e\x92\xfc', 2: b'111111111111111111111111111111111111111111111111', 3: b'ping', 4: [{b'protocolVersion': 1}], 5: b'should not error' })) self.assertEqual(datagram.packet_type, REQUEST_TYPE) self.assertEqual(b'ping', datagram.method)
def test_invalid_datagram_type(self): serialized = b'di0ei5ei1e20:11111111111111111111i2e48:11111111111111111111' \ b'1111111111111111111111111111i3e13:FakeErrorTypei4e9:more infoe' self.assertRaises(ValueError, decode_datagram, serialized) self.assertRaises(DecodeError, decode_datagram, _bencode([1, 2, 3, 4]))
def test_list(self): self.assertEqual(_bencode([b'spam', 42]), b'l4:spami42ee') self.assertEqual(bdecode(b'l4:spami42ee', True), [b'spam', 42])
def test_string(self): self.assertEqual(_bencode(''), b'0:') self.assertEqual(_bencode('spam'), b'4:spam') self.assertEqual(_bencode('4:spam'), b'6:4:spam')
def test_integer(self): self.assertEqual(_bencode(42), b'i42e') self.assertEqual(bdecode(b'i42e', True), 42)