1# Copyright 2018 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#     https://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
15import proto
16
17
18def test_singly_nested_message():
19    class Foo(proto.Message):
20        class Bar(proto.Message):
21            value = proto.Field(proto.INT32, number=1)
22
23        bar = proto.Field(proto.MESSAGE, number=1, message=Bar)
24
25    foo = Foo(bar=Foo.Bar(value=42))
26    assert foo.bar.value == 42
27
28
29def test_multiply_nested_message():
30    class Foo(proto.Message):
31        class Bar(proto.Message):
32            class Baz(proto.Message):
33                value = proto.Field(proto.INT32, number=1)
34
35            baz = proto.Field(proto.MESSAGE, number=1, message=Baz)
36
37        bar = proto.Field(proto.MESSAGE, number=1, message=Bar)
38
39    foo = Foo(bar=Foo.Bar(baz=Foo.Bar.Baz(value=42)))
40    assert foo.bar.baz.value == 42
41
42
43def test_forking_nested_messages():
44    class Foo(proto.Message):
45        class Bar(proto.Message):
46            spam = proto.Field(proto.STRING, number=1)
47            eggs = proto.Field(proto.BOOL, number=2)
48
49        class Baz(proto.Message):
50            class Bacon(proto.Message):
51                value = proto.Field(proto.INT32, number=1)
52
53            bacon = proto.Field(proto.MESSAGE, number=1, message=Bacon)
54
55        bar = proto.Field(proto.MESSAGE, number=1, message=Bar)
56        baz = proto.Field(proto.MESSAGE, number=2, message=Baz)
57
58    foo = Foo(
59        bar={"spam": "xyz", "eggs": False}, baz=Foo.Baz(bacon=Foo.Baz.Bacon(value=42)),
60    )
61    assert foo.bar.spam == "xyz"
62    assert not foo.bar.eggs
63    assert foo.baz.bacon.value == 42
64