pytest - 测试期间假时间变化

发布于 2025-01-15 19:15:21 字数 1139 浏览 1 评论 0原文

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

我想在测试期间更改时间。也就是说,测试应该从 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”变量内容,而是更改日期时间模型返回的时间。

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

I have the following code to set a faketime during tests.

I'ld like to change the time during a test. That is, the test should start at 9:00 for instance and then continue as if it is 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

How can I change the fake time during the test. The 'datetime' is used inside the code tested, so it's not about changing the "fakeTime" variable contents, but about changing the time returned by the datetime mockup.

Maybe I need to change the mocking method completely, I am just sharing my current code.

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

好听的两个字的网名 2025-01-22 19:15:21

按照这个答案@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)


# Test & Example using the fixture above
@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():
    # The test starts with the fake time set in the parameter above
    fakeTime = datetime.datetime.now()
    # Assert (verify) that the fake time is used
    assert fakeTime == datetime.datetime(2020, 12, 9, 11, 22, 00)
    # Move the fake time 1 hour and 10 seconds in the future
    datetime.datetime.delta(hours=1,seconds=10)
    # Get the new fake time
    fakeTime = datetime.datetime.now()
    # Assert (verify) that the fake time was updated as expected
    assert fakeTime == datetime.datetime(2020, 12, 9, 12, 22, 10)

Following this answer on another question provided by @MrBeanBremen I updated my code like this:

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)


# Test & Example using the fixture above
@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():
    # The test starts with the fake time set in the parameter above
    fakeTime = datetime.datetime.now()
    # Assert (verify) that the fake time is used
    assert fakeTime == datetime.datetime(2020, 12, 9, 11, 22, 00)
    # Move the fake time 1 hour and 10 seconds in the future
    datetime.datetime.delta(hours=1,seconds=10)
    # Get the new fake time
    fakeTime = datetime.datetime.now()
    # Assert (verify) that the fake time was updated as expected
    assert fakeTime == datetime.datetime(2020, 12, 9, 12, 22, 10)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文