Skip to content

Commit

Permalink
Fixed a bug with enums, bumped coverage to 100%
Browse files Browse the repository at this point in the history
  • Loading branch information
tnajdek committed Jul 19, 2015
1 parent 3a994af commit e28164b
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 13 deletions.
22 changes: 9 additions & 13 deletions schemamessages/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,13 @@ class MessageFactory(object):

@classmethod
def _get_binary_format_symbol(cls, number):
if(number > sys.maxsize or number > 1.8446744073709552e+19):
raise OverflowError(
"Unable to represent number {} in packed structure".format(
number
)
)

bytes_needed = math.ceil(math.log(number, 2) / 8)
if(bytes_needed <= 1):
binary_format = 'B'
Expand All @@ -172,14 +179,6 @@ def _get_binary_format_symbol(cls, number):
binary_format = 'I'
elif(bytes_needed <= 8):
binary_format = 'Q'
else:
# this should never happen, it will fail earlier
# around when number > sys.maxsize
raise OverflowError(
"Unable to represent number {} in packed structure".format(
number
)
)

return binary_format

Expand Down Expand Up @@ -222,7 +221,7 @@ def get_binary_format(self, msg_schema):
elif(msg_schema['format'][field] == 'enum'):
try:
binary_format += self.__class__._get_binary_format_symbol(
len(msg_schema['format'][field])
len(msg_schema['enums'][field])
)
except Exception:
raise ImproperlyConfigured(
Expand Down Expand Up @@ -352,10 +351,7 @@ def unpack_message(data, factory):
indexes_to_remove.append(idx)

binary_format = cls.binary_format.format(*string_lengths)
try:
msg_data = list(struct.unpack_from(binary_format, buffer_)[1:])
except Exception:
import ipdb; ipdb.set_trace()
msg_data = list(struct.unpack_from(binary_format, buffer_)[1:])

for idx in indexes_to_remove:
del msg_data[idx]
Expand Down
36 changes: 36 additions & 0 deletions test/schemamessages_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,42 @@ def test_bad_schema(self):
)

def test_bad_enum(self):
"""
Test if schema with invalid enums is caught correctly
"""

allthings = MagicMock()
allthings.__len__.return_value = sys.maxsize + 1

bad_schema = {
'BadMessage': {
'enums': {
'allthings': allthings
},
'format': {
'allthings': 'enum'
}
}
}

self.assertRaises(ImproperlyConfigured, MessageFactory, bad_schema)

def test_bad_msg_lookup(self):
"""
Test if making an invalid message class lookup is caught correctly
"""

try:
self.factory.get('FooMessage')
self.factory.get(1)
except KeyError:
self.fail()

self.assertRaises(KeyError, self.factory.get, 'FlyingCars')
self.assertRaises(KeyError, self.factory.get, 999)


def test_bad_enum_lookup(self):
"""
Test if making an invalid enum lookup is caught correctly
"""
Expand Down

0 comments on commit e28164b

Please sign in to comment.