fakeredis Documentation

repository·master·Indexed 19 days ago

https://github.com/cunla/fakeredis-py

A fast, pure-Python, in-memory implementation of the Redis protocol designed as a drop-in replacement for redis-py and valkey-py. It allows developers to test Redis, Valkey, DragonflyDB, or KeyDB applications without a real server. Features include support for Asyncio, version emulation, a TCP fake server, and specialized extras for Lua scripting, JSON commands, and probabilistic filters.

Tokens
20.1K
Snippets
59
Records
145
Agent score
16%

What's inside fakeredis

  1. Use RedisTimeSeries commands in fakeredis-py

    master

    The fakeredis-py library provides a complete implementation of the RedisTimeSeries module. All 17 timeseries commands are currently implemented, allowing you to simulate time-series data operations without a running Redis server.

    Supported commands include:

    • Data Ingestion: TS.ADD, TS.MADD (multi-add)
    • Data Retrieval: TS.GET, TS.MGET, TS.RANGE, TS.REVRANGE, TS.MRANGE, TS.MREVRANGE
    • Management: TS.CREATE, TS.ALTER, TS.DEL, TS.INFO, TS.QUERYINDEX
    • Compaction Rules: TS.CREATERULE, TS.DELETERULE
    • Arithmetic: TS.INCRBY, TS.DECRBY
  2. Understand the known limitations of fakeredis

    master

    While fakeredis provides a high-fidelity implementation of the Redis protocol, there are several behavioral differences compared to a real Redis server that you should be aware of:

    • Hyperloglogs: Implemented using sets. The type command may return incorrect results, get cannot retrieve encoded values, and counts may differ slightly (though they are exact).
    • Error Handling: When multiple error conditions exist (e.g., wrong type vs. malformed argument), the specific error returned might not match Redis.
    • Precision: incrbyfloat and hincrbyfloat use Python's float instead of Redis's C long double, which may result in different precision.
    • Blocking Commands: fakeredis does not guarantee the same wake-up order for clients blocked on commands.
    • CLIENT PAUSE: The command validates arguments, but command processing is not actually suspended; commands sent while paused are served immediately.
    • Client Addressing: Every connection reports 127.0.0.1:0, meaning CLIENT KILL with the ADDR filter will match all connections.
    • SCAN Commands: SCAN, ZSCAN, HSCAN, and SSCAN may not iterate all items if keys are deleted/renamed during iteration, and they may use different chunk sizes or orders than Redis.
    • DUMP/RESTORE: Uses Python's pickle module instead of the RDB format. WARNING: Do not use RESTORE with untrusted data, as malicious pickles can execute arbitrary code.
    • Undefined Behavior: In cases where Redis behavior is undefined (like element order in sets/hashes), fakeredis results may differ.
  3. How FakeRedis connection modes work

    master

    FakeRedis offers two primary modes of operation:

    1. Direct (in-process) mode: Uses FakeRedis() or FakeAsyncRedis(). This is the fastest mode and is ideal for unit and integration tests where you can inject the fake client directly into your code. It operates entirely in-memory.

    2. TCP server mode: Uses TcpFakeServer to expose the fake server over a socket (e.g., 127.0.0.1:6379). This mode is necessary when your application code creates its own redis.Redis connections via host/port and you cannot easily inject a fake client instance.

  4. Share state between multiple FakeRedis clients

    master

    By default, every FakeRedis instance creates its own internal FakeServer with isolated state. To allow multiple clients to share the same data (simulating multiple connections to one real Redis instance), you must explicitly create a FakeServer and pass it to the server argument of each client.

    import fakeredis
    
    server = fakeredis.FakeServer()
    r1 = fakeredis.FakeStrictRedis(server=server)
    r2 = fakeredis.FakeStrictRedis(server=server)
    
    r1.set("foo", "bar")
    print(r2.get("foo"))  # b'bar'
  5. Share state between clients using FakeServer

    master

    By default, each FakeStrictRedis instance is isolated. To allow multiple clients to share the same in-memory data, instantiate a FakeServer and pass it to the server argument of your client instances.

    import fakeredis
    
    server = fakeredis.FakeServer()
    r1 = fakeredis.FakeStrictRedis(server=server)
    r2 = fakeredis.FakeStrictRedis(server=server)
    
    r1.set("greeting", "hello")
    r2.get("greeting")  # b'hello' — same underlying data
  6. Quickstart: Use fakeredis with Asyncio

    master

    For asynchronous applications, use FakeAsyncRedis to emulate redis.asyncio.Redis.

    import fakeredis
    
    async def main():
        r = fakeredis.FakeAsyncRedis()
        await r.set("foo", "bar")
        await r.get("foo")  # b'bar'
  7. Quickstart: Use fakeredis as a drop-in replacement

    master

    You can use fakeredis as a synchronous, in-memory replacement for redis-py. The API is identical to redis.Redis.

    import fakeredis
    
    r = fakeredis.FakeStrictRedis()
    r.set("foo", "bar")
    r.get("foo")  # b'bar'
  8. Install fakeredis

    master

    Install the core package or specific extras depending on the Redis features you need to emulate. On macOS/zsh, ensure you quote the extra names in your pip command.

    • Core (no extras): pip install fakeredis
    • Lua scripting support: pip install "fakeredis[lua]"
    • JSON commands: pip install "fakeredis[json]"
    • Bloom/Cuckoo filters: pip install "fakeredis[bf]"
    • Probabilistic filters + JSON: pip install "fakeredis[probabilistic,json]"
    pip install fakeredis                        # core, no extras
    pip install "fakeredis[lua]"                 # EVAL / EVALSHA scripting
    pip install "fakeredis[json]"                # JSON.* commands
    pip install "fakeredis[bf]"                  # Bloom / Cuckoo / Count-Min / Top-K filters
    pip install "fakeredis[probabilistic,json]"  # probabilistic filters + JSON
  9. Use fakeredis in pytest

    master

    To use fakeredis in your test suite, create a pytest fixture that returns a FakeStrictRedis instance. This ensures each test gets a clean, isolated in-memory server.

    import pytest
    import fakeredis
    
    @pytest.fixture
    def redis_client():
        return fakeredis.FakeStrictRedis()
    
    def test_cache_set(redis_client):
        redis_client.set("user:1", "alice")
        assert redis_client.get("user:1") == b"alice"
  10. Configure Django to use FakeRedis for caching

    master

    To use fakeredis with the standard Django cache backend, provide FakeConnection in the OPTIONS of your CACHES setting.

    If using the django-redis library, you must pass the connection class via CONNECTION_POOL_KWARGS.

    # Standard Django RedisCache
    from fakeredis import FakeConnection
    
    CACHES = {
        "default": {
            "BACKEND": "django.core.cache.backends.redis.RedisCache",
            "LOCATION": "...",
            "OPTIONS": {"connection_class": FakeConnection},
        }
    }
    
    # Using django-redis library
    CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "...",
            "OPTIONS": {
                "CONNECTION_POOL_KWARGS": {"connection_class": FakeConnection},
            },
        }
    }