Spaces:
Sleeping
Sleeping
from __future__ import annotations | |
import logging | |
import unittest | |
from google.protobuf import timestamp_pb2 | |
import dataclasses | |
from domain.domain_protocol import DomainProtocol, ProtoDeserializationError | |
class TimestampTestD(DomainProtocol[timestamp_pb2.Timestamp]): | |
nanos: int | |
def id(self) -> str: | |
return str(self.nanos) | |
def _from_proto(cls, proto: timestamp_pb2.Timestamp) -> TimestampTestD: | |
return cls(nanos=proto.nanos) | |
def to_proto(self) -> timestamp_pb2.Timestamp: | |
return timestamp_pb2.Timestamp(nanos=self.nanos) | |
class DomainProtocolTest(unittest.TestCase): | |
def setUpClass(cls) -> None: | |
cls.timestamp_d = TimestampTestD(nanos=1) | |
cls.timestamp_proto = timestamp_pb2.Timestamp(nanos=1) | |
def test_proto_roundtrip(self): | |
proto = self.timestamp_d.to_proto() | |
domain_from_proto = TimestampTestD.from_proto(proto) | |
self.assertEqual(self.timestamp_d, domain_from_proto) | |
def test_json_roundtrip(self): | |
json_str = self.timestamp_d.to_json() | |
domain_from_json = TimestampTestD.from_json(json_str) | |
self.assertEqual(self.timestamp_d, domain_from_json) | |
def test_from_proto_empty_fail(self): | |
empty_proto = timestamp_pb2.Timestamp() | |
with self.assertRaises(ProtoDeserializationError): | |
TimestampTestD.from_proto(empty_proto) | |
def test_from_proto_empty_allowed_flag(self): | |
empty_proto = timestamp_pb2.Timestamp() | |
domain_from_proto = TimestampTestD.from_proto(empty_proto, allow_empty=True) | |
self.assertEqual(TimestampTestD(nanos=0), domain_from_proto) | |
def test_validate_proto_not_empty(self): | |
empty_proto = timestamp_pb2.Timestamp() | |
with self.assertRaises(ValueError): | |
TimestampTestD.validate_proto_not_empty(empty_proto) | |
def test_is_empty(self): | |
empty_proto = timestamp_pb2.Timestamp() | |
self.assertTrue(TimestampTestD.is_empty(empty_proto)) | |
def test_message_cls(self): | |
self.assertEqual(timestamp_pb2.Timestamp, TimestampTestD.message_cls()) | |
if __name__ == "__main__": | |
logging.basicConfig(level=logging.INFO) | |
unittest.main() | |