pytest - 测试期间假时间变化

问题描述 投票:0回答:1

我有以下代码来在测试期间设置假时间。

我想在测试期间更改时间。 也就是说,测试应该从 9:00 开始,然后像 10:00 一样继续。

from __future__ import annotations

import datetime
import logging

import pytest

LOGGER = logging.getLogger(__name__)


@pytest.fixture(params=[datetime.datetime(2020, 12, 25, 17, 5, 55)])
def patch_datetime_now(request, monkeypatch):
    class mydatetime(datetime.datetime):
        @classmethod
        def now(cls):
            return request.param

    class mydate(datetime.date):
        @classmethod
        def today(cls):
            return request.param.date()

    monkeypatch.setattr(datetime, "datetime", mydatetime)
    monkeypatch.setattr(datetime, "date", mydate)


@pytest.mark.usefixtures("patch_datetime_now")
@pytest.mark.parametrize(
    "patch_datetime_now", [(datetime.datetime(2020, 12, 9, 11, 22, 00))], indirect=True
)
def test_update_data():
    fakeTime = datetime.datetime.now()
    # Do some stuff

    # Change the fake time

    # Do some other stuff

如何更改考试期间的假时间? “datetime”在测试的代码中使用,因此不是更改“fakeTime”变量内容,而是更改日期时间模型返回的时间。

也许我需要完全改变模拟方法,我只是分享我当前的代码。

python datetime mocking pytest
1个回答
0
投票

按照@MrBeanBremen提供的另一个问题的答案我更新了我的代码,如下所示:

from __future__ import annotations import datetime import logging import pytest LOGGER = logging.getLogger(__name__) @pytest.fixture(params=[datetime.datetime(2020, 12, 25, 17, 5, 55)]) def patch_datetime_now(request, monkeypatch): def _delta(timedelta=None, **kwargs): """ Moves time fwd/bwd by the delta""" from datetime import timedelta as td if not timedelta: timedelta = td(**kwargs) request.param += timedelta class mydatetime(datetime.datetime): @classmethod def now(cls): return request.param @classmethod def delta(cls,*args,**kwargs): _delta(*args,**kwargs) class mydate(datetime.date): @classmethod def today(cls): return request.param.date() @classmethod def delta(cls,*args,**kwargs): _delta(*args,**kwargs) monkeypatch.setattr(datetime, "datetime", mydatetime) monkeypatch.setattr(datetime, "date", mydate) @pytest.mark.usefixtures("patch_datetime_now") @pytest.mark.parametrize( "patch_datetime_now", [(datetime.datetime(2020, 12, 9, 11, 22, 00))], indirect=True ) def test_update_data(): fakeTime = datetime.datetime.now() assert fakeTime == datetime.datetime(2020, 12, 9, 11, 22, 00) datetime.datetime.delta(hours=1,seconds=10) fakeTime = datetime.datetime.now() assert fakeTime == datetime.datetime(2020, 12, 9, 12, 22, 10)
    
© www.soinside.com 2019 - 2024. All rights reserved.