我使用Flask-Caching==1.3.3在我的Flask应用程序中实现了Redis缓存,但很明显,我的一些端点单元测试现在失败了,因为响应被缓存了,使得一些POST/PUT测试失败。
有没有在单元测试期间禁用缓存的好方法?我正在使用pytest==3.5.0
例如:这会失败,因为旧条目是从缓存中返回的:
def test_updating_biography(self):
"""Should update the current newest entry with the data in the JSON."""
response = self.app.put(
"/api/1.0/biography/",
data=json.dumps(
dict(
short="UnitTest Updated newest short",
full="UnitTest Updated newest full",
)
),
content_type="application/json"
)
get_bio = self.app.get("/api/1.0/biography/")
biodata = json.loads(get_bio.get_data().decode())
self.assertEquals(200, response.status_code)
self.assertEquals(200, get_bio.status_code)
> self.assertEquals("UnitTest Updated newest short", biodata["biography"][0]["short"])
E AssertionError: 'UnitTest Updated newest short' != 'UnitTest fourth short'
E - UnitTest Updated newest short
E + UnitTest fourth short
tests/biography/test_biography_views.py:100: AssertionError例如,我尝试过:
def setUp(self):
app.config["CACHE_TYPE"] = None
app.config["CACHE_REDIS_URL"] = ""
self.app = app.test_client()还有app.config["CACHE_TYPE"] = "null"和app.config["CACHE_TYPE"] = "",但它在单元测试中仍然使用缓存。
我试过这个,但它当然是在应用程序上下文之外:
@cache.cached(timeout=0)
def test_updating_biography(self):发布于 2018-03-23 22:37:41
正如评论中提到的,sytech的想法对我来说很有效,因为我只用这个redis测试了一个应用程序。显然,如果你在多个应用程序中使用一个共享的redis,这可能对你不起作用。但对于我的情况,它工作得很好,可以重复使用,没有问题:
import unittest
from flask_caching import Cache
from app import app, db
class TestBiographyViews(unittest.TestCase):
def setUp(self):
"""Add some test entries to the database, so we can test getting the latest one."""
# Clear redis cache completely
cache = Cache()
cache.init_app(app, config={"CACHE_TYPE": "redis"})
with app.app_context():
cache.clear()
self.app = app.test_client()以上就是您需要的全部内容。其余的测试用例可以正常运行。这对我很有效。
https://stackoverflow.com/questions/49451820
复制相似问题