[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[tor-commits] [stem/master] Provide a nicer error message for packing negative numbers with unsigned types



commit 2fa32642d4b734821746d2488334ef68c38ad634
Author: Dave Rolek <dmr-x@xxxxxxxxxx>
Date:   Mon Aug 6 21:45:26 2018 +0000

    Provide a nicer error message for packing negative numbers with unsigned types
---
 stem/client/datatype.py  | 3 +++
 test/unit/client/size.py | 9 +++++++++
 2 files changed, 12 insertions(+)

diff --git a/stem/client/datatype.py b/stem/client/datatype.py
index 5ca4e820..e19adfb1 100644
--- a/stem/client/datatype.py
+++ b/stem/client/datatype.py
@@ -349,6 +349,7 @@ class Size(Field):
     self.name = name
     self.size = size
     self.format = pack_format
+    self.unsigned = pack_format.isupper()
 
   @staticmethod
   def pop(packed):
@@ -357,6 +358,8 @@ class Size(Field):
   def pack(self, content):
     if not stem.util._is_int(content):
       raise ValueError('Size.pack encodes an integer, but was a %s' % type(content).__name__)
+    if self.unsigned and content < 0:
+      raise ValueError('A %s field cannot pack negative values, but %i was tried' % (self.name, content))
 
     packed = struct.pack(self.format, content)
 
diff --git a/test/unit/client/size.py b/test/unit/client/size.py
index eebe3619..3d7d796f 100644
--- a/test/unit/client/size.py
+++ b/test/unit/client/size.py
@@ -7,17 +7,22 @@ import unittest
 
 from stem.client.datatype import Size
 
+SIGNED_CHAR = Size('SIGNED_CHAR', 1, '!b')
+
 
 class TestSize(unittest.TestCase):
   def test_attributes(self):
     self.assertEqual('CHAR', Size.CHAR.name)
     self.assertEqual('!B', Size.CHAR.format)
+    self.assertEqual(True, Size.CHAR.unsigned)
 
     self.assertEqual(1, Size.CHAR.size)
     self.assertEqual(2, Size.SHORT.size)
     self.assertEqual(4, Size.LONG.size)
     self.assertEqual(8, Size.LONG_LONG.size)
 
+    self.assertEqual(False, SIGNED_CHAR.unsigned)
+
   def test_pack(self):
     self.assertEqual(b'\x12', Size.CHAR.pack(18))
     self.assertEqual(b'\x00\x12', Size.SHORT.pack(18))
@@ -26,9 +31,13 @@ class TestSize(unittest.TestCase):
 
     self.assertRaisesWith(ValueError, 'Size.pack encodes an integer, but was a str', Size.CHAR.pack, 'hi')
 
+    self.assertRaisesWith(ValueError, 'A CHAR field cannot pack negative values, but -1 was tried', Size.CHAR.pack, -1)
+
     bad_size = Size('BAD_SIZE', 1, '!H')
     self.assertRaisesRegexp(ValueError, re.escape("'\\x00\\x12' is the wrong size for a BAD_SIZE field"), bad_size.pack, 18)
 
+    self.assertEqual(b'\xFF', SIGNED_CHAR.pack(-1))
+
   def test_unpack(self):
     self.assertEqual(18, Size.CHAR.unpack(b'\x12'))
     self.assertEqual(18, Size.SHORT.unpack(b'\x00\x12'))



_______________________________________________
tor-commits mailing list
tor-commits@xxxxxxxxxxxxxxxxxxxx
https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits