首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Flask with redis -在pytest期间禁用缓存?

Flask with redis -在pytest期间禁用缓存?
EN

Stack Overflow用户
提问于 2018-03-23 22:21:57
回答 1查看 1.3K关注 0票数 1

我使用Flask-Caching==1.3.3在我的Flask应用程序中实现了Redis缓存,但很明显,我的一些端点单元测试现在失败了,因为响应被缓存了,使得一些POST/PUT测试失败。

有没有在单元测试期间禁用缓存的好方法?我正在使用pytest==3.5.0

例如:这会失败,因为旧条目是从缓存中返回的:

代码语言:javascript
复制
   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

例如,我尝试过:

代码语言:javascript
复制
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"] = "",但它在单元测试中仍然使用缓存。

我试过这个,但它当然是在应用程序上下文之外:

代码语言:javascript
复制
@cache.cached(timeout=0)
def test_updating_biography(self):
EN

回答 1

Stack Overflow用户

发布于 2018-03-23 22:37:41

正如评论中提到的,sytech的想法对我来说很有效,因为我只用这个redis测试了一个应用程序。显然,如果你在多个应用程序中使用一个共享的redis,这可能对你不起作用。但对于我的情况,它工作得很好,可以重复使用,没有问题:

代码语言:javascript
复制
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()

以上就是您需要的全部内容。其余的测试用例可以正常运行。这对我很有效。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49451820

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档