Test your add-on against Redis#
This guide shows you how to run your add-on's tests with @ram.cache going through collective.redismemoize.
Use it to check that the values your functions cache are shareable, before a deploy finds out.
The tests use fakeredis, an in-process Redis, so they need no server.
Add the test dependencies#
Add collective.redismemoize and fakeredis to your add-on's test extra:
[project.optional-dependencies]
test = [
"collective.redismemoize",
"fakeredis",
]
Add the layer#
REDIS_MEMOIZE_FIXTURE loads the cache chooser and points it at a fake server.
Put it in the bases of a testing layer, after the Plone fixture.
With pytest and pytest-plone, in your conftest.py:
from collective.redismemoize.testing import REDIS_MEMOIZE_FIXTURE
from plone.app.testing import IntegrationTesting
from plone.app.testing import PLONE_FIXTURE
from pytest_plone import fixtures_factory
pytest_plugins = ["pytest_plone"]
INTEGRATION_TESTING = IntegrationTesting(
bases=(PLONE_FIXTURE, REDIS_MEMOIZE_FIXTURE),
name="MyAddon:RedisIntegrationTesting",
)
globals().update(fixtures_factory(((INTEGRATION_TESTING, "integration"),)))
Write the tests#
Every test starts with an empty fake server, an empty RAM cache, and no learned routes.
Plone's own cached functions may store values while the test's site is set up, so look for the keys of your function only.
The server is available as REDIS_MEMOIZE_FIXTURE["redis_server"]:
from collective.redismemoize.testing import REDIS_MEMOIZE_FIXTURE
from plone.memoize import ram
import fakeredis
CALLS = []
def _key(fun, lang):
return lang
@ram.cache(_key)
def greeting(lang):
CALLS.append(lang)
return {"en": "Hello", "pt": "Olá"}[lang]
def stored_keys():
"""Return the keys Redis holds for ``greeting``."""
client = fakeredis.FakeRedis(server=REDIS_MEMOIZE_FIXTURE["redis_server"])
return client.keys("*:test_greeting.greeting:*")
def test_cached_in_redis(portal):
assert greeting("en") == "Hello"
assert greeting("en") == "Hello"
assert CALLS == ["en"]
assert len(stored_keys()) == 1
def test_each_test_starts_empty(portal):
assert stored_keys() == []
greeting("en")
assert CALLS == ["en", "en"]
The test suite of collective.redismemoize runs these two files as they are.
Without layers#
collective.redismemoize.testing.activate() and deactivate() do the same as the layer, for a pytest fixture or a test runner without layers.
activate returns the fake server.