Skip to content
This repository was archived by the owner on Apr 22, 2024. It is now read-only.

Commit 04dd2a3

Browse files
erickvermotmacartur
authored andcommitted
Make binarydata accept other type of values
Types allowed by binarydata are None, packable value and False
1 parent 61e2ba4 commit 04dd2a3

2 files changed

Lines changed: 24 additions & 14 deletions

File tree

pyof/foundation/basic_types.py

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -428,7 +428,7 @@ class BinaryData(GenericType):
428428
return the size of the instance using Python's :func:`len`.
429429
"""
430430

431-
def __init__(self, value=b''): # noqa
431+
def __init__(self, value=None): # noqa
432432
"""The constructor takes the parameter below.
433433
434434
Args:
@@ -438,10 +438,23 @@ def __init__(self, value=b''): # noqa
438438
ValueError: If given value is not bytes.
439439
440440
"""
441-
if not isinstance(value, bytes):
442-
raise ValueError('BinaryData must contain bytes.')
441+
value = self._pack(value)
443442
super().__init__(value)
444443

444+
@staticmethod
445+
def _pack(value):
446+
if hasattr(value, 'pack') and callable(value.pack):
447+
value = value.pack()
448+
elif value is None:
449+
value = b''
450+
451+
if not isinstance(value, bytes):
452+
msg = 'BinaryData value must contain bytes or have pack method. '
453+
msg += 'Received type {} value: "{}"'.format(type(value), value)
454+
raise ValueError(msg)
455+
456+
return value
457+
445458
def pack(self, value=None):
446459
"""Pack the value as a binary representation.
447460
@@ -452,18 +465,9 @@ def pack(self, value=None):
452465
:exc:`~.exceptions.NotBinaryData`: If value is not :class:`bytes`.
453466
454467
"""
455-
if isinstance(value, type(self)):
456-
return value.pack()
457-
458468
if value is None:
459-
value = self._value
460-
461-
if value:
462-
if isinstance(value, bytes):
463-
return value
464-
raise ValueError('BinaryData must contain bytes.')
465-
466-
return b''
469+
return self._value
470+
return self._pack(value)
467471

468472
def unpack(self, buff, offset=0):
469473
"""Unpack a binary message into this object's attributes.

tests/test_foundation/test_basic_types.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,12 @@ def test_default_value(self):
172172
actual = BinaryData().pack()
173173
self.assertEqual(expected, actual)
174174

175+
def test_none_value(self):
176+
"""Pack of BinaryData initialized with None should be empty bytes."""
177+
expected = b''
178+
actual = BinaryData(None).pack()
179+
self.assertEqual(expected, actual)
180+
175181
def test_pack_bytes(self):
176182
"""Test packing some bytes."""
177183
expected = b'forty two'

0 commit comments

Comments
 (0)