• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2024 Google LLC
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Helpers for tests"""
16
17import logging
18from typing import List
19
20import proto
21
22from google.protobuf import duration_pb2
23from google.protobuf import timestamp_pb2
24from google.protobuf.json_format import MessageToJson
25
26
27class Genre(proto.Enum):
28    GENRE_UNSPECIFIED = 0
29    CLASSICAL = 1
30    JAZZ = 2
31    ROCK = 3
32
33
34class Composer(proto.Message):
35    given_name = proto.Field(proto.STRING, number=1)
36    family_name = proto.Field(proto.STRING, number=2)
37    relateds = proto.RepeatedField(proto.STRING, number=3)
38    indices = proto.MapField(proto.STRING, proto.STRING, number=4)
39
40
41class Song(proto.Message):
42    composer = proto.Field(Composer, number=1)
43    title = proto.Field(proto.STRING, number=2)
44    lyrics = proto.Field(proto.STRING, number=3)
45    year = proto.Field(proto.INT32, number=4)
46    genre = proto.Field(Genre, number=5)
47    is_five_mins_longer = proto.Field(proto.BOOL, number=6)
48    score = proto.Field(proto.DOUBLE, number=7)
49    likes = proto.Field(proto.INT64, number=8)
50    duration = proto.Field(duration_pb2.Duration, number=9)
51    date_added = proto.Field(timestamp_pb2.Timestamp, number=10)
52
53
54class EchoResponse(proto.Message):
55    content = proto.Field(proto.STRING, number=1)
56
57
58def parse_responses(response_message_cls, all_responses: List[proto.Message]) -> bytes:
59    # json.dumps returns a string surrounded with quotes that need to be stripped
60    # in order to be an actual JSON.
61    json_responses = [
62        (
63            response_message_cls.to_json(response).strip('"')
64            if issubclass(response_message_cls, proto.Message)
65            else MessageToJson(response).strip('"')
66        )
67        for response in all_responses
68    ]
69    logging.info(f"Sending JSON stream: {json_responses}")
70    ret_val = "[{}]".format(",".join(json_responses))
71    return bytes(ret_val, "utf-8")
72