本文介紹了Python:如何模擬 datetime.utcnow()?的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我有以下內(nèi)容:
from datetime import datetime
def get_report_month_key():
month_for_report = datetime.utcnow()
return month_for_report.strftime("%Y%m")
我如何模擬 datetime.utcnow() 以便我可以在這個(gè)函數(shù)上編寫單元測(cè)試?
How do I mock datetime.utcnow() so that I can write unit test on this function?
嘗試閱讀此一個(gè)但是我無(wú)法讓它在 utcnow() 上為我工作
Tried reading this one but I am unable to get it working for me on utcnow()
推薦答案
在你的測(cè)試文件中:
from yourfile import get_report_month_key
import mock
import unittest
from datetime import datetime
class TestCase(unittest.TestCase):
@mock.patch('yourfile.datetime')
def test_dt(self, mock_dt):
mock_dt.utcnow = mock.Mock(return_value=datetime(1901, 12, 21))
r = get_report_month_key()
self.assertEqual('190112', r)
這篇關(guān)于Python:如何模擬 datetime.utcnow()?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!