()
| 136 | |
| 137 | |
| 138 | def test_oneof_support(): |
| 139 | @dataclass |
| 140 | class Sub(betterproto.Message): |
| 141 | val: int = betterproto.int32_field(1) |
| 142 | |
| 143 | @dataclass |
| 144 | class Foo(betterproto.Message): |
| 145 | bar: int = betterproto.int32_field(1, group="group1") |
| 146 | baz: str = betterproto.string_field(2, group="group1") |
| 147 | sub: Sub = betterproto.message_field(3, group="group2") |
| 148 | abc: str = betterproto.string_field(4, group="group2") |
| 149 | |
| 150 | foo = Foo() |
| 151 | |
| 152 | assert betterproto.which_one_of(foo, "group1")[0] == "" |
| 153 | |
| 154 | foo.bar = 1 |
| 155 | foo.baz = "test" |
| 156 | |
| 157 | # Other oneof fields should now be unset |
| 158 | assert not hasattr(foo, "bar") |
| 159 | assert object.__getattribute__(foo, "bar") == betterproto.PLACEHOLDER |
| 160 | assert betterproto.which_one_of(foo, "group1")[0] == "baz" |
| 161 | |
| 162 | foo.sub = Sub(val=1) |
| 163 | assert betterproto.serialized_on_wire(foo.sub) |
| 164 | |
| 165 | foo.abc = "test" |
| 166 | |
| 167 | # Group 1 shouldn't be touched, group 2 should have reset |
| 168 | assert not hasattr(foo, "sub") |
| 169 | assert object.__getattribute__(foo, "sub") == betterproto.PLACEHOLDER |
| 170 | assert betterproto.which_one_of(foo, "group2")[0] == "abc" |
| 171 | |
| 172 | # Zero value should always serialize for one-of |
| 173 | foo = Foo(bar=0) |
| 174 | assert betterproto.which_one_of(foo, "group1")[0] == "bar" |
| 175 | assert bytes(foo) == b"\x08\x00" |
| 176 | |
| 177 | # Round trip should also work |
| 178 | foo2 = Foo().parse(bytes(foo)) |
| 179 | assert betterproto.which_one_of(foo2, "group1")[0] == "bar" |
| 180 | assert foo.bar == 0 |
| 181 | assert betterproto.which_one_of(foo2, "group2")[0] == "" |
| 182 | |
| 183 | |
| 184 | @pytest.mark.skipif( |
nothing calls this directly
no test coverage detected