Debian Codegraph @

tests/i/network/test_server.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 asyncio
18 import logging
19 from threading import BrokenBarrierError
20 from typing import Callable
21
22 import pytest
23
24 from cylc.flow import __version__ as CYLC_VERSION
25 from cylc.flow.network.server import PB_METHOD_MAP, WorkflowRuntimeServer
26 from cylc.flow.scheduler import Scheduler
27
28
29 @pytest.fixture(scope='module')
30 async def myflow(mod_flow, mod_scheduler, mod_run, mod_one_conf):
31 id_ = mod_flow(mod_one_conf)
32 schd = mod_scheduler(id_)
33 async with mod_run(schd):
34 yield schd
35
36
37 def test_graphql(myflow):
38 """Test GraphQL endpoint method."""
39 request_string = f'''
40 query {{
41 workflows(ids: ["{myflow.id}"]) {{
42 id
43 }}
44 }}
45 '''
46 data = myflow.server.graphql(request_string)
47 assert myflow.id == data['workflows'][0]['id']
48
49
50 def test_graphql_error(myflow):
51 """Test GraphQL endpoint method."""
52 request_string = f'''
53 query {{
54 workflows(ids: ["{myflow.id}"]) {{
55 id
56 notafield
57 alsonotafield
58 }}
59 }}
60 '''
61 with pytest.raises(Exception) as excinfo:
62 myflow.server.graphql(request_string)
63 assert "Cannot query field 'notafield'" in excinfo
64 assert "Cannot query field 'alsonotafield'" in excinfo
65
66
67 def test_pb_data_elements(myflow):
68 """Test Protobuf elements endpoint method."""
69 element_type = 'workflow'
70 data = PB_METHOD_MAP['pb_data_elements'][element_type]()
71 data.ParseFromString(
72 myflow.server.pb_data_elements(element_type)
73 )
74 assert data.added.id == myflow.id
75
76
77 def test_pb_entire_workflow(myflow):
78 """Test Protobuf entire workflow endpoint method."""
79 data = PB_METHOD_MAP['pb_entire_workflow']()
80 data.ParseFromString(
81 myflow.server.pb_entire_workflow()
82 )
83 assert data.workflow.id == myflow.id
84
85
86 async def test_stop(one: Scheduler, start):
87 """Test stop."""
88 async with start(one):
89 assert one.server.thread.is_alive()
90 assert one.server.publisher
91 assert one.server.curve_auth.is_alive()
92 async with asyncio.timeout(2):
93 # Wait for the server to consume the STOP signal.
94 # If it doesn't, the test will fail with a asyncio.timeout error.
95 await one.server.stop('TESTING')
96 assert not one.server.thread.is_alive()
97 assert not one.server.publisher
98 assert not one.server.curve_auth.is_alive()
99 assert not one.server.loop.is_running()
100
101
102 @pytest.mark.filterwarnings(
103 r"ignore:.*:pytest.PytestUnhandledThreadExceptionWarning"
104 )
105 async def test_broken_barrier_shutdown(
106 one: Scheduler, start, monkeypatch: pytest.MonkeyPatch
107 ):
108 """Test that the server shuts down if the barrier is broken on startup.
109
110 Broken barrier has been observed to happen if the scheduler host is sickly
111 https://github.com/cylc/cylc-flow/issues/7425
112 """
113 class MockServer(WorkflowRuntimeServer):
114 def start(self, barrier):
115 barrier.abort()
116 super().start(barrier)
117
118 monkeypatch.setattr(
119 'cylc.flow.scheduler.WorkflowRuntimeServer', MockServer
120 )
121 with pytest.raises(BrokenBarrierError):
122 async with start(one):
123 pass
124 assert not one.server.thread.is_alive()
125
126
127 async def test_receiver_basic(one: Scheduler, start, log_filter):
128 """Test the receiver with different message objects."""
129 async with asyncio.timeout(5):
130 async with start(one):
131 # start with a message that works
132 msg = {'command': 'api', 'user': 'bono', 'args': {}}
133 res = one.server.receiver(msg)
134 assert not res.get('error')
135 assert res['data']
136 assert res['cylc_version'] == CYLC_VERSION
137
138 # simulate a command failure with the original message
139 # (the one which worked earlier) - should error
140 def _api(*args, **kwargs):
141 raise Exception('oopsie')
142 one.server.api = _api
143 res = one.server.receiver(msg)
144 assert res == {
145 'error': {'message': 'oopsie'},
146 'cylc_version': CYLC_VERSION,
147 }
148 assert log_filter(logging.ERROR, 'oopsie')
149
150
151 @pytest.mark.parametrize(
152 'msg, expected',
153 [
154 pytest.param(
155 {'user': 'bono', 'args': {}},
156 "Request missing field 'command' required for"
157 f" Cylc {CYLC_VERSION}",
158 id='missing-command',
159 ),
160 pytest.param(
161 {'command': 'foobar', 'user': 'bono', 'args': {}},
162 f"No method by the name 'foobar' at Cylc {CYLC_VERSION}",
163 id='bad-command',
164 ),
165 ],
166 )
167 async def test_receiver_bad_requests(one: Scheduler, start, msg, expected):
168 """Test the receiver with different bad requests."""
169 async with asyncio.timeout(5):
170 async with start(one):
171 res = one.server.receiver(msg)
172 assert res == {
173 'error': {'message': expected},
174 'cylc_version': CYLC_VERSION,
175 }
176
177
178 async def test_publish_before_shutdown(
179 one: Scheduler, start: Callable
180 ):
181 """Test that the server publishes final deltas before shutting down."""
182 async with start(one):
183 one.server.publish_queue.put([(b'fake', b'blah')])
184 await one.server.stop('i said stop!')
185 assert not one.server.publish_queue.qsize()