File size: 2,257 Bytes
9041389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from __future__ import annotations
import logging
import unittest
from google.protobuf import timestamp_pb2
import dataclasses

from domain.domain_protocol import DomainProtocol, ProtoDeserializationError


@dataclasses.dataclass(frozen=True)
class TimestampTestD(DomainProtocol[timestamp_pb2.Timestamp]):

    nanos: int

    @property
    def id(self) -> str:
        return str(self.nanos)

    @classmethod
    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):

    @classmethod
    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()