conformance_python.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. #!/usr/bin/env python
  2. #
  3. # Protocol Buffers - Google's data interchange format
  4. # Copyright 2008 Google Inc. All rights reserved.
  5. # https://developers.google.com/protocol-buffers/
  6. #
  7. # Redistribution and use in source and binary forms, with or without
  8. # modification, are permitted provided that the following conditions are
  9. # met:
  10. #
  11. # * Redistributions of source code must retain the above copyright
  12. # notice, this list of conditions and the following disclaimer.
  13. # * Redistributions in binary form must reproduce the above
  14. # copyright notice, this list of conditions and the following disclaimer
  15. # in the documentation and/or other materials provided with the
  16. # distribution.
  17. # * Neither the name of Google Inc. nor the names of its
  18. # contributors may be used to endorse or promote products derived from
  19. # this software without specific prior written permission.
  20. #
  21. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. """A conformance test implementation for the Python protobuf library.
  33. See conformance.proto for more information.
  34. """
  35. import struct
  36. import sys
  37. import os
  38. from google.protobuf import json_format
  39. from google.protobuf import message
  40. from google.protobuf import test_messages_proto3_pb2
  41. from google.protobuf import test_messages_proto2_pb2
  42. import conformance_pb2
  43. sys.stdout = os.fdopen(sys.stdout.fileno(), 'wb', 0)
  44. sys.stdin = os.fdopen(sys.stdin.fileno(), 'rb', 0)
  45. test_count = 0
  46. verbose = False
  47. class ProtocolError(Exception):
  48. pass
  49. def do_test(request):
  50. test_message = test_messages_proto3_pb2.TestAllTypes()
  51. response = conformance_pb2.ConformanceResponse()
  52. test_message = test_messages_proto3_pb2.TestAllTypes()
  53. test_message_proto2 = test_messages_proto2_pb2.TestAllTypesProto2()
  54. isProto3 = (request.message_type == "proto3")
  55. isJson = (request.WhichOneof('payload') == 'json_payload')
  56. try:
  57. if request.WhichOneof('payload') == 'protobuf_payload':
  58. if isProto3:
  59. try:
  60. test_message.ParseFromString(request.protobuf_payload)
  61. except message.DecodeError as e:
  62. response.parse_error = str(e)
  63. return response
  64. elif request.message_type == "proto2":
  65. try:
  66. test_message_proto2.ParseFromString(request.protobuf_payload)
  67. except message.DecodeError as e:
  68. response.parse_error = str(e)
  69. return response
  70. else:
  71. raise ProtocolError("Protobuf request doesn't have specific payload type")
  72. elif request.WhichOneof('payload') == 'json_payload':
  73. try:
  74. json_format.Parse(request.json_payload, test_message)
  75. except Exception as e:
  76. response.parse_error = str(e)
  77. return response
  78. else:
  79. raise ProtocolError("Request didn't have payload.")
  80. if request.requested_output_format == conformance_pb2.UNSPECIFIED:
  81. raise ProtocolError("Unspecified output format")
  82. elif request.requested_output_format == conformance_pb2.PROTOBUF:
  83. if isProto3 or isJson:
  84. response.protobuf_payload = test_message.SerializeToString()
  85. else:
  86. response.protobuf_payload = test_message_proto2.SerializeToString()
  87. elif request.requested_output_format == conformance_pb2.JSON:
  88. try:
  89. if isProto3 or isJson:
  90. response.json_payload = json_format.MessageToJson(test_message)
  91. else:
  92. response.json_payload = json_format.MessageToJson(test_message_proto2)
  93. except Exception as e:
  94. response.serialize_error = str(e)
  95. return response
  96. except Exception as e:
  97. response.runtime_error = str(e)
  98. return response
  99. def do_test_io():
  100. length_bytes = sys.stdin.read(4)
  101. if len(length_bytes) == 0:
  102. return False # EOF
  103. elif len(length_bytes) != 4:
  104. raise IOError("I/O error")
  105. # "I" is "unsigned int", so this depends on running on a platform with
  106. # 32-bit "unsigned int" type. The Python struct module unfortunately
  107. # has no format specifier for uint32_t.
  108. length = struct.unpack("<I", length_bytes)[0]
  109. serialized_request = sys.stdin.read(length)
  110. if len(serialized_request) != length:
  111. raise IOError("I/O error")
  112. request = conformance_pb2.ConformanceRequest()
  113. request.ParseFromString(serialized_request)
  114. response = do_test(request)
  115. serialized_response = response.SerializeToString()
  116. sys.stdout.write(struct.pack("<I", len(serialized_response)))
  117. sys.stdout.write(serialized_response)
  118. sys.stdout.flush()
  119. if verbose:
  120. sys.stderr.write("conformance_python: request=%s, response=%s\n" % (
  121. request.ShortDebugString().c_str(),
  122. response.ShortDebugString().c_str()))
  123. global test_count
  124. test_count += 1
  125. return True
  126. while True:
  127. if not do_test_io():
  128. sys.stderr.write("conformance_python: received EOF from test runner " +
  129. "after %s tests, exiting\n" % (test_count))
  130. sys.exit(0)