New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Ruby] allow encode json options to be an object that responds to to_hash #9513
Conversation
What is an example of how this arises in real code? What is a |
We ran into this in a Rails application that serves a JSON api and calls out to a GRPC Service. The JSON response is supposed to include the protobuf message. msg = protobuf_message # returned from a GRPC service
{
msg: protobuf_message,
# and other fields
}.to_json
It is not safe for protobuf to assume that the Links: |
@@ -870,6 +870,9 @@ def test_protobuf_encode_decode_json_helpers | |||
|
|||
decoded_msg = Google::Protobuf.decode_json(proto_module::TestMessage, encoded_msg) | |||
assert_equal proto_module::TestMessage.decode_json(m.to_json), decoded_msg | |||
|
|||
assert_equal [m].to_json, Google::Protobuf.encode_json([m]) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe I am missing something, but this test doesn't seem to exercise the new code. We need a test that calls encode_json
with a second parameter that response to to_h
but is not itself a Hash
.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[m].to_json
will do exactly that. Ruby's #to_json
creates a json::Ext::Generator::State
which is not a Hash
. That state object will then be passed to m.to_json
which in turn passes the state to encode_json
.
Withouth my changes the assert fails.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
An ArgumentError: Expected hash arguments
is raised without my changes.
Error: test_protobuf_encode_decode_json_helpers(BasicTest::MessageContainerTest): ArgumentError: Expected hash arguments.
/Users/luka/code/protobuf/ruby/lib/google/protobuf/message_exts.rb:44:in `encode_json'
/Users/luka/code/protobuf/ruby/lib/google/protobuf/message_exts.rb:44:in `to_json'
/Users/luka/code/protobuf/ruby/tests/common_tests.rb:874:in `to_json'
/Users/luka/code/protobuf/ruby/tests/common_tests.rb:874:in `test_protobuf_encode_decode_json_helpers'
871: decoded_msg = Google::Protobuf.decode_json(proto_module::TestMessage, encoded_msg)
872: assert_equal proto_module::TestMessage.decode_json(m.to_json), decoded_msg
873:
=> 874: assert_equal [m].to_json, Google::Protobuf.encode_json([m])
875: assert_equal proto_module::TestMessage.decode_json([m.to_json].first), decoded_msg
876: end
877:
fixes #9500