I have a package:
- package/
- __init__.py
- cache.py
- module1.py
- module2.py
- tests/
- test_module1.py
- test_module2.py
- conftest.py
both module1 and module2 are importing from cache.py:
from package.cache import cache
@cache()
def foo():
...
by default, cache is using file based caching provied by dogpile.cache, however when running tests, I'd like to mock cache with a memory based caching which is also supported by dogpile.cache.
here is what I'm tring:
# conftest.py
import pytest
@pytest.fixture(autouse=True)
def patch_cache(monkeypatch):
from dogpile.cache import make_region
m_cache = make_region().configure('dogpile.cache.memory')
monkeypatch.setattr('package.cache.cache', m_cache)
as you can see, I created a fixture in which using monkeypatch to replace cache with m_cache
however, this doesn't work, when I run test with py.test, they're still using the old file based cache. is there anything wrong?
@cache() is applied when the module is imported, because the decorator is called at the top level of the module. If you monkeypatch it after that module is imported, your patched in version won't be applied.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With