Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

revert StructStream.__bytes__() to a working state instead of intentional failure #17075

Merged
merged 2 commits into from
Dec 18, 2023
Merged
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
5 changes: 2 additions & 3 deletions chia/util/struct_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +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 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()
Loading