首页 > 解决方案 > 使 pytest 使用数据库的固定日期

问题描述

我正在使用 pytest 来测试一些数学函数。我希望数据库认为这是过去的日期。

例如,我会将数据库设置为 2019 年 8 月 1 日。

有没有办法用 pytest 配置它?

目前我的数据库是这样设置的:

@pytest.fixture(autouse=True)
def autouse_db(db):
    pass

标签: pythonpytest

解决方案


您使用什么 ORM 以及如何在查询中使用日期?如果您在查询中使用日期时间,可能的解决方案是制作简单的夹具,例如

from datetime import datetime
import pytest

@pytest.fixture(autouse=True)
def current_date():
    return datetime(2019, 8, 1, 0, 0, 0)

另一种方法是在测试中使用monkeyepatch datetime.now() 函数。归根结底,这一切都源于您如何从 python 与数据库进行交互。


推荐阅读