Skip to content

Commit

Permalink
Avoid mutation of @DaTa from external reference
Browse files Browse the repository at this point in the history
Added a ternany and .dup to the return of 'with_thing_at' to avoid
return a mutable reference that allowed in memory mutation of the
@DaTa struct inside MockRedis

This commit done on the dime of:
Simply Measured
twitter: @SimplyMeasured
web: http://www.simplymeasured.com

Change-Id: I7ea498929a9183f83f40b6f4e6589b7aaacd397b
Reviewed-on: https://gerrit.causes.com/19655
Reviewed-by: Aiden Scandella <aiden@causes.com>
Tested-by: jenkins <jenkins@causes.com>
  • Loading branch information
kungfumike authored and Aiden Scandella committed Mar 14, 2013
1 parent c3803d5 commit a08edf7
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
### 0.6.6 (unreleased)
* Avoid mutation of @data from external reference

### 0.6.5
* Fix `zrevrange` to return an empty array on invalid range
* Fix `srandmember` spec on redis-rb 3.0.3
Expand Down
6 changes: 5 additions & 1 deletion lib/mock_redis/utility_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,16 @@ def with_thing_at(key, assertion, empty_thing_generator)
data_key_ref = data[key]
ret = yield data[key]
data[key] = data_key_ref if data[key].nil?
ret
primitive?(ret) ? ret.dup : ret
ensure
clean_up_empties_at(key)
end
end

def primitive?(value)
value.kind_of?(::Array) || value.kind_of?(::Hash) || value.kind_of?(::String)
end

def clean_up_empties_at(key)
if data[key] && data[key].empty?
del(key)
Expand Down
10 changes: 10 additions & 0 deletions spec/commands/hgetall_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,15 @@
@redises.hgetall('mock-redis-test:nonesuch').should == {}
end

it "doesn't return a mutable reference to the returned data" do
mr = MockRedis.new
mr.hset(@key, 'k1', 'v1')
mr.hset(@key, 'k2', 'v2')
hash = mr.hgetall(@key)
hash['dont'] = 'mutate'
new_hash = mr.hgetall(@key)
new_hash.keys.sort.should == ['k1', 'k2']
end

it_should_behave_like "a hash-only command"
end

0 comments on commit a08edf7

Please sign in to comment.