Redis SADD SMEMBERS Set Mock in Python
A lightweight mock of Redis SADD and SMEMBERS using Python sets for testing or local caching.
Python code
29 linesclass RedisSetMock:
def __init__(self):
self.sets = {}
def sadd(self, key, *members):
if key not in self.sets:
self.sets[key] = set()
before = len(self.sets[key])
self.sets[key].update(members)
return len(self.sets[key]) - before
def smembers(self, key):
return set(self.sets.get(key, set()))
if __name__ == "__main__":
redis_mock = RedisSetMock()
added = redis_mock.sadd("users:online", "alice", "bob", "carol")
print(f"Added: {added}")
added_dup = redis_mock.sadd("users:online", "alice", "dave")
print(f"Added (with dup): {added_dup}")
members = redis_mock.smembers("users:online")
print(f"Members: {sorted(members)}")
empty = redis_mock.smembers("nonexistent")
print(f"Non-existent key members: {empty}")
Output
Added: 3
Added (with dup): 1
Members: ['alice', 'bob', 'carol', 'dave']
Non-existent key members: set()
How it works
The RedisSetMock class stores each Redis key as a Python set, guaranteeing uniqueness. sadd uses set.update to add members and returns the count of truly new members by comparing lengths before and after. smembers returns a copy of the set or an empty set for missing keys, mimicking Redis behavior. The mock is useful for unit tests and local development without a real Redis server.
Common mistakes
- Returning the full set size from SADD instead of the number of newly added members.
- Returning the internal set directly, risking accidental mutation from outside code.
- Forgetting to handle missing keys in SMEMBERS with an empty set.
Variations
- Use `fakeredis` library for a more comprehensive Redis mock.
- Store sets as lists with manual duplicate checks if you need ordered members.
Real-world use cases
- Unit testing code that uses Redis sets without spinning up a local Redis server.
- Simulating online user sets in a local development environment for quick prototyping.
- Caching small in-memory sets in applications where Redis is not required for production.
Sponsored
More from Caching & Redis
- Cache Asides in Python with a Read-Through Loader easy
- Cache Data in Redis with Python easy
- Cache Penetration Null Object Mock in Python medium
- Cache Stampede Prevention with SingleFlight in Python medium
- Cache Warming with Python: Preload Hot Keys easy
- Coalescing duplicate in-flight requests: one shared result for concurrent callers hard
Keep learning
Related tutorials and quizzes for this topic.