"""Tests for runner module.""" from unittest.mock import MagicMock from unittest.mock import patch from garcon import activity from garcon import task from flows import runner @patch('flows.runner.log') @patch('flows.runner.logger') def test_wrap_task_with_logger_no_cid(logger, log): """Test that wrapping a task with no correlation ID uses old logger.""" task = MagicMock() context = {} wrapped_task = runner.wrap_task_with_logger(task, context) wrapped_task() assert not logger.OwsLoggingAdapter.called assert log.get_logger.called assert task.called @patch('flows.runner.log') @patch('flows.runner.logger') def test_wrap_task_with_logger_with_cid(logger, log): """Test wrapping a task with correlation ID uses ows logging adapter.""" task = MagicMock() mock_logger = MagicMock() log.get_logger.return_value = mock_logger context = {'correlation_id': '123'} wrapped_task = runner.wrap_task_with_logger(task, context) wrapped_task() logger.OwsLoggingAdapter.assert_called_with(mock_logger, context) assert log.get_logger.called assert task.called def test_synchronous_tasks(monkeypatch): """Test synchronous tasks.""" resp = dict(foo='bar') mock_tasks = [MagicMock(), MagicMock(return_value=resp)] mock_wrapper = MagicMock() mock_wrapper.side_effect = mock_tasks monkeypatch.setattr(runner, 'wrap_task_with_logger', mock_wrapper) monkeypatch.setattr(activity.Activity, '__init__', lambda self: None) monkeypatch.setattr(activity.Activity, 'heartbeat', lambda self: None) current_runner = runner.Sync(*mock_tasks) current_activity = activity.Activity() current_activity.hydrate(dict(runner=current_runner)) result = current_runner.execute(current_activity, dict()) assert len(current_runner.tasks) == 2 for current_task in task.flatten(current_runner.tasks, dict()): assert current_task.called mock_wrapper.assert_any_call(current_task, dict()) assert resp == result def test_aynchronous_tasks(monkeypatch): """Test asynchronous tasks.""" tasks = [MagicMock() for i in range(5)] tasks[2].return_value = dict(oi='mondo') tasks[4].return_value = dict(bonjour='monde') mock_wrapper = MagicMock() mock_wrapper.side_effect = tasks monkeypatch.setattr(runner, 'wrap_task_with_logger', mock_wrapper) monkeypatch.setattr(activity.Activity, '__init__', lambda self: None) monkeypatch.setattr(activity.Activity, 'heartbeat', lambda self: None) expected_response = dict( list(tasks[2].return_value.items()) + list(tasks[4].return_value.items())) workers = 2 current_runner = runner.Async(*tasks, max_workers=workers) assert current_runner.max_workers == workers assert len(current_runner.tasks) == len(tasks) current_activity = activity.Activity() current_activity.hydrate(dict(runner=current_runner)) context = dict(hello='world') resp = current_runner.execute(current_activity, context) for i, current_task in enumerate(tasks): assert current_task.called # ignore context, just assert task is wrapped assert mock_wrapper.call_args_list[i][0][0] == current_task assert resp == expected_response