Skip to content

Commit

Permalink
Handle key expiry in _ExpiringDict.__iter__
Browse files Browse the repository at this point in the history
Fixes #135 and #185.
  • Loading branch information
bmerry committed Apr 3, 2018
1 parent 0cf62b5 commit 39553dc
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
14 changes: 14 additions & 0 deletions fakeredis.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,11 @@ def copy(self):
new_copy.update(self._dict)
return new_copy

# Not strictly necessary, but MutableMapping implements it by popping one
# item at a time, which may have odd effects in _ExpiringDict.
def clear(self):
self._dict.clear()


class _ExpiringDict(_StrKeyDict):
def __getitem__(self, key):
Expand Down Expand Up @@ -183,6 +188,15 @@ def persist(self, key):
def expiring(self, key):
return self._dict[to_bytes(key)][1]

def __iter__(self):
def generator():
for key, (value, expiration) in iteritems(self._dict):
if expiration is not None and datetime.now() > expiration:
continue
yield key

return generator()


class _ZSet(_StrKeyDict):
redis_type = b'zset'
Expand Down
7 changes: 7 additions & 0 deletions test_fakeredis.py
Original file line number Diff line number Diff line change
Expand Up @@ -1294,6 +1294,13 @@ def test_scan_all_in_single_call(self):
self.assertEqual(set(actual[1]), set(all_keys))
self.assertEqual(actual[0], 0)

@attr('slow')
def test_scan_expired_key(self):
self.redis.set('expiringkey', 'value')
self.redis.pexpire('expiringkey', 1)
sleep(1)
self.assertEqual(self.redis.scan()[1], [])

def test_scard(self):
self.redis.sadd('foo', 'member1')
self.redis.sadd('foo', 'member2')
Expand Down

0 comments on commit 39553dc

Please sign in to comment.