Skip to content

Commit

Permalink
Make __getitem__ raise a KeyError for missing keys
Browse files Browse the repository at this point in the history
In redis-py, attempting to use __getitem__ with a non-existent key
causes a KeyError to be raised, while fakeredis returns None. This
change makes it so that __getitem__ in fakeredis works the same way as
in redis-py.
  • Loading branch information
dnoetzel committed May 22, 2018
1 parent 8216b16 commit 56b1367
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
5 changes: 4 additions & 1 deletion fakeredis.py
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,10 @@ def get(self, name):
return to_bytes(value)

def __getitem__(self, name):
return self.get(name)
value = self.get(name)
if value is not None:
return value
raise KeyError(name)

def getbit(self, name, offset):
"""Returns a boolean indicating the value of ``offset`` in ``name``"""
Expand Down
5 changes: 5 additions & 0 deletions test_fakeredis.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,11 @@ def test_setitem_getitem(self):
self.redis['foo'] = 'bar'
self.assertEqual(self.redis['foo'], b'bar')

def test_getitem_non_existent_key(self):
self.assertEqual(self.redis.keys(), [])
with self.assertRaises(KeyError):
self.redis['noexists']

def test_strlen(self):
self.redis['foo'] = 'bar'

Expand Down

0 comments on commit 56b1367

Please sign in to comment.