Debian Codegraph @

tests/u/test_xtrigger_mgr.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 import pytest
19
20 from cylc.flow import CYLC_LOG
21 from cylc.flow.cycling.iso8601 import ISO8601Point, ISO8601Sequence, init
22 from cylc.flow.exceptions import XtriggerConfigError
23 from cylc.flow.id import Tokens
24 from cylc.flow.subprocctx import SubFuncContext
25 from cylc.flow.task_proxy import TaskProxy
26 from cylc.flow.taskdef import TaskDef
27 from cylc.flow.xtrigger_mgr import (
28 RE_STR_TMPL,
29 XtriggerCollator
30 )
31
32
33 def test_extract_templates():
34 """Test escaped templates in xtrigger arg string.
35
36 They should be left alone and passed into the function as string
37 literals, not identified as template args.
38 """
39 assert (
40 RE_STR_TMPL.findall('%(cat)s, %(dog)s, %%(fish)s') == ['cat', 'dog']
41 )
42
43
44 def test_add_missing_func():
45 """Test for adding an xtrigger that can't be found."""
46 xtriggers = XtriggerCollator()
47 xtrig = SubFuncContext(
48 label="fooble",
49 func_name="fooble123", # no such module
50 func_args=["name", "age"],
51 func_kwargs={"location": "soweto"}
52 )
53 with pytest.raises(
54 XtriggerConfigError,
55 match=r"\[@xtrig\] fooble123\(.*\)\nNo module named 'fooble123'"
56 ):
57 xtriggers.add_trig("xtrig", xtrig, 'fdir')
58
59
60 def test_add_xtrigger():
61 """Test for adding and validating an xtrigger."""
62 xtriggers = XtriggerCollator()
63 xtrig = SubFuncContext(
64 label="echo",
65 func_name="echo",
66 func_args=["name", "age"],
67 func_kwargs={"location": "soweto"}
68 )
69 with pytest.raises(
70 XtriggerConfigError,
71 match="Requires 'succeed=True/False' arg"
72 ):
73 xtriggers.add_trig("xtrig", xtrig, 'fdir')
74
75 xtrig = SubFuncContext(
76 label="echo",
77 func_name="echo",
78 func_args=["name", "age"],
79 func_kwargs={"location": "soweto", "succeed": True}
80 )
81 xtriggers.add_trig("xtrig", xtrig, 'fdir')
82 assert xtrig == xtriggers.functx_map["xtrig"]
83
84
85 def test_add_xtrigger_with_template_good():
86 """Test adding an xtrigger with a valid string template arg value."""
87 xtriggers = XtriggerCollator()
88 xtrig = SubFuncContext(
89 label="echo",
90 func_name="echo",
91 func_args=["name", "%(point)s"], # valid template
92 func_kwargs={"location": "soweto", "succeed": True}
93 )
94 xtriggers.add_trig("xtrig", xtrig, 'fdir')
95 assert xtrig == xtriggers.functx_map["xtrig"]
96
97
98 def test_add_xtrigger_with_template_bad():
99 """Test adding an xtrigger with an invalid string template arg value."""
100 xtriggers = XtriggerCollator()
101 xtrig = SubFuncContext(
102 label="echo",
103 func_name="echo",
104 func_args=["name", "%(point)s"],
105 # invalid template:
106 func_kwargs={"location": "%(what_is_this)s", "succeed": True}
107 )
108 with pytest.raises(
109 XtriggerConfigError,
110 match="Illegal template in xtrigger: what_is_this"
111 ):
112 xtriggers.add_trig("xtrig", xtrig, 'fdir')
113
114
115 def test_add_xtrigger_with_deprecated_params(
116 caplog: pytest.LogCaptureFixture
117 ):
118 """It should flag deprecated template variables."""
119 xtriggers = XtriggerCollator()
120 xtrig = SubFuncContext(
121 label="echo",
122 func_name="echo",
123 func_args=[1, "name", "%(suite_name)s"],
124 func_kwargs={"succeed": True}
125 )
126 caplog.set_level(logging.WARNING, CYLC_LOG)
127 xtriggers.add_trig("xtrig", xtrig, 'fdir')
128 assert caplog.messages == [
129 'Xtrigger "xtrig" uses deprecated template variables: suite_name'
130 ]
131
132
133 def test_load_xtrigger_for_restart(xtrigger_mgr):
134 """Test loading an xtrigger for restart.
135
136 The function is loaded from database, where the value is formatted
137 as JSON."""
138 row = "get_name", "{\"name\": \"function\"}"
139 xtrigger_mgr.load_xtrigger_for_restart(row_idx=0, row=row)
140 assert xtrigger_mgr.sat_xtrig["get_name"]["name"] == "function"
141
142
143 def test_load_invalid_xtrigger_for_restart(xtrigger_mgr):
144 """Test loading an invalid xtrigger for restart.
145
146 It simulates that the DB has a value that is not valid JSON.
147 """
148 row = "get_name", "{name: \"function\"}" # missing double quotes
149 with pytest.raises(ValueError):
150 xtrigger_mgr.load_xtrigger_for_restart(row_idx=0, row=row)
151
152
153 def test_housekeeping_nothing_satisfied(xtrigger_mgr):
154 """The housekeeping method makes sure only satisfied xtrigger function
155 are kept."""
156 row = "get_name", "{\"name\": \"function\"}"
157 # now XtriggerManager#sat_xtrigger will contain the get_name xtrigger
158 xtrigger_mgr.add_xtriggers(XtriggerCollator())
159 xtrigger_mgr.load_xtrigger_for_restart(row_idx=0, row=row)
160 assert xtrigger_mgr.sat_xtrig
161 xtrigger_mgr.housekeep([])
162 assert not xtrigger_mgr.sat_xtrig
163
164
165 def test_housekeeping_with_xtrigger_satisfied(xtrigger_mgr):
166 """The housekeeping method makes sure only satisfied xtrigger function
167 are kept."""
168
169 xtriggers = XtriggerCollator()
170
171 xtrig = SubFuncContext(
172 label="get_name",
173 func_name="echo",
174 func_args=[],
175 func_kwargs={"succeed": True}
176 )
177 xtriggers.add_trig("get_name", xtrig, 'fdir')
178 xtrigger_mgr.add_xtriggers(xtriggers)
179
180 xtrig.out = "[\"True\", {\"name\": \"Yossarian\"}]"
181 tdef = TaskDef(
182 name="foo",
183 rtcfg={'completion': None},
184 start_point=1,
185 initial_point=1,
186 )
187
188 init()
189 sequence = ISO8601Sequence('P1D', '2019')
190 tdef.xtrig_labels[sequence] = ["get_name"]
191 start_point = ISO8601Point('2019')
192 itask = TaskProxy(Tokens('~user/workflow'), tdef, start_point)
193 # pretend the function has been activated
194
195 xtrigger_mgr.active.append(xtrig.get_signature())
196
197 xtrigger_mgr.callback(xtrig)
198 assert xtrigger_mgr.sat_xtrig
199
200 xtrigger_mgr.housekeep([itask])
201 # here we still have the same number as before
202 assert xtrigger_mgr.sat_xtrig
203
204
205 def test__call_xtriggers_async(xtrigger_mgr):
206 """Test _call_xtriggers_async"""
207
208 xtriggers = XtriggerCollator()
209
210 # the echo1 xtrig (not satisfied)
211 echo1_xtrig = SubFuncContext(
212 label="echo1",
213 func_name="echo",
214 func_args=[],
215 func_kwargs={"succeed": False}
216 )
217
218 echo1_xtrig.out = "[\"True\", {\"name\": \"herminia\"}]"
219 xtriggers.add_trig("echo1", echo1_xtrig, "fdir")
220
221 # the echo2 xtrig (satisfied through callback later)
222 echo2_xtrig = SubFuncContext(
223 label="echo2",
224 func_name="echo",
225 func_args=[],
226 func_kwargs={"succeed": True}
227 )
228 echo2_xtrig.out = "[\"True\", {\"name\": \"herminia\"}]"
229 xtriggers.add_trig("echo2", echo2_xtrig, "fdir")
230
231 xtrigger_mgr.add_xtriggers(xtriggers)
232
233 # create a task
234 tdef = TaskDef(
235 name="foo",
236 rtcfg={'completion': None},
237 start_point=1,
238 initial_point=1
239 )
240 init()
241 sequence = ISO8601Sequence('P1D', '2000')
242 tdef.xtrig_labels[sequence] = ["echo1", "echo2"]
243 # cycle point for task proxy
244 init()
245 start_point = ISO8601Point('2019')
246 # create task proxy
247 itask = TaskProxy(Tokens('~user/workflow'), tdef, start_point)
248
249 # we start with no satisfied xtriggers, and nothing active
250 assert len(xtrigger_mgr.sat_xtrig) == 0
251 assert len(xtrigger_mgr.active) == 0
252
253 # after calling the first time, we get two active
254 xtrigger_mgr.call_xtriggers_async(itask)
255 assert len(xtrigger_mgr.sat_xtrig) == 0
256 assert len(xtrigger_mgr.active) == 2
257
258 # calling again does not change anything
259 xtrigger_mgr.call_xtriggers_async(itask)
260 assert len(xtrigger_mgr.sat_xtrig) == 0
261 assert len(xtrigger_mgr.active) == 2
262
263 # now we call callback manually as the proc_pool we passed is a mock
264 # then both should be satisfied
265 xtrigger_mgr.callback(echo1_xtrig)
266 xtrigger_mgr.callback(echo2_xtrig)
267 # so both were satisfied, and nothing is active
268 assert len(xtrigger_mgr.sat_xtrig) == 2
269 assert len(xtrigger_mgr.active) == 0
270
271 # calling satisfy_xtriggers again still does not change anything
272 xtrigger_mgr.call_xtriggers_async(itask)
273 assert len(xtrigger_mgr.sat_xtrig) == 2
274 assert len(xtrigger_mgr.active) == 0
275
276
277 def test_callback_not_active(xtrigger_mgr):
278 """Test callback with no active contexts."""
279 # calling callback with a SubFuncContext with none active
280 # results in a ValueError
281
282 get_name = SubFuncContext(
283 label="get_name",
284 func_name="get_name",
285 func_args=[],
286 func_kwargs={}
287 )
288 with pytest.raises(ValueError):
289 xtrigger_mgr.callback(get_name)
290
291
292 def test_callback_invalid_json(xtrigger_mgr):
293 """Test callback with invalid JSON."""
294 get_name = SubFuncContext(
295 label="get_name",
296 func_name="get_name",
297 func_args=[],
298 func_kwargs={}
299 )
300 get_name.out = "{no_quotes: \"mom!\"}"
301 xtrigger_mgr.active.append(get_name.get_signature())
302 xtrigger_mgr.callback(get_name)
303 # this means that the xtrigger was not satisfied
304 # TODO: this means site admins are only aware of this if they
305 # look at the debug log. Is that OK?
306 assert not xtrigger_mgr.sat_xtrig
307
308
309 def test_callback(xtrigger_mgr):
310 """Test callback."""
311 get_name = SubFuncContext(
312 label="get_name",
313 func_name="get_name",
314 func_args=[],
315 func_kwargs={}
316 )
317 get_name.out = "[\"True\", \"1\"]"
318 xtrigger_mgr.active.append(get_name.get_signature())
319 xtrigger_mgr.callback(get_name)
320 # this means that the xtrigger was satisfied
321 assert xtrigger_mgr.sat_xtrig