pytest - 测试期间假时间变化
我有以下代码来在测试期间设置假时间。
我想在测试期间更改时间。也就是说,测试应该从 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
按照这个答案@MrBeanBremen提供的另一个问题 我像这样更新了我的代码:
Following this answer on another question provided by @MrBeanBremen I updated my code like this: