pytest期间禁用缓存的Flask?

2024-09-27 20:16:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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

我试过举例:

^{pr2}$

以及app.config["CACHE_TYPE"] = "null"和{},但它仍在单元测试中使用缓存。在

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

@cache.cached(timeout=0)
def test_updating_biography(self):

Tags: thetestselfjsonappdataget单元测试
1条回答
网友
1楼 · 发布于 2024-09-27 20:16:36

正如评论中提到的,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()

以上就是你所需要的。其余的测试用例可以是正常的。对我有用。在

相关问题 更多 >

    热门问题