Debian Codegraph @

tests/i/network/test_resolvers.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 import logging
18 from typing import AsyncGenerator, Callable
19 from unittest.mock import Mock
20
21 import pytest
22
23 from cylc.flow.data_store_mgr import EDGES, TASK_PROXIES
24 from cylc.flow.id import Tokens
25 from cylc.flow import CYLC_LOG
26 from cylc.flow.network.resolvers import Resolvers
27 from cylc.flow.scheduler import Scheduler
28 from cylc.flow.workflow_status import StopMode
29
30
31 @pytest.fixture
32 def flow_args():
33 return {
34 'workflows': [],
35 'exworkflows': [],
36 }
37
38
39 @pytest.fixture
40 def node_args():
41 return {
42 'workflows': [],
43 'exworkflows': [],
44 'ids': [],
45 'exids': [],
46 'states': [],
47 'exstates': [],
48 'mindepth': -1,
49 'maxdepth': -1,
50 }
51
52
53 @pytest.fixture(scope='module')
54 async def mock_flow(
55 mod_flow: Callable[..., str],
56 mod_scheduler: Callable[..., Scheduler],
57 mod_start,
58 ) -> AsyncGenerator[Scheduler, None]:
59 ret = Mock()
60 ret.id_ = mod_flow({
61 'scheduler': {
62 'allow implicit tasks': True
63 },
64 'scheduling': {
65 'initial cycle point': '2000',
66 'dependencies': {
67 'R1': 'prep => foo',
68 'PT12H': 'foo[-PT12H] => foo => bar'
69 }
70 }
71 })
72
73 ret.schd = mod_scheduler(ret.id_, paused_start=True)
74 async with mod_start(ret.schd):
75 ret.schd.pool.release_runahead_tasks()
76 ret.schd.data_store_mgr.initiate_data_model()
77
78 ret.owner = ret.schd.owner
79 ret.name = ret.schd.workflow
80 ret.id = list(ret.schd.data_store_mgr.data.keys())[0]
81 ret.resolvers = Resolvers(
82 ret.schd.data_store_mgr,
83 schd=ret.schd
84 )
85 ret.data = ret.schd.data_store_mgr.data[ret.id]
86 ret.node_ids = [
87 node.id
88 for node in ret.data[TASK_PROXIES].values()
89 ]
90 ret.edge_ids = [
91 edge.id
92 for edge in ret.data[EDGES].values()
93 ]
94
95 yield ret
96
97
98 async def test_get_workflows(mock_flow, flow_args):
99 """Test method returning workflow messages satisfying filter args."""
100 flow_args['workflows'].append({
101 'user': mock_flow.owner,
102 'workflow': mock_flow.name,
103 'workflow_sel': None,
104 })
105 flow_msgs = await mock_flow.resolvers.get_workflows(flow_args)
106 assert len(flow_msgs) == 1
107
108
109 async def test_get_nodes_all(mock_flow, node_args):
110 """Test method returning workflow(s) node message satisfying filter args.
111 """
112 node_args['workflows'].append({
113 'user': mock_flow.owner,
114 'workflow': mock_flow.name,
115 'workflow_sel': None,
116 })
117 node_args['states'].append('failed')
118 nodes = await mock_flow.resolvers.get_nodes_all(TASK_PROXIES, node_args)
119 assert len(nodes) == 0
120 node_args['states'] = []
121 node_args['ids'].append(Tokens(mock_flow.node_ids[0]))
122 nodes = [
123 n for n in await mock_flow.resolvers.get_nodes_all(
124 TASK_PROXIES, node_args)
125 if n in mock_flow.data[TASK_PROXIES].values()
126 ]
127 assert len(nodes) == 1
128
129
130 async def test_get_nodes_by_ids(mock_flow, node_args):
131 """Test method returning workflow(s) node messages
132 who's ID is a match to any given."""
133 node_args['workflows'].append({
134 'user': mock_flow.owner,
135 'workflow': mock_flow.name,
136 'workflow_sel': None
137 })
138 nodes = await mock_flow.resolvers.get_nodes_by_ids(TASK_PROXIES, node_args)
139 assert len(nodes) == 0
140
141 node_args['native_ids'] = mock_flow.node_ids
142 nodes = [
143 n
144 for n in await mock_flow.resolvers.get_nodes_by_ids(
145 TASK_PROXIES, node_args
146 )
147 if n in mock_flow.data[TASK_PROXIES].values()
148 ]
149 assert len(nodes) > 0
150
151
152 async def test_get_node_by_id(mock_flow, node_args):
153 """Test method returning a workflow node message
154 who's ID is a match to that given."""
155 node_args['id'] = Tokens(
156 user='me',
157 workflow='mine',
158 cycle='20500808T00',
159 task='jin',
160 ).id
161 node_args['workflows'].append({
162 'user': mock_flow.owner,
163 'workflow': mock_flow.name,
164 'workflow_sel': None
165 })
166 node = await mock_flow.resolvers.get_node_by_id(TASK_PROXIES, node_args)
167 assert node is None
168 node_args['id'] = mock_flow.node_ids[0]
169 node = await mock_flow.resolvers.get_node_by_id(TASK_PROXIES, node_args)
170 assert node in mock_flow.data[TASK_PROXIES].values()
171
172
173 async def test_get_edges_all(mock_flow, flow_args):
174 """Test method returning all workflow(s) edges."""
175 edges = [
176 e
177 for e in await mock_flow.resolvers.get_edges_all(flow_args)
178 if e in mock_flow.data[EDGES].values()
179 ]
180 assert len(edges) > 0
181
182
183 async def test_get_edges_by_ids(mock_flow, node_args):
184 """Test method returning workflow(s) edge messages
185 who's ID is a match to any given edge IDs."""
186 edges = await mock_flow.resolvers.get_edges_by_ids(node_args)
187 assert len(edges) == 0
188 node_args['native_ids'] = mock_flow.edge_ids
189 edges = [
190 e
191 for e in await mock_flow.resolvers.get_edges_by_ids(node_args)
192 if e in mock_flow.data[EDGES].values()
193 ]
194 assert len(edges) > 0
195
196
197 async def test_mutator(mock_flow, flow_args):
198 """Test the mutation method."""
199 flow_args['workflows'].append({
200 'user': mock_flow.owner,
201 'workflow': mock_flow.name,
202 'workflow_sel': None
203 })
204 args = {}
205 meta = {}
206 response = await mock_flow.resolvers.mutator(
207 None,
208 'pause',
209 flow_args,
210 args,
211 meta
212 )
213 assert response[0]['id'] == mock_flow.id
214
215
216 async def test_mutation_mapper(mock_flow):
217 """Test the mapping of mutations to internal command methods."""
218 meta = {}
219 response = await mock_flow.resolvers._mutation_mapper('pause', {}, meta)
220 assert response[0] is True # (True, command-uuid-str)
221 with pytest.raises(ValueError):
222 await mock_flow.resolvers._mutation_mapper('non_exist', {}, meta)
223
224
225 async def test_command_logging(mock_flow, caplog, log_filter):
226 """The command log message should include non-owner name."""
227
228 meta = {}
229
230 caplog.set_level(logging.INFO, CYLC_LOG)
231
232 await mock_flow.resolvers._mutation_mapper(
233 "stop",
234 {'mode': StopMode.REQUEST_CLEAN.value},
235 meta,
236 )
237 assert log_filter(contains='Command "stop" received')
238
239 # put_messages: only log for owner
240 kwargs = {
241 "task_job": "1/foo/01",
242 "event_time": "bedtime",
243 "messages": [[logging.CRITICAL, "it's late"]]
244 }
245 meta["auth_user"] = mock_flow.owner
246 await mock_flow.resolvers._mutation_mapper("put_messages", kwargs, meta)
247 assert not log_filter(contains='Command "put_messages" received:')
248
249 meta["auth_user"] = "Dr Spock"
250 await mock_flow.resolvers._mutation_mapper("put_messages", kwargs, meta)
251 assert log_filter(contains='Command "put_messages" received from Dr Spock')
252
253
254 async def test_command_validation_failure(
255 mock_flow,
256 caplog,
257 flow_args,
258 monkeypatch,
259 ):
260 """It should log command validation failures server side."""
261 caplog.set_level(logging.DEBUG, None)
262 flow_args['workflows'].append(
263 {
264 'user': mock_flow.owner,
265 'workflow': mock_flow.name,
266 'workflow_sel': None,
267 }
268 )
269
270 # submit a command with invalid arguments:
271 async def submit_invalid_command(verbosity=0):
272 monkeypatch.setattr('cylc.flow.flags.verbosity', verbosity)
273 caplog.clear()
274 return await mock_flow.resolvers.mutator(
275 None,
276 'stop',
277 flow_args,
278 {'task': 'cycle/task/job', 'mode': 'not-a-mode'},
279 {},
280 )
281
282 # submitting the invalid command should result in this error
283 msg = 'This command does not take job IDs: cycle/task/job'
284
285 # test submitting the command at *default* verbosity
286 response = await submit_invalid_command()
287
288 # the error should be sent back to the client:
289 assert response[0]['response'][1] == msg
290 # it should also be logged by the server:
291 assert caplog.records[-1].levelno == logging.WARNING
292 assert msg in caplog.records[-1].message
293
294 # test submitting the command at *debug* verbosity
295 response = await submit_invalid_command(verbosity=2)
296
297 # the error should be sent back to the client:
298 assert response[0]['response'][1] == msg
299 # it should be logged at the server
300 assert caplog.records[-2].levelno == logging.WARNING
301 assert msg in caplog.records[-2].message
302 # the traceback should also be logged
303 # (note traceback gets logged at the ERROR level and shows up funny in
304 # caplog)
305 assert caplog.records[-1].levelno == logging.ERROR
306 assert msg in caplog.records[-1].message