Skip to content
This repository has been archived by the owner on Sep 11, 2019. It is now read-only.

Add option to create an instance with non-shared data #14

Merged
merged 1 commit into from
Feb 20, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ test you run, be sure to call `r.flushall()` in your
# Clear data in fakenewsredis.
self.r.flushall()

Alternatively, you can create an instance that does not share data with other
instances, by passing `singleton=False` to the constructor.

Fakenewsredis implements the same interface as `redis-py`_, the
popular redis client for python, and models the responses
Expand Down
18 changes: 11 additions & 7 deletions fakenewsredis.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,10 +269,14 @@ def from_url(cls, url, db=None, **kwargs):
return cls(db=db, **kwargs)

def __init__(self, db=0, charset='utf-8', errors='strict',
decode_responses=False, **kwargs):
if db not in DATABASES:
DATABASES[db] = _ExpiringDict()
self._db = DATABASES[db]
decode_responses=False, singleton=True, **kwargs):
if singleton:
self._dbs = DATABASES
else:
self._dbs = {}
if db not in self._dbs:
self._dbs[db] = _ExpiringDict()
self._db = self._dbs[db]
self._db_num = db
self._encoding = charset
self._encoding_errors = errors
Expand All @@ -282,12 +286,12 @@ def __init__(self, db=0, charset='utf-8', errors='strict',
_patch_responses(self)

def flushdb(self):
DATABASES[self._db_num].clear()
self._db.clear()
return True

def flushall(self):
for db in DATABASES:
DATABASES[db].clear()
for db in self._dbs.values():
db.clear()

del self._pubsubs[:]

Expand Down
18 changes: 18 additions & 0 deletions test_fakenewsredis.py
Original file line number Diff line number Diff line change
Expand Up @@ -3644,6 +3644,24 @@ def test_can_accept_any_kwargs(self):
fakenewsredis.FakeRedis(foo='bar', bar='baz')
fakenewsredis.FakeStrictRedis(foo='bar', bar='baz')

def test_singleton(self):
r1 = fakenewsredis.FakeStrictRedis(singleton=False)
r2 = fakenewsredis.FakeStrictRedis(singleton=False)
r3 = fakenewsredis.FakeStrictRedis()
r4 = fakenewsredis.FakeStrictRedis()
r3.flushall()

r1.set('foo', 'bar')
r3.set('bar', 'baz')

self.assertIn('foo', r1)
self.assertNotIn('foo', r2)
self.assertNotIn('foo', r3)

self.assertIn('bar', r3)
self.assertIn('bar', r4)
self.assertNotIn('bar', r1)

def test_from_url(self):
db = fakenewsredis.FakeStrictRedis.from_url(
'redis://username:password@localhost:6379/0')
Expand Down