conformance_python.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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 descriptor
  39. from google.protobuf import descriptor_pool
  40. from google.protobuf import json_format
  41. from google.protobuf import message
  42. from google.protobuf import test_messages_proto3_pb2
  43. from google.protobuf import test_messages_proto2_pb2
  44. import conformance_pb2
  45. sys.stdout = os.fdopen(sys.stdout.fileno(), 'wb', 0)
  46. sys.stdin = os.fdopen(sys.stdin.fileno(), 'rb', 0)
  47. test_count = 0
  48. verbose = False
  49. class ProtocolError(Exception):
  50. pass
  51. def do_test(request):
  52. isProto3 = (request.message_type == "protobuf_test_messages.proto3.TestAllTypesProto3")
  53. isJson = (request.WhichOneof('payload') == 'json_payload')
  54. isProto2 = (request.message_type == "protobuf_test_messages.proto2.TestAllTypesProto2")
  55. if (not isProto3) and (not isJson) and (not isProto2):
  56. raise ProtocolError("Protobuf request doesn't have specific payload type")
  57. test_message = test_messages_proto2_pb2.TestAllTypesProto2() if isProto2 else \
  58. test_messages_proto3_pb2.TestAllTypesProto3()
  59. response = conformance_pb2.ConformanceResponse()
  60. try:
  61. if request.WhichOneof('payload') == 'protobuf_payload':
  62. try:
  63. test_message.ParseFromString(request.protobuf_payload)
  64. except message.DecodeError as e:
  65. response.parse_error = str(e)
  66. return response
  67. elif request.WhichOneof('payload') == 'json_payload':
  68. try:
  69. ignore_unknown_fields = \
  70. request.test_category == \
  71. conformance_pb2.JSON_IGNORE_UNKNOWN_PARSING_TEST
  72. json_format.Parse(request.json_payload, test_message,
  73. ignore_unknown_fields)
  74. except Exception as e:
  75. response.parse_error = str(e)
  76. return response
  77. else:
  78. raise ProtocolError("Request didn't have payload.")
  79. if request.requested_output_format == conformance_pb2.UNSPECIFIED:
  80. raise ProtocolError("Unspecified output format")
  81. elif request.requested_output_format == conformance_pb2.PROTOBUF:
  82. response.protobuf_payload = test_message.SerializeToString()
  83. elif request.requested_output_format == conformance_pb2.JSON:
  84. try:
  85. response.json_payload = json_format.MessageToJson(test_message)
  86. except Exception as e:
  87. response.serialize_error = str(e)
  88. return response
  89. except Exception as e:
  90. response.runtime_error = str(e)
  91. return response
  92. def do_test_io():
  93. length_bytes = sys.stdin.read(4)
  94. if len(length_bytes) == 0:
  95. return False # EOF
  96. elif len(length_bytes) != 4:
  97. raise IOError("I/O error")
  98. # "I" is "unsigned int", so this depends on running on a platform with
  99. # 32-bit "unsigned int" type. The Python struct module unfortunately
  100. # has no format specifier for uint32_t.
  101. length = struct.unpack("<I", length_bytes)[0]
  102. serialized_request = sys.stdin.read(length)
  103. if len(serialized_request) != length:
  104. raise IOError("I/O error")
  105. request = conformance_pb2.ConformanceRequest()
  106. request.ParseFromString(serialized_request)
  107. response = do_test(request)
  108. serialized_response = response.SerializeToString()
  109. sys.stdout.write(struct.pack("<I", len(serialized_response)))
  110. sys.stdout.write(serialized_response)
  111. sys.stdout.flush()
  112. if verbose:
  113. sys.stderr.write("conformance_python: request=%s, response=%s\n" % (
  114. request.ShortDebugString().c_str(),
  115. response.ShortDebugString().c_str()))
  116. global test_count
  117. test_count += 1
  118. return True
  119. while True:
  120. if not do_test_io():
  121. sys.stderr.write("conformance_python: received EOF from test runner " +
  122. "after %s tests, exiting\n" % (test_count))
  123. sys.exit(0)