Debian Codegraph @

cylc/flow/xtriggers/xrandom.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 from random import random, randint
18 from time import sleep
19 from typing import Any, Dict, Tuple
20
21 from cylc.flow.exceptions import WorkflowConfigError
22
23
24 COLORS = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]
25 SIZES = ["tiny", "small", "medium", "large", "huge", "humongous"]
26
27
28 def xrandom(
29 percent: float, secs: int = 0, _: Any = None
30 ) -> Tuple[bool, Dict[str, str]]:
31 """Random xtrigger, with configurable sleep and percent success.
32
33 Sleep for ``sec`` seconds, and report satisfied with ``percent``
34 likelihood.
35
36 The ``_`` argument is not used in the function code, but can be used to
37 specialize the function signature to cycle point or task.
38
39 Args:
40 percent:
41 Percent likelihood of passing.
42 secs:
43 Seconds to sleep before starting the trigger.
44 _:
45 Used to allow users to specialize the trigger with extra
46 parameters.
47
48 Returns:
49 tuple: (satisfied, results)
50
51 satisfied:
52 True if ``satisfied`` else ``False``.
53 results:
54 A dictionary containing the following keys:
55
56 ``COLOR``
57 A random colour (e.g. red, orange, ...).
58 ``SIZE``
59 A random size (e.g. small, medium, ...).
60
61 Examples:
62 If the percent is zero, it returns that the trigger condition was
63 not satisfied, and an empty dictionary.
64
65 >>> xrandom(0, 0)
66 (False, {})
67
68 If the percent is not zero, but the random percent success is not met,
69 then it also returns that the trigger condition was not satisfied,
70 and an empty dictionary.
71
72 >>> import sys
73 >>> mocked_random = lambda: 0.3
74 >>> sys.modules[__name__].random = mocked_random
75 >>> xrandom(15.5, 0)
76 (False, {})
77
78 Finally, if the percent is not zero, and the random percent success is
79 met, then it returns that the trigger condition was satisfied, and a
80 dictionary containing random colour and size as result.
81
82 >>> import sys
83 >>> mocked_random = lambda: 0.9
84 >>> sys.modules[__name__].random = mocked_random
85 >>> mocked_randint = lambda x, y: 1
86 >>> sys.modules[__name__].randint = mocked_randint
87 >>> xrandom(99.99, 0)
88 (True, {'COLOR': 'orange', 'SIZE': 'small'})
89
90 """
91 sleep(float(secs))
92 results = {}
93 satisfied = random() < float(percent) / 100 # nosec: B311
94 if satisfied:
95 results = {
96 'COLOR': COLORS[randint(0, len(COLORS) - 1)], # nosec: B311
97 'SIZE': SIZES[randint(0, len(SIZES) - 1)] # nosec: B311
98 }
99 return satisfied, results
100
101
102 def validate(args: Dict[str, Any]):
103 """Validate the args that xrandom is called with.
104
105 Cylc calls this function automatically when parsing the workflow.
106
107 Here we specify the rules for args are:
108
109 * percent: Must be 0 ≤ x ≤ 100
110 * secs: Must be an integer.
111 """
112 percent = args['percent']
113 if (
114 not isinstance(percent, (float, int))
115 or not (0 <= percent <= 100)
116 ):
117 raise WorkflowConfigError(
118 "'percent' should be a float between 0 and 100"
119 )
120
121 secs = args['secs']
122 if not isinstance(secs, int):
123 raise WorkflowConfigError("'secs' should be an integer")