Skip to content

Commit

Permalink
Fix redundant and missed checks
Browse files Browse the repository at this point in the history
Signed-off-by: Alexey Stepanov <penguinolog@gmail.com>
  • Loading branch information
penguinolog committed Dec 9, 2016
1 parent 26cf6cc commit c7c135d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
8 changes: 7 additions & 1 deletion binfield/binfield.py
Expand Up @@ -114,7 +114,6 @@ def _get_index(val):
return slice(*val)
if isinstance(val, dict):
return slice(*val['_index_'])
raise TypeError('Unexpected index format: {!r}'.format(val))


def _get_idx(val):
Expand Down Expand Up @@ -214,6 +213,10 @@ def __new__(mcs, name, bases, classdict):
raise TypeError(
'Pre-defined size has invalid type: {!r}'.format(size)
)

if size <= 0:
raise ValueError('Size must be positive value !')

mask_from_size = (1 << size) - 1

mask = classdict.get('_mask_', mask_from_size)
Expand All @@ -223,6 +226,9 @@ def __new__(mcs, name, bases, classdict):
raise TypeError(
'Pre-defined mask has invalid type: {!r}'.format(mask)
)
if mask < 0:
raise ValueError('BitMask is strictly positive!')

if size is None:
size = mask.bit_length()

Expand Down
37 changes: 37 additions & 0 deletions test/test_baseFunc.py
Expand Up @@ -258,3 +258,40 @@ class NestedMappedBinField(BinField):
'(0xC1) (0b11000001)>'
)
self.assertEqual(nbf[:], nbf) # Full slice calls self-copy

def test_negative(self):
with self.assertRaises(TypeError):
class NewBinField(BinField):
pass

class NestedBitField(NewBinField):
pass

with self.assertRaises(ValueError):
class UnexpectedIndex(BinField):
_index_ = (0, 10)

with self.assertRaises(IndexError):
class IntersectIndexes(BinField):
first = (0, 2)
second = (1, 3)

with self.assertRaises(TypeError):
class IncorrectSizeType(BinField):
_size_ = 'Some size'

with self.assertRaises(ValueError):
class IncorrectSizeValue(BinField):
_size_ = -1

with self.assertRaises(TypeError):
class IncorrectMaskType(BinField):
_mask_ = 'Some mask'

with self.assertRaises(ValueError):
class IncorrectMaskValue(BinField):
_mask_ = -1

with self.assertRaises(TypeError):
class GarbageData(BinField):
value = 'Not recognized'

0 comments on commit c7c135d

Please sign in to comment.