|
| 1 | +# Copyright (C) 2020 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 | +import pytest |
| 16 | + |
| 17 | +import proto |
| 18 | +from google.protobuf.json_format import MessageToJson, Parse |
| 19 | + |
| 20 | + |
| 21 | +def test_message_to_json(): |
| 22 | + class Squid(proto.Message): |
| 23 | + mass_kg = proto.Field(proto.INT32, number=1) |
| 24 | + |
| 25 | + s = Squid(mass_kg=100) |
| 26 | + json = Squid.to_json(s) |
| 27 | + json = json.replace(" ", "").replace("\n", "") |
| 28 | + assert json == '{"massKg":100}' |
| 29 | + |
| 30 | + |
| 31 | +def test_message_from_json(): |
| 32 | + class Squid(proto.Message): |
| 33 | + mass_kg = proto.Field(proto.INT32, number=1) |
| 34 | + |
| 35 | + json = '''{ |
| 36 | + "massKg": 100 |
| 37 | + } |
| 38 | + ''' |
| 39 | + |
| 40 | + s = Squid.from_json(json) |
| 41 | + assert s == Squid(mass_kg=100) |
| 42 | + |
| 43 | + |
| 44 | +def test_message_json_round_trip(): |
| 45 | + class Squid(proto.Message): |
| 46 | + mass_kg = proto.Field(proto.INT32, number=1) |
| 47 | + |
| 48 | + s = Squid(mass_kg=100) |
| 49 | + json = Squid.to_json(s) |
| 50 | + s2 = Squid.from_json(json) |
| 51 | + |
| 52 | + assert s == s2 |
0 commit comments