Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 40 additions & 21 deletions construct/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -745,10 +745,17 @@ class Validator(SymmetricAdapter):
Needs to implement `_validate()` that returns a bool (or a truthy value)

:param subcon: Construct instance
:param exception: optional. User provided exception to raise when check fails.

:raises ValidationError: validation function returned false. Can be overriden by `exception`
"""
def __init__(self, subcon, exception=None):
super(Validator, self).__init__(subcon)
self.exception = ValidationError if exception is None else exception

def _decode(self, obj, context, path):
if not self._validate(obj, context, path):
raise ValidationError("object failed validation: %s" % (obj,))
raise self.exception("object failed validation: %s" % (obj,))
return obj

def _validate(self, obj, context, path):
Expand Down Expand Up @@ -2507,9 +2514,10 @@ class Const(Subconstruct):

:param value: expected value, usually a bytes literal
:param subcon: optional, Construct instance, subcon used to build value from, assumed to be Bytes if value parameter was a bytes literal
:param exception: optional. User provided exception to raise when check fails.

:raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
:raises ConstError: parsed data does not match specified value, or building from wrong value
:raises ConstError: parsed data does not match specified value, or building from wrong value. Can be overriden by `exception`.
:raises StringError: building from non-bytes value, perhaps unicode

Example::
Expand All @@ -2525,24 +2533,25 @@ class Const(Subconstruct):
b'\xff\x00\x00\x00'
"""

def __init__(self, value, subcon=None):
def __init__(self, value, subcon=None, exception=None):
if subcon is None:
if not isinstance(value, bytestringtype):
raise StringError("given non-bytes value, perhaps unicode? %r" % (value,))
subcon = Bytes(len(value))
super(Const, self).__init__(subcon)
self.value = value
self.flagbuildnone = True
self.exception = ConstError if exception is None else exception

def _parse(self, stream, context, path):
obj = self.subcon._parsereport(stream, context, path)
if obj != self.value:
raise ConstError("parsing expected %r but parsed %r" % (self.value, obj))
raise self.exception("parsing expected %r but parsed %r" % (self.value, obj))
return obj

def _build(self, obj, stream, context, path):
if obj not in (None, self.value):
raise ConstError("building expected None or %r but got %r" % (self.value, obj))
raise self.exception("building expected None or %r but got %r" % (self.value, obj))
return self.subcon._build(self.value, stream, context, path)

def _sizeof(self, context, path):
Expand Down Expand Up @@ -2759,8 +2768,9 @@ class Check(Construct):
Parsing and building return nothing (but check the condition). Size is 0 because stream is unaffected.

:param func: bool or context lambda, that gets run on parsing and building
:param exception: optional. User provided exception to raise when check fails

:raises CheckError: lambda returned false
:raises CheckError: lambda returned false. Can be overriden by `exception`

Can propagate any exception from the lambda, possibly non-ConstructError.

Expand All @@ -2770,20 +2780,21 @@ class Check(Construct):
Check(len_(this.payload.data) == this.payload_len)
"""

def __init__(self, func):
def __init__(self, func, exception=None):
super(Check, self).__init__()
self.func = func
self.flagbuildnone = True
self.exception = CheckError if exception is None else exception

def _parse(self, stream, context, path):
passed = self.func(context) if callable(self.func) else self.func
if not passed:
raise CheckError("check failed during parsing")
raise self.exception("check failed during parsing")

def _build(self, obj, stream, context, path):
passed = self.func(context) if callable(self.func) else self.func
if not passed:
raise CheckError("check failed during building")
raise self.exception("check failed during building")

def _sizeof(self, context, path):
return 0
Expand Down Expand Up @@ -5111,8 +5122,9 @@ class Checksum(Construct):
:param checksumfield: a subcon field that reads the checksum, usually Bytes(int)
:param hashfunc: function that takes bytes and returns whatever checksumfield takes when building, usually from hashlib module
:param bytesfunc: context lambda that returns bytes (or object) to be hashed, usually like this.rawcopy1.data
:param exception: optional. User provided exception to raise when checksum check fails

:raises ChecksumError: parsing and actual checksum does not match actual data
:raises ChecksumError: parsing and actual checksum does not match actual data. Can be overriden by `exception`

Can propagate any exception from the lambdas, possibly non-ConstructError.

Expand Down Expand Up @@ -5145,20 +5157,22 @@ class Checksum(Construct):
d.build(dict(fields=dict(value={})))
"""

def __init__(self, checksumfield, hashfunc, bytesfunc):
def __init__(self, checksumfield, hashfunc, bytesfunc, exception=None):
super(Checksum, self).__init__()
self.checksumfield = checksumfield
self.hashfunc = hashfunc
self.bytesfunc = bytesfunc
self.flagbuildnone = True
self.exception = ChecksumError if exception is None else exception

def _parse(self, stream, context, path):
hash1 = self.checksumfield._parsereport(stream, context, path)
hash2 = self.hashfunc(self.bytesfunc(context))
if hash1 != hash2:
raise ChecksumError("wrong checksum, read %r, computed %r" % (
raise self.exception("wrong checksum, read %r, computed %r" % (
hash1 if not isinstance(hash1,bytestringtype) else binascii.hexlify(hash1),
hash2 if not isinstance(hash2,bytestringtype) else binascii.hexlify(hash2), ))
hash2 if not isinstance(hash2,bytestringtype) else binascii.hexlify(hash2)
))
return hash1

def _build(self, obj, stream, context, path):
Expand Down Expand Up @@ -5670,6 +5684,9 @@ class ExprValidator(Validator):

:param subcon: Construct instance, subcon to adapt
:param validator: lambda that takes (obj, context) and returns a bool
:param exception: optional. User provided exception to raise when check fails.

:raises ValidationError: parsed or build value is not among valids. Can be overriden by `exception`

Example::

Expand All @@ -5680,21 +5697,22 @@ class ExprValidator(Validator):
ValidationError: object failed validation: 88

"""
def __init__(self, subcon, validator):
super(ExprValidator, self).__init__(subcon)
def __init__(self, subcon, validator, exception=None):
super(ExprValidator, self).__init__(subcon, exception=exception)
self._validate = lambda obj,ctx,path: validator(obj,ctx)


def OneOf(subcon, valids):
def OneOf(subcon, valids, exception=None):
r"""
Validates that the object is one of the listed values, both during parsing and building.

.. note:: For performance, `valids` should be a set/frozenset.

:param subcon: Construct instance, subcon to validate
:param valids: collection implementing __contains__, usually a list or set
:param exception: optional. User provided exception to raise when check fails.

:raises ValidationError: parsed or build value is not among valids
:raises ValidationError: parsed or build value is not among valids. Can be overriden by `exception`

Example::

Expand All @@ -5704,22 +5722,23 @@ def OneOf(subcon, valids):
>>> d.parse(b"\xff")
construct.core.ValidationError: object failed validation: 255
"""
return ExprValidator(subcon, lambda obj,ctx: obj in valids)
return ExprValidator(subcon, lambda obj,ctx: obj in valids, exception=exception)


def NoneOf(subcon, invalids):
def NoneOf(subcon, invalids, exception=None):
r"""
Validates that the object is none of the listed values, both during parsing and building.

.. note:: For performance, `valids` should be a set/frozenset.

:param subcon: Construct instance, subcon to validate
:param invalids: collection implementing __contains__, usually a list or set
:param exception: optional. User provided exception to raise when check fails.

:raises ValidationError: parsed or build value is among invalids
:raises ValidationError: parsed or build value is among invalids. Can be overriden by `exception`

"""
return ExprValidator(subcon, lambda obj,ctx: obj not in invalids)
return ExprValidator(subcon, lambda obj,ctx: obj not in invalids, exception=exception)


def Filter(predicate, subcon):
Expand Down
2 changes: 2 additions & 0 deletions docs/adapters.rst
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,5 @@ For example, if 7 out of 8 bits are not allowed to be set (like a flag boolean):
b'\x01'
>>> d.build(88)
ValidationError: object failed validation: 88

ExprValidator also accepts an `exception` keyword argument to override `ValidationError`.
2 changes: 2 additions & 0 deletions docs/misc.rst
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ b'\xff\x00\x00\x00'

The shortcoming is that it only works if the amount and exact bytes are known in advance. To check if a "variable" data meets some criterium (not mere equality), you would need the :class:`~construct.core.Check` class. There is also :class:`~construct.core.OneOf` and :class:`~construct.core.NoneOf` class.

Const also accepts an `exception` keyword argument to override `ConstError`.

Computed
--------
Expand Down Expand Up @@ -160,6 +161,7 @@ FormatFieldError: packer '>B' error during building, given value 9090
>>> st.build(dict(count=9090, items=[]))
ValidationError: check failed during building

Check also accepts an `exception` keyword argument to override `ValidationError`.

Error
------
Expand Down
17 changes: 16 additions & 1 deletion tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,9 @@ def test_const():
assert raises(Const(b"MZ").parse, b"???") == ConstError
assert raises(Const(b"MZ").build, b"???") == ConstError
assert raises(Const(255, Int32ul).parse, b"\x00\x00\x00\x00") == ConstError
class CustomError(Exception):
pass
assert raises(Const(255, Int32ul, exception=CustomError).parse, b"\x00\x00\x00\x00") == CustomError
assert Struct(Const(b"MZ")).build({}) == b"MZ"
# non-prefixed string literals are unicode on Python 3
assert raises(lambda: Const(u"no prefix string")) == StringError
Expand Down Expand Up @@ -574,6 +577,9 @@ def test_check():
assert raises(Check(False).parse, b"") == CheckError
assert raises(Check(this.x == 255).parse, b"", x=0) == CheckError
assert raises(Check(len_(this.a) == 3).parse, b"", a=[]) == CheckError
class CustomError(Exception):
pass
assert raises(Check(len_(this.a) == 3, exception=CustomError).parse, b"", a=[]) == CustomError

def test_error():
assert raises(Error.parse, b"") == ExplicitError
Expand Down Expand Up @@ -1165,18 +1171,21 @@ def test_processrotateleft():
common(d, b'\x0f\xf0', b'\xff\x00')

def test_checksum():
class CustomError(Exception):
pass
d = Struct(
"fields" / RawCopy(Struct(
"a" / Byte,
"b" / Byte,
)),
"checksum" / Checksum(Bytes(64), lambda data: hashlib.sha512(data).digest(), this.fields.data),
"checksum" / Checksum(Bytes(64), lambda data: hashlib.sha512(data).digest(), this.fields.data, exception=CustomError),
)

c = hashlib.sha512(b"\x01\x02").digest()
assert d.parse(b"\x01\x02"+c) == Container(fields=dict(data=b"\x01\x02", value=Container(a=1)(b=2), offset1=0, offset2=2, length=2))(checksum=c)
assert d.build(dict(fields=dict(data=b"\x01\x02"))) == b"\x01\x02"+c
assert d.build(dict(fields=dict(value=dict(a=1,b=2)))) == b"\x01\x02"+c
assert raises(d.parse, b"\x01\x02" + b"\x00" * 64) == CustomError

def test_checksum_nonbytes_issue_323():
st = Struct(
Expand Down Expand Up @@ -1387,11 +1396,17 @@ def test_oneof():
assert OneOf(Byte,[4,5,6,7]).parse(b"\x05") == 5
assert OneOf(Byte,[4,5,6,7]).build(5) == b"\x05"
assert raises(OneOf(Byte,[4,5,6,7]).parse, b"\x08") == ValidationError
class CustomError(Exception):
pass
assert raises(OneOf(Byte,[4,5,6,7], exception=CustomError).parse, b"\x08") == CustomError
assert raises(OneOf(Byte,[4,5,6,7]).build, 8) == ValidationError

def test_noneof():
assert NoneOf(Byte,[4,5,6,7]).parse(b"\x08") == 8
assert raises(NoneOf(Byte,[4,5,6,7]).parse, b"\x06") == ValidationError
class CustomError(Exception):
pass
assert raises(NoneOf(Byte,[4,5,6,7], exception=CustomError).parse, b"\x06") == CustomError

def test_filter():
d = Filter(obj_ != 0, GreedyRange(Byte))
Expand Down