Python: How do I mock datetime.utcnow()?

后端 未结 5 1061
梦如初夏
梦如初夏 2020-12-30 02:24

I have the below:

from datetime import datetime

def get_report_month_key():
    month_for_report = datetime.utcnow()
    return month_for_report.strftime(\"         


        
5条回答
  •  情深已故
    2020-12-30 02:52

    If your code is in another file you need to patch where the import happens (lets call your file file1.py):

    from file1 import get_report_month_key
    import mock
    
    @mock.patch("get_report_month_key.datetime.utcnow")
    def test_get_report_month_key(mock_utcnow):
        mock_utcnow.return_value = "your value"
        assert get_report_month_key() == "your expected value"
    

    Of course, I would wrap it with unittest framework.

提交回复
热议问题