Skip to content

Instantly share code, notes, and snippets.

@hectorcanto
Last active February 8, 2019 15:55
Show Gist options
  • Save hectorcanto/5f9651491922a59d862f54536bb7b07e to your computer and use it in GitHub Desktop.
Save hectorcanto/5f9651491922a59d862f54536bb7b07e to your computer and use it in GitHub Desktop.
Mock time.sleep and time.time to enhace your tests.
"""
A typical mock case is changing the output of time, date and datetime methods.
You may be tempted to make a time.sleep of N seconds. That's wasting your time.
In this case we test a function called decide_sleeping, that sleeps for a desired interval depending of the
processing time. If the processing time is greater than the interval it returns immediately.
This is useful for busy waiting loops.
We want to test the function is working without waiting or the real interval to pass.
In this case we mock both time.time (to return what we want) and time.sleep, to avoid waiting.
We well also use the "spy" mock inserts in the mocked method, os we can assert how it was called.
"""
import time
INTERVAL = 300
START_TIME = 1000
def decide_sleeping(start_time, interval):
elapsed_time = int(time.time() - start_time)
sleep_interval = int(interval - elapsed_time)
if sleep_interval > 0:
time.sleep(sleep_interval)
return
def test_do_sleep(mocker):
"""
mocker is the fixture for unittest.mock. When called, it will remove all the mocks after the given test
See more at https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch
"""
mocker.patch("time.time", return_value=START_TIME + INTERVAL - 100)
sleeper = mocker.patch("time.sleep")
decide_sleeping(START_TIME, interval=INTERVAL) # 1200 - 1000 = 200, needs to sleep 100 ms
sleeper.assert_called_with(100)
def test_no_sleep(mocker):
mocker.patch("time.time", return_value=START_TIME + INTERVAL + 200)
sleeper = mocker.patch("time.sleep")
decide_sleeping(START_TIME, interval=INTERVAL)
assert not sleeper.called
def test_time_goes_backwards(mocker):
# This probably cannot happen, but it is fun
mocker.patch("time.time", return_value=START_TIME - 100)
sleeper = mocker.patch("time.sleep")
decide_sleeping(START_TIME, interval=INTERVAL)
sleeper.assert_called_with(INTERVAL + 100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment