async def test_scheduler_async_run_fail(caplog): sched = util.Scheduler("xxx") i = [] async def action(): i.append(0) await asyncio.sleep(0) raise Exception("Marker") sched.add_action(action, 0.05, 0) while len(i) == 0: await asyncio.sleep(0.01) sched.stop() length = len(i) await asyncio.sleep(0.1) assert len(i) == length assert not sched._executing_tasks[action] print(caplog.messages) log_contains(caplog, "inmanta.util", logging.ERROR, "Uncaught exception while executing scheduled action")
async def test_scheduler_stop(caplog): sched = util.Scheduler("stop") i = [] async def action(): i.append(0) return "A" sched.add_action(action, 0.05, 0) while len(i) == 0: await asyncio.sleep(0.01) sched.stop() length = len(i) await asyncio.sleep(0.1) assert len(i) == length no_error_in_logs(caplog) caplog.clear() sched.add_action(action, 0.05, 0) assert "Scheduling action 'action', while scheduler is stopped" in caplog.messages assert not sched._executing_tasks[action]
async def test_scheduler_cancel_executing_tasks() -> None: """ Verify that executing tasks are cancelled when the scheduler is stopped. """ @dataclasses.dataclass class TaskStatus: task_is_executing: bool = False task_was_cancelled: bool = False task_status = TaskStatus() async def action(): task_status.task_is_executing = True try: await asyncio.sleep(1000) except asyncio.CancelledError: task_status.task_was_cancelled = True raise sched = util.Scheduler("xxx") sched.add_action(action, interval=1000, initial_delay=0) await util.retry_limited(lambda: task_status.task_is_executing, timeout=10) assert task_status.task_is_executing assert not task_status.task_was_cancelled assert sched._executing_tasks[action] sched.stop() await util.retry_limited(lambda: task_status.task_was_cancelled, timeout=10) assert not sched._executing_tasks[action]
def __init__(self, name: str, timeout: int = 120, reconnect_delay: int = 5): super().__init__(name) self._transport = client.RESTClient self._sched = util.Scheduler("session endpoint") self._env_id: Optional[uuid.UUID] = None self.sessionid: uuid.UUID = uuid.uuid1() self.running: bool = True self.server_timeout = timeout self.reconnect_delay = reconnect_delay self.add_call_target(self)
async def test_scheduler_remove(caplog): sched = util.Scheduler("remove") i = [] async def action(): i.append(0) sched.add_action(action, 0.05, 0) while len(i) == 0: await asyncio.sleep(0.01) sched.remove(action) length = len(i) await asyncio.sleep(0.1) assert len(i) == length no_error_in_logs(caplog)
async def test_scheduler_run_async(caplog): sched = util.Scheduler("xxx") i = [] async def action(): i.append(0) sched.add_action(action, 0.05, 0) while len(i) == 0: await asyncio.sleep(0.01) sched.stop() length = len(i) await asyncio.sleep(0.1) assert len(i) == length assert not sched._executing_tasks[action] no_error_in_logs(caplog)