Skip to content

Commit

Permalink
fix(gapic-common): Fixed handling of optional fields in coerce (#954)
Browse files Browse the repository at this point in the history
  • Loading branch information
psyho authored May 30, 2023
1 parent 095c530 commit fc8fb74
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
1 change: 1 addition & 0 deletions gapic-common/lib/gapic/protobuf.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ module Protobuf
# @return [Object] An instance of the given message class.
def self.coerce hash, to:
return hash if hash.is_a? to
return nil if hash.nil?

# Special case handling of certain types
return time_to_timestamp hash if to == Google::Protobuf::Timestamp && hash.is_a?(Time)
Expand Down
9 changes: 9 additions & 0 deletions gapic-common/test/gapic/protobuf/coerce_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,15 @@ class ProtobufCoerceTest < Minitest::Spec
_(user.type).must_equal USER_TYPE
end

it "handles optional fields in a simple hash" do
hash = { name: USER_NAME, type: USER_TYPE, timestamp: nil }
user = Gapic::Protobuf.coerce hash, to: Gapic::Examples::User
_(user).must_be_kind_of Gapic::Examples::User
_(user.name).must_equal USER_NAME
_(user.type).must_equal USER_TYPE
_(user.timestamp).must_be_nil
end

it "creates a protobuf message from a hash with a nested message" do
request_hash = { name: REQUEST_NAME, user: Gapic::Examples::User.new(name: USER_NAME, type: USER_TYPE) }
request = Gapic::Protobuf.coerce request_hash, to: Gapic::Examples::Request
Expand Down

0 comments on commit fc8fb74

Please sign in to comment.