Skip to content

Commit

Permalink
Setup fix for python/upb for the enforcement of closed enums in editi…
Browse files Browse the repository at this point in the history
…ons.

This will be a breaking change in the 30.0 release.

PiperOrigin-RevId: 675335785
  • Loading branch information
mkruskal-google authored and copybara-github committed Sep 20, 2024
1 parent 7d3e80c commit c570a5f
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 0 deletions.
5 changes: 5 additions & 0 deletions python/convert.c
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include "python/protobuf.h"
#include "upb/message/compare.h"
#include "upb/message/map.h"
#include "upb/reflection/def.h"
#include "upb/reflection/message.h"
#include "utf8_range.h"

Expand Down Expand Up @@ -179,8 +180,12 @@ static bool PyUpb_PyToUpbEnum(PyObject* obj, const upb_EnumDef* e,
} else {
int32_t i32;
if (!PyUpb_GetInt32(obj, &i32)) return false;
#ifdef UPB_FUTURE_PYTHON_CLOSED_ENUM_ENFORCEMENT
if (upb_EnumDef_IsClosed(e) && !upb_EnumDef_CheckNumber(e, i32)) {
#else
if (upb_FileDef_Syntax(upb_EnumDef_File(e)) == kUpb_Syntax_Proto2 &&
!upb_EnumDef_CheckNumber(e, i32)) {
#endif
PyErr_Format(PyExc_ValueError, "invalid enumerator %d", (int)i32);
return false;
}
Expand Down
6 changes: 6 additions & 0 deletions python/google/protobuf/internal/message_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1422,6 +1422,12 @@ def testAssignInvalidEnum(self):
m.repeated_nested_enum[0] = 2
with self.assertRaises(ValueError):
m.repeated_nested_enum[0] = 123456
else:
m.optional_nested_enum = 1234567
m.repeated_nested_enum.append(1234567)
m.repeated_nested_enum.append(2)
m.repeated_nested_enum[0] = 2
m.repeated_nested_enum[0] = 123456

# Unknown enum value can be parsed but is ignored.
m2 = unittest_proto3_arena_pb2.TestAllTypes()
Expand Down
11 changes: 11 additions & 0 deletions upb/port/def.inc
Original file line number Diff line number Diff line change
Expand Up @@ -429,3 +429,14 @@ void __asan_unpoison_memory_region(void const volatile *addr, size_t size);
#define UPB_LINKARR_APPEND(name)

#endif

// Future versions of upb will include breaking changes to some APIs.
// This macro can be set to enable these API changes ahead of time, so that
// user code can be updated before upgrading versions of protobuf.
#ifdef UPB_FUTURE_BREAKING_CHANGES

// Properly enforce closed enums in python.
// Owner: mkruskal@
#define UPB_FUTURE_PYTHON_CLOSED_ENUM_ENFORCEMENT 1

#endif
2 changes: 2 additions & 0 deletions upb/port/undef.inc
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,5 @@
#undef UPB_LINKARR_APPEND
#undef UPB_LINKARR_START
#undef UPB_LINKARR_STOP
#undef UPB_FUTURE_BREAKING_CHANGES
#undef UPB_FUTURE_PYTHON_CLOSED_ENUM_ENFORCEMENT

0 comments on commit c570a5f

Please sign in to comment.