本文介紹了如何使用 py.test 對 python 的 datetime.datetime.now 進行猴子補丁?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我需要測試使用 datetime.datetime.now()
的函數(shù).最簡單的方法是什么?
I need to test functions which uses datetime.datetime.now()
. What is the easiest way to do this?
推薦答案
你需要monkeypatch datetime.now 函數(shù).在下面的示例中,我正在創(chuàng)建可以稍后在其他測試中重復(fù)使用的夾具:
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
這篇關(guān)于如何使用 py.test 對 python 的 datetime.datetime.now 進行猴子補丁?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!