google/truth

Protobuf: allow unpopulated required fields when `comparingExpectedFieldsOnly`

dmdashenkov opened this issue · 5 comments

Current behaviour

Right now, when a ProtoSubject.comparingExpectedFieldsOnly() is called, the actual message will be rebuilt before an assertion. This is logical and expected.

However, the message is rebuilt using the build() method. The method ensures that all the required fields are set. In the case of Proto 3, this causes no actual checks. But in the case of Proto 2, there may be some missing fields that were simply not the point of the assertion. The check will fail and the assertion causes an UninitializedMessageException.

Note that the check is meaningless. It runs on a subset of fields which were selected from a message that is already built, i.e. the check has either already been done or was intentionally skipped.

Suggestion

Use buildPartial() instead of build(). This way the required field check is skipped.

If the general idea of this proposal is approved, I will be happy to implement it and submit a pull request.

More context

I am actually using Proto 3. I'm modifying the generated code with custom validation logic. It would sound reasonable that build() runs the validation, while buildPartial() skips it.

However, as I've mentioned, even without any customization, it's fairly sensible to use buildPartial() when rebuilding a partial message.

Thanks. It looks to me like we intended to change the code to support this but failed to update the external code (which is slightly forked for legacy reasons). @torquestomp (see internal CL 198651283) would probably know offhand.

And @torquestomp tells me that this probably got incidentally fixed as part of a change back in February. We just haven't done a release since then. Is the build() call you're seeing a problem with indeed the one in FieldScopeImpl.createFromSetFields? If so, I can cut a release, and the problem should go away.

@cpovirk, yes, that's the method. It would be great if you could do the release. Thank you!

Great, it works now! Thank you.