为什么在单元测试(manage.py 测试)期间访问 Django 缓存会生成 datetime.datetime 对象而不是预期值?

发布于 2025-01-12 03:34:03 字数 585 浏览 5 评论 0原文

我有一个 Django 应用程序,我正在尝试为使用缓存的函数/方法创建单元测试。我的测试使用 python manage.py test 运行,使用的 Docker 容器与我在本地运行应用程序时使用的容器相同。我正在测试的函数/方法包含类似于以下内容的行:

from django.core.cache import cache
...
def some_function():
    ...
    cache.set('test', ('hello', 'world'))
    retrieved = cache.get('test')
    ...

我希望 retrieved 是我从缓存中检索的值(在本例中为 ('hello', '世界'));然而,retrieve 总是一个 datetime.datetime 对象。这种情况发生在各种不同的缓存后端,包括 django.core.cache.backends.locmem.LocMemCache 和 django_redis.cache.RedisCache。如何更正此缓存行为以进行测试?

I have a Django app, and I'm trying to create unit tests for functions/methods that work with the cache. My tests are run using python manage.py test using the same Docker container that I use for running the app locally. The functions/methods I'm testing contain lines that are similar to the following:

from django.core.cache import cache
...
def some_function():
    ...
    cache.set('test', ('hello', 'world'))
    retrieved = cache.get('test')
    ...

I expect retrieved to be the value that I retrieved from the cache (in this case, ('hello', 'world')); however, retrieved is somehow always a datetime.datetime object. This happens for various different cache backends, including django.core.cache.backends.locmem.LocMemCache and django_redis.cache.RedisCache. How can I correct this cache behavior for tests?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文