python - 使pytest对数据库使用固定日期

标签 python pytest

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

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

有没有办法用 pytest 配置它?

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

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

最佳答案

使用freezegun用于 monkeypatching datetime 函数。示例:

import datetime
import pytest
from freezegun import freeze_time


@pytest.fixture
def fast_forward_to_2038():
    # use me to test the year 2038 problem
    with freeze_time('2038-01-19 03:14:08'):
        # year 2038 problem should be reproducible now
        yield


@pytest.mark.usefixtures('fast_forward_to_2038')
def test_2038_problem():
    assert datetime.datetime.now() == datetime.datetime(2038, 1, 19, 03, 14, 08)
    ...

查看包中的更多示例 readme .

关于python - 使pytest对数据库使用固定日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57579659/

相关文章:

python - 如何测试自定义 excepthook 是否已正确安装?

python - 如何在 If else 语句上运行 Pytest?

python - Pybind11 : "ImportError: DLL not found" when trying to import *. Python解释器中的pyd

python - VBO PyOpenGL 点

python不会创建线程?

python - 是否可以使用 Pytest 运行 Robot Framework 单元测试?

python - 是否可以在 pytest 中并行执行相同的测试?

python - 使用 Python 生成 Amazon S3 CORS 签名

python - 模块未找到错误: No module named 'tia.analysis.model'

python - 在 pytest 中运行 Jupyter notebook 测试。操作系统错误