2022-04-28 00:57:49 +02:00
|
|
|
import datetime
|
|
|
|
import queue
|
2021-03-09 00:18:33 +01:00
|
|
|
import pytest
|
|
|
|
import time
|
|
|
|
|
2022-04-28 00:57:49 +02:00
|
|
|
from dateutil.tz import gettz
|
|
|
|
from mock import patch
|
|
|
|
|
2021-03-09 00:18:33 +01:00
|
|
|
test_timeout = 10
|
2022-04-28 00:57:49 +02:00
|
|
|
cron_queue = queue.Queue()
|
|
|
|
|
|
|
|
|
|
|
|
class MockDatetime(datetime.datetime):
|
|
|
|
timedelta = datetime.timedelta()
|
2021-03-09 00:18:33 +01:00
|
|
|
|
2022-04-28 00:57:49 +02:00
|
|
|
@classmethod
|
|
|
|
def now(cls):
|
|
|
|
return super().now(tz=gettz()) + cls.timedelta
|
2021-03-09 00:18:33 +01:00
|
|
|
|
|
|
|
|
2022-04-28 00:57:49 +02:00
|
|
|
def _test_cron_queue(expected_msg: str):
|
|
|
|
msg = None
|
|
|
|
test_start = time.time()
|
|
|
|
while time.time() - test_start <= test_timeout and msg != expected_msg:
|
|
|
|
try:
|
|
|
|
msg = cron_queue.get(block=True, timeout=test_timeout)
|
|
|
|
except queue.Empty:
|
|
|
|
break
|
|
|
|
|
|
|
|
assert msg == expected_msg, 'The expected cronjob has not been executed'
|
2021-03-09 00:18:33 +01:00
|
|
|
|
|
|
|
|
2022-04-28 00:57:49 +02:00
|
|
|
def test_cron_execution():
|
2021-03-09 00:18:33 +01:00
|
|
|
"""
|
|
|
|
Test that the cronjob in ``../etc/scripts/test_cron.py`` runs successfully.
|
|
|
|
"""
|
2022-04-28 00:57:49 +02:00
|
|
|
_test_cron_queue('cron_test')
|
|
|
|
|
|
|
|
|
|
|
|
def test_cron_execution_upon_system_clock_change():
|
|
|
|
"""
|
|
|
|
Test that the cronjob runs at the right time even upon DST or other
|
|
|
|
system clock changes.
|
|
|
|
"""
|
|
|
|
# Mock datetime.datetime with a class that has overridable timedelta
|
|
|
|
patcher = patch('datetime.datetime', MockDatetime)
|
2021-03-09 00:18:33 +01:00
|
|
|
|
2022-04-28 00:57:49 +02:00
|
|
|
try:
|
|
|
|
patcher.start()
|
|
|
|
time.sleep(1)
|
|
|
|
# Simulate a +1hr shift on the system clock
|
|
|
|
MockDatetime.timedelta = datetime.timedelta(hours=1)
|
|
|
|
time.sleep(1)
|
|
|
|
finally:
|
|
|
|
patcher.stop()
|
2021-03-09 00:18:33 +01:00
|
|
|
|
2022-04-28 00:57:49 +02:00
|
|
|
# Ensure that the cronjob that was supposed to run in an hour is now running
|
|
|
|
_test_cron_queue('cron_1hr_test')
|
2021-03-09 00:18:33 +01:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
pytest.main()
|
|
|
|
|
|
|
|
|
|
|
|
# vim:sw=4:ts=4:et:
|