Pytest: Mocking time (test expiration)
In this application the user can "login" by providing their name and then call the access_page method within session_length seconds.
Because we know it internally users the time.time function to retreive the current time (in seconds since the epoch) we can replace that function with ours that will fake the time to be in the future.
examples/pytest/time-passed/app.py
import time class App(): session_length = 10 def login(self, username): self.username = username self.start = time.time() def access_page(self, username): if self.username == username and self.start + self.session_length > time.time(): return 'approved' else: return 'expired'
examples/pytest/time-passed/test_app.py
import app import time def test_app(monkeypatch): user = app.App() user.login('foo') assert user.access_page('foo') == 'approved' current = time.time() print(current) monkeypatch.setattr(app.time, 'time', lambda : current + 9) assert user.access_page('foo') == 'approved' monkeypatch.setattr(app.time, 'time', lambda : current + 11) assert user.access_page('foo') == 'expired'