[bencode] Fix unhandled TypeError with string

Passing a non-bencoded dict to bdecode resulted in an unhandled
TypeError.

- Catch TypeError in decode_func.
- Add bdecode tests.
- Replace KeyError and IndexError with base LookupError.
This commit is contained in:
Calum Lind 2019-05-18 11:12:01 +01:00
parent b961e11df6
commit 09cfd9b89e
2 changed files with 11 additions and 1 deletions

View File

@ -84,7 +84,7 @@ decode_func[b'9'] = decode_string
def bdecode(x):
try:
r, __ = decode_func[x[0:1]](x, 0)
except (IndexError, KeyError, ValueError):
except (LookupError, TypeError, ValueError):
raise BTFailure('Not a valid bencoded string')
else:
return r

View File

@ -21,4 +21,14 @@ class BencodeTestCase(unittest.TestCase):
bencode.bencode({b'info': metainfo})
def test_bencode_unicode_value(self):
self.assertEqual(bencode.bencode(b'abc'), b'3:abc')
self.assertEqual(bencode.bencode('abc'), b'3:abc')
def test_bdecode(self):
self.assertEqual(bencode.bdecode(b'3:dEf'), b'dEf')
with self.assertRaises(bencode.BTFailure):
bencode.bdecode('dEf')
with self.assertRaises(bencode.BTFailure):
bencode.bdecode(b'dEf')
with self.assertRaises(bencode.BTFailure):
bencode.bdecode({'dEf': 123})