Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

advance time artificially in pytest

Tags:

python

pytest

I have code that depends on elapsed time (for instance: If 10 minutes has passed)

What is the best way to simulate this in pytest? Monkey patching methods in module time?

Example code (the tested code - a bit schematic but conveys the message):

current_time = datetime.datetime.utcnow()
retry_time = current_time + datetime.timedelta(minutes=10)
#time_in_db represents time extracted from DB
if time_in_db > retry_time:
    #perform the retry
like image 766
Boaz Avatar asked Oct 15 '15 13:10

Boaz


People also ask

What is the pytest syntax to skip a test?

The simplest way to skip a test function is to mark it with the skip decorator which may be passed an optional reason : @pytest. mark. skip(reason="no way of currently testing this") def test_the_unknown(): ...

Can you use mock with pytest?

In pytest , mocking can replace the return value of a function within a function. This is useful for testing the desired function and replacing the return value of a nested function within that desired function we are testing.

Which command can be used to show all available fixtures?

Additionally, if you wish to display a list of fixtures for each test, try the --fixtures-per-test flag.


1 Answers

FreezeGun is probably the easiest solution.

Sample code from its readme:

from freezegun import freeze_time

@freeze_time("2012-01-14")
def test():
    assert datetime.datetime.now() == datetime.datetime(2012, 01, 14)
like image 96
Josh Kelley Avatar answered Oct 19 '22 16:10

Josh Kelley