Skip to content

Commit

Permalink
Merge pull request #197 from zachmargolis/unknown-enum-values
Browse files Browse the repository at this point in the history
Handle unknown enums when decoding
  • Loading branch information
localshred committed Jul 28, 2014
2 parents fc9b239 + cf6264d commit 97ba12d
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/protobuf/field/enum_field.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ def encode(value)
super(value.to_i)
end

def decode(value)
if acceptable?(value)
value
end
end

def enum?
true
end
Expand Down
59 changes: 59 additions & 0 deletions spec/lib/protobuf/message_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,65 @@
it 'creates a new message object decoded from the given bytes' do
expect(::Test::Resource.decode(message.encode)).to eq message
end

context 'with a new enum value' do
let(:older_message) do
Class.new(Protobuf::Message) do
enum_class = Class.new(::Protobuf::Enum) do
define :YAY, 1
end

optional enum_class, :enum_field, 1
repeated enum_class, :enum_list, 2
end
end

let(:newer_message) do
Class.new(Protobuf::Message) do
enum_class = Class.new(::Protobuf::Enum) do
define :YAY, 1
define :HOORAY, 2
end

optional enum_class, :enum_field, 1
repeated enum_class, :enum_list, 2
end
end

context 'with a singular field' do
it 'treats the field as if it was unset when decoding' do
newer = newer_message.new(:enum_field => :HOORAY).serialize

expect(older_message.decode(newer).enum_field!).to be_nil
end

it 'rejects an unknown value when using the constructor' do
expect { older_message.new(:enum_field => :HOORAY) }.to raise_error
end

it 'rejects an unknown value when the setter' do
older = older_message.new
expect { older.enum_field = :HOORAY }.to raise_error
end
end

context 'with a repeated field' do
it 'treats the field as if it was unset when decoding' do
newer = newer_message.new(:enum_list => [ :HOORAY ]).serialize

expect(older_message.decode(newer).enum_list).to eq([])
end

it 'rejects an unknown value when using the constructor' do
expect { older_message.new(:enum_list => [ :HOORAY ]) }.to raise_error
end

it 'rejects an unknown value when the setter' do
older = older_message.new
expect { older.enum_field = [ :HOORAY ] }.to raise_error
end
end
end
end

describe 'defining a new field' do
Expand Down

0 comments on commit 97ba12d

Please sign in to comment.