How to taunt / set the system date in pytest?

In some of my tests, I have a problem that they fail in Travis due to problems with the time zone and time zone, so I want to make fun of the system time for my test. How can i do this?

+6
source share
3 answers

AFAIK, you cannot make fun of built-in methods.

One approach that I often did was to modify my code a bit so as not to use datetime directly to get the date, but somewhere a wrapper function:

 # mymodule.py def get_today(): return datetime.date.today() 

This makes it trivial only to mock it in your test:

 def test_something(): with mock.patch('mymodule.get_today', return_value=datetime.date(2014, 6, 2)): ... 

You can also use the freezegun module.

+7
source

There are two ways to do this:

  • Create a function that you will call instead of datetime.datetime.now() as suggested by Bruno, but there is another implementation here:

     import os import datetime def mytoday(): if 'MYDATE' in os.environ: return datetime.datetime.strptime(os.getenv('MYDATE'), '%m-%d-%Y').date() else: return datetime.date.today() 

    Then in your test, you are just the monkeypatch environment variable:

     import datetime def test_patched_date(monkeypatch): monkeytest.setenv('MYDATE', '05-31-2014') assert datetime.date.today() == datetime.date(2014, 5, 31) 
  • Monkeypatch datetime function:

     import datetime import pytest FAKE_TIME = datetime.datetime(2020, 12, 25, 17, 05, 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 
+6
source

@ Brian-Kruger answer is the best. I voted for his restoration. Meanwhile...

Use freezegun ( repo ).

From README:

 from freezegun import freeze_time @freeze_time("2012-01-14") def test(): assert datetime.datetime.now() == datetime.datetime(2012, 1, 14) 
+1
source

Source: https://habr.com/ru/post/970159/


All Articles