File: test_broadcast.py

package info (click to toggle)
cylc-flow 8.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 14,368 kB
  • sloc: python: 87,751; sh: 17,109; sql: 233; xml: 171; javascript: 78; lisp: 55; makefile: 11
file content (316 lines) | stat: -rw-r--r-- 10,450 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from ansimarkup import strip as cstrip

from cylc.flow.network.client import WorkflowRuntimeClient
from cylc.flow.option_parsers import Options
from cylc.flow.rundb import CylcWorkflowDAO
from cylc.flow.scripts.broadcast import _main, get_option_parser
from cylc.flow.util import sstrip


BroadcastOptions = Options(get_option_parser())


async def test_broadcast_multi_workflow(
    one_conf,
    flow,
    scheduler,
    start,
    run_dir,
    test_dir,
    capsys,
):
    """Test a multi-workflow broadcast command."""
    # create three workflows
    one = scheduler(flow(one_conf))
    two = scheduler(flow(one_conf))
    thr = scheduler(flow(one_conf))

    # the ID under which all three are installed
    id_base = test_dir.relative_to(run_dir)

    async with start(one):
        async with start(two):
            async with start(thr):
                capsys.readouterr()

                # test a successful broadcast command
                rets = await _main(
                    BroadcastOptions(settings=['script=true']), f'{id_base}*'
                )

                # all three broadcasts should have succeeded
                assert list(rets.values()) == [True, True, True]

                out, err = capsys.readouterr()
                assert '[*/root] script=true' in out
                assert err == ''

                # test an unsuccessful broadcast command
                rets = await _main(
                    BroadcastOptions(
                        namespaces=['*'],
                        settings=['script=true'],
                    ),
                    f'{id_base}*',
                )

                # all three broadcasts should have failed
                assert list(rets.values()) == [False, False, False]

                out, err = capsys.readouterr()
                assert '[*/root] script=true' not in out
                assert (
                    # NOTE: for historical reasons this message goes to stdout
                    # not stderr
                    'Rejected broadcast:'
                    ' settings are not compatible with the workflow'
                ) in out
                assert err == ''


async def test_broadcast_multi_namespace(
    flow,
    scheduler,
    start,
    db_select,
):
    """Test a multi-namespace broadcast command.

    See https://github.com/cylc/cylc-flow/issues/6334
    """
    id_ = flow(
        {
            'scheduling': {
                'graph': {'R1': 'a & b & c & fin'},
            },
            'runtime': {
                'root': {'execution time limit': 'PT1S'},
                'VOWELS': {'execution time limit': 'PT2S'},
                'CONSONANTS': {'execution time limit': 'PT3S'},
                'a': {'inherit': 'VOWELS'},
                'b': {'inherit': 'CONSONANTS'},
                'c': {'inherit': 'CONSONANTS'},
            },
        }
    )
    schd = scheduler(id_)

    async with start(schd):
        # issue a broadcast to multiple namespaces
        rets = await _main(
            BroadcastOptions(
                settings=['execution time limit = PT5S'],
                namespaces=['root', 'VOWELS', 'CONSONANTS'],
            ),
            schd.workflow,
        )

        # the broadcast should succeed
        assert list(rets.values()) == [True]

        # the broadcast manager should store the "coerced" setting
        for task in ['a', 'b', 'c', 'fin']:
            assert schd.broadcast_mgr.get_broadcast(
                schd.tokens.duplicate(cycle='1', task=task)
            ) == {'execution time limit': 5.0}

        # the database should store the "raw" setting
        assert sorted(
            db_select(schd, True, CylcWorkflowDAO.TABLE_BROADCAST_STATES)
        ) == [
            ('*', 'CONSONANTS', 'execution time limit', 'PT5S'),
            ('*', 'VOWELS', 'execution time limit', 'PT5S'),
            ('*', 'root', 'execution time limit', 'PT5S'),
        ]


async def test_broadcast_truncated_datetime(flow, scheduler, start, capsys):
    """It should reject truncated datetime cycle points.

    See https://github.com/cylc/cylc-flow/issues/6407
    """
    id_ = flow({
        'scheduling': {
            'initial cycle point': '2000',
            'graph': {
                'R1': 'foo',
            },
        }
    })
    schd = scheduler(id_)
    async with start(schd):
        # attempt an invalid broadcast
        rets = await _main(
            BroadcastOptions(
                settings=['[environment]FOO=bar'],
                point_strings=['050101T0000Z'],  # <== truncated
            ),
            schd.workflow,
        )

        # the broadcast should fail
        assert list(rets.values()) == [False]

        # an error should be recorded
        _out, err = capsys.readouterr()
        assert (
            'Rejected broadcast:'
            ' settings are not compatible with the workflow'
        ) in err


async def test_invalid(one, start, capsys, monkeypatch):
    """It should reject invalid broadcasts.

    * Broadcast operations may contain a mix of valid and invalid
      cycles/namespaces/settings.
    * Valid settings are applied and reported.
    * Invalid settings are rejected and reported.
    """
    # disable client side config validation so that we can see invalid
    # broadcast settings in the CLI output
    monkeypatch.setattr(
        'cylc.flow.scripts.broadcast.cylc_config_validate',
        lambda *args, **kwargs: True,
    )

    # 1) disable CLI colour output
    monkeypatch.setattr('cylc.flow.scripts.broadcast.cparse', cstrip)

    async with start(one):
        # test the GraphQL API
        client = WorkflowRuntimeClient(one.workflow)
        response = await client.async_request(
            'graphql',
            {
                'request_string': '''
                    mutation(
                        $workflows: [WorkflowID]!,
                        $cycles: [BroadcastCyclePoint],
                        $namespaces: [NamespaceName],
                        $settings: [BroadcastSetting]
                    ) {
                      broadcast(
                        mode: Set
                        workflows: $workflows
                        cyclePoints: $cycles
                        namespaces: $namespaces
                        settings: $settings
                      ) {
                        result
                      }
                    }
                ''',
                'variables': {
                    'workflows': [one.workflow],
                    # valid, invalid
                    'cycles': ['*', 'invalid'],
                    'namespaces': ['root', 'invalid'],
                    'settings': [{'script': 'true'}, {'invalid': 'false'}],
                }
            }
        )
        modified, rejected = response['broadcast']['result'][0]['response']

        assert modified == [
            [
                # cycle
                '*',
                # namespace
                'root',
                # settings
                {'script': 'true'},
            ]
        ]
        assert rejected == {
            'point_strings': ['invalid'],
            'namespaces': ['invalid'],
            'settings': [{'invalid': 'false'}],
        }

        # 2) test the CLI
        capsys.readouterr()  # flush out any stdout/err
        await _main(
            BroadcastOptions(
                point_strings=['*', 'invalid'],
                namespaces=['root', 'invalid'],
                settings=['script=true', 'invalid=false'],
            ),
            one.workflow,
        )
        out, err = capsys.readouterr()
        assert out == 'Broadcast set:\n+ [*/root] script=true\n'
        assert err == sstrip('''
    ERROR: Rejected broadcast: settings are not compatible with the workflow
      --namespace=invalid
      --point=invalid
      --set=invalid=false
        ''') + '\n'


async def test_internal_error(one, start, capsys, monkeypatch, log_filter):
    """It should handle internal code errors elegantly."""

    # simulate an internal error
    # Note: The broadcast "lock" mechanism is an example of how such an error
    # could arise
    def put_broadcast(*args, **kwargs):
        raise Exception('FooBar')

    async with start(one):
        # issue a broadcast
        one.broadcast_mgr.put_broadcast = put_broadcast
        client = WorkflowRuntimeClient(one.workflow)
        response = await client.async_request(
            'graphql',
            {
                'request_string': '''
                    mutation(
                        $workflows: [WorkflowID]!,
                        $cycles: [BroadcastCyclePoint],
                        $namespaces: [NamespaceName],
                        $settings: [BroadcastSetting]
                    ) {
                      broadcast(
                        mode: Set
                        workflows: $workflows
                        cyclePoints: $cycles
                        namespaces: $namespaces
                        settings: $settings
                      ) {
                        result
                      }
                    }
                ''',
                'variables': {
                    'workflows': [one.workflow],
                    'cycles': ['*'],
                    'namespaces': ['root'],
                    'settings': [{'script': 'true'}],
                }
            }
        )

        # check it comes back with an error code
        assert (
            response['broadcast']['result'][0]
        )['response']['error']['message'] == 'FooBar'

        # the error should be logged server-side too
        assert log_filter(contains='FooBar')