2015-08-20 17:27:15 +02:00
|
|
|
#!/usr/bin/env python
|
|
|
|
#
|
|
|
|
# This library is free software, distributed under the terms of
|
|
|
|
# the GNU Lesser General Public License Version 3, or any later version.
|
|
|
|
# See the COPYING file included in this archive
|
|
|
|
|
2018-05-24 00:28:22 +02:00
|
|
|
from twisted.trial import unittest
|
2015-08-20 17:27:15 +02:00
|
|
|
import lbrynet.dht.encoding
|
|
|
|
|
2018-05-24 00:28:22 +02:00
|
|
|
|
2015-08-20 17:27:15 +02:00
|
|
|
class BencodeTest(unittest.TestCase):
|
|
|
|
""" Basic tests case for the Bencode implementation """
|
|
|
|
def setUp(self):
|
|
|
|
self.encoding = lbrynet.dht.encoding.Bencode()
|
|
|
|
# Thanks goes to wikipedia for the initial test cases ;-)
|
2018-07-18 04:00:34 +02:00
|
|
|
self.cases = ((42, b'i42e'),
|
|
|
|
(b'spam', b'4:spam'),
|
|
|
|
([b'spam', 42], b'l4:spami42ee'),
|
|
|
|
({b'foo': 42, b'bar': b'spam'}, b'd3:bar4:spam3:fooi42ee'),
|
2015-08-20 17:27:15 +02:00
|
|
|
# ...and now the "real life" tests
|
2018-07-18 04:00:34 +02:00
|
|
|
([[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'))
|
2017-09-29 12:44:22 +02:00
|
|
|
# The following test cases are "bad"; i.e. sending rubbish into the decoder to test
|
|
|
|
# what exceptions get thrown
|
2018-07-18 04:00:34 +02:00
|
|
|
self.badDecoderCases = (b'abcdefghijklmnopqrstuvwxyz',
|
|
|
|
b'')
|
2017-09-29 12:44:22 +02:00
|
|
|
|
2015-08-20 17:27:15 +02:00
|
|
|
def testEncoder(self):
|
|
|
|
""" Tests the bencode encoder """
|
|
|
|
for value, encodedValue in self.cases:
|
|
|
|
result = self.encoding.encode(value)
|
2018-07-21 22:55:43 +02:00
|
|
|
self.assertEqual(
|
2017-09-29 12:44:22 +02:00
|
|
|
result, encodedValue,
|
|
|
|
'Value "%s" not correctly encoded! Expected "%s", got "%s"' %
|
|
|
|
(value, encodedValue, result))
|
|
|
|
|
2015-08-20 17:27:15 +02:00
|
|
|
def testDecoder(self):
|
|
|
|
""" Tests the bencode decoder """
|
|
|
|
for value, encodedValue in self.cases:
|
|
|
|
result = self.encoding.decode(encodedValue)
|
2018-07-21 22:55:43 +02:00
|
|
|
self.assertEqual(
|
2017-09-29 12:44:22 +02:00
|
|
|
result, value,
|
|
|
|
'Value "%s" not correctly decoded! Expected "%s", got "%s"' %
|
|
|
|
(encodedValue, value, result))
|
2015-08-20 17:27:15 +02:00
|
|
|
for encodedValue in self.badDecoderCases:
|
2018-07-21 22:55:43 +02:00
|
|
|
self.assertRaises(
|
2017-09-29 12:44:22 +02:00
|
|
|
lbrynet.dht.encoding.DecodeError, self.encoding.decode, encodedValue)
|