本文介紹了如何使用 py.test 對 python 的 datetime.datetime.now 進行猴子補丁?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我需要測試使用 datetime.datetime.now()
的函數.最簡單的方法是什么?
I need to test functions which uses datetime.datetime.now()
. What is the easiest way to do this?
推薦答案
你需要monkeypatch datetime.now 函數.在下面的示例中,我正在創建可以稍后在其他測試中重復使用的夾具:
You need to monkeypatch datetime.now function. In example below, I'm creating fixture which I can re-use later in other tests:
import datetime
import pytest
FAKE_TIME = datetime.datetime(2020, 12, 25, 17, 5, 55)
@pytest.fixture
def patch_datetime_now(monkeypatch):
class mydatetime:
@classmethod
def now(cls):
return FAKE_TIME
monkeypatch.setattr(datetime, 'datetime', mydatetime)
def test_patch_datetime(patch_datetime_now):
assert datetime.datetime.now() == FAKE_TIME
這篇關于如何使用 py.test 對 python 的 datetime.datetime.now 進行猴子補丁?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!