Skip to content

Commit

Permalink
test .stream_to_bytes() == bytes()
Browse files Browse the repository at this point in the history
  • Loading branch information
altendky committed Dec 18, 2023
1 parent 4dbe35e commit 83ef22a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
5 changes: 1 addition & 4 deletions chia/util/struct_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,5 @@ def from_bytes(cls: Type[_T_StructStream], blob: bytes) -> _T_StructStream: # t
def stream_to_bytes(self) -> bytes:
return super().to_bytes(length=self.SIZE, byteorder="big", signed=self.SIGNED)

# this is meant to avoid mixing up construcing a bytes object of a specific
# size (i.e. bytes(int)) vs. serializing the integer to bytes (i.e. bytes(uint32))
# __bytes__ = None
def __bytes__(self) -> bytes:
return super().to_bytes(length=self.SIZE, byteorder="big", signed=self.SIGNED)
return self.stream_to_bytes()
24 changes: 24 additions & 0 deletions tests/util/test_struct_stream.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import enum
import io
import struct
from dataclasses import dataclass
Expand Down Expand Up @@ -27,6 +28,13 @@ def dataclass_parameters(instances: Iterable[object]) -> List[ParameterSet]:
return [dataclass_parameter(instance) for instance in instances]


class StreamAndBytesMatchMode(enum.Enum):
minimum = "minimum"
middle_low = "middle low"
middle_high = "middle high"
maximum = "maximum"


@dataclass(frozen=True)
class BadName:
name: str
Expand Down Expand Up @@ -288,3 +296,19 @@ def test_parse_metadata_from_name_correct_maximum(self, good: Good) -> None:

def test_parse_metadata_from_name_correct_minimum(self, good: Good) -> None:
assert good.cls.MINIMUM == good.minimum

@pytest.mark.parametrize("mode", list(StreamAndBytesMatchMode), ids=lambda mode: mode.value)
def test_stream_to_bytes_and_bytes_match_minimum(self, good: Good, mode: StreamAndBytesMatchMode) -> None:
if mode == StreamAndBytesMatchMode.minimum:
value = good.minimum
elif mode == StreamAndBytesMatchMode.middle_low:
value = int(good.minimum + ((good.maximum - good.minimum) * 0.3))
elif mode == StreamAndBytesMatchMode.middle_high:
value = int(good.minimum + ((good.maximum - good.minimum) * 0.7))
elif mode == StreamAndBytesMatchMode.maximum:
value = good.maximum
else:
raise Exception(f"unhandled parametrization: {mode!r}")

instance = good.cls(value)
assert bytes(instance) == instance.stream_to_bytes()

0 comments on commit 83ef22a

Please sign in to comment.