Passed
Push — master ( 0d5fad...e0a32b )
by Vinicius
02:31 queued 14s
created

TestMain.test_on_topology_loaded()   A

Complexity

Conditions 1

Size

Total Lines 9
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 8
nop 1
dl 0
loc 9
ccs 7
cts 7
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
"""Test Main methods."""
2 1
from unittest.mock import AsyncMock, MagicMock, call, patch
3
4 1
from httpx import Response
5 1
from kytos.core.events import KytosEvent
6 1
from kytos.core.exceptions import (KytosTagsNotInTagRanges,
7
                                   KytosTagsAreNotAvailable)
8 1
from kytos.lib.helpers import (get_controller_mock, get_interface_mock,
9
                               get_kytos_event_mock, get_switch_mock,
10
                               get_test_client)
11 1
from napps.kytos.of_lldp.utils import get_cookie
12 1
from tenacity import RetryError
13
14 1
from tests.helpers import get_topology_mock
15
16
17 1 View Code Duplication
@patch('kytos.core.controller.Controller.get_switch_by_dpid')
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
18 1
@patch('napps.kytos.of_lldp.main.Main._unpack_non_empty')
19 1
@patch('napps.kytos.of_lldp.main.UBInt32')
20 1
@patch('napps.kytos.of_lldp.main.DPID')
21 1
@patch('napps.kytos.of_lldp.main.LLDP')
22 1
@patch('napps.kytos.of_lldp.main.Ethernet')
23 1
async def test_on_ofpt_packet_in(*args):
24
    """Test on_ofpt_packet_in."""
25 1
    (mock_ethernet, mock_lldp, mock_dpid, mock_ubint32,
26
     mock_unpack_non_empty, mock_get_switch_by_dpid) = args
27
28
    # pylint: disable=bad-option-value, import-outside-toplevel
29 1
    from napps.kytos.of_lldp.main import Main
30 1
    Main.get_liveness_controller = MagicMock()
31 1
    topology = get_topology_mock()
32 1
    controller = get_controller_mock()
33 1
    controller.buffers.app.aput = AsyncMock()
34 1
    controller.switches = topology.switches
35 1
    napp = Main(controller)
36 1
    napp.loop_manager.process_if_looped = AsyncMock()
37 1
    napp.liveness_manager.consume_hello_if_enabled = AsyncMock()
38
39 1
    switch = get_switch_mock("00:00:00:00:00:00:00:01", 0x04)
40 1
    message = MagicMock(in_port=1, data='data')
41 1
    event = KytosEvent('ofpt_packet_in', content={'source': switch.connection,
42
                       'message': message})
43
44 1
    mocked, ethernet, lldp, dpid, port_b = [MagicMock() for _ in range(5)]
45 1
    mocked.value = 1
46 1
    mock_ubint32.return_value = mocked
47 1
    ethernet.ether_type = 0x88CC
48 1
    ethernet.data = 'eth_data'
49 1
    lldp.chassis_id.sub_value = 'chassis_id'
50 1
    lldp.port_id.sub_value = 'port_id'
51 1
    dpid.value = "00:00:00:00:00:00:00:02"
52 1
    port_b.value = 2
53
54 1
    mock_unpack_non_empty.side_effect = [ethernet, lldp, dpid, port_b]
55 1
    mock_get_switch_by_dpid.return_value = get_switch_mock(dpid.value,
56
                                                           0x04)
57 1
    await napp.on_ofpt_packet_in(event)
58
59 1
    calls = [call(mock_ethernet, message.data),
60
             call(mock_lldp, ethernet.data),
61
             call(mock_dpid, lldp.chassis_id.sub_value),
62
             call(mock_ubint32, lldp.port_id.sub_value)]
63 1
    mock_unpack_non_empty.assert_has_calls(calls)
64 1
    assert napp.loop_manager.process_if_looped.call_count == 1
65 1
    assert napp.liveness_manager.consume_hello_if_enabled.call_count == 1
66 1
    assert controller.buffers.app.aput.call_count == 1
67
68
69 1 View Code Duplication
@patch('kytos.core.controller.Controller.get_switch_by_dpid')
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
70 1
@patch('napps.kytos.of_lldp.main.Main._unpack_non_empty')
71 1
@patch('napps.kytos.of_lldp.main.UBInt32')
72 1
@patch('napps.kytos.of_lldp.main.DPID')
73 1
@patch('napps.kytos.of_lldp.main.LLDP')
74 1
@patch('napps.kytos.of_lldp.main.Ethernet')
75 1
async def test_on_ofpt_packet_in_early_intf(*args):
76
    """Test on_ofpt_packet_in early intf return."""
77 1
    (mock_ethernet, mock_lldp, mock_dpid, mock_ubint32,
78
     mock_unpack_non_empty, mock_get_switch_by_dpid) = args
79
80
    # pylint: disable=bad-option-value, import-outside-toplevel
81 1
    from napps.kytos.of_lldp.main import Main
82 1
    Main.get_liveness_controller = MagicMock()
83 1
    topology = get_topology_mock()
84 1
    controller = get_controller_mock()
85 1
    controller.buffers.app.aput = AsyncMock()
86 1
    controller.switches = topology.switches
87 1
    napp = Main(controller)
88 1
    napp.loop_manager.process_if_looped = AsyncMock()
89 1
    napp.liveness_manager.consume_hello_if_enabled = AsyncMock()
90
91 1
    switch = get_switch_mock("00:00:00:00:00:00:00:01", 0x04)
92 1
    message = MagicMock(in_port=1, data='data')
93 1
    event = KytosEvent('ofpt_packet_in', content={'source': switch.connection,
94
                       'message': message})
95
96 1
    mocked, ethernet, lldp, dpid, port_b = [MagicMock() for _ in range(5)]
97 1
    mocked.value = 1
98 1
    mock_ubint32.return_value = mocked
99 1
    ethernet.ether_type = 0x88CC
100 1
    ethernet.data = 'eth_data'
101 1
    lldp.chassis_id.sub_value = 'chassis_id'
102 1
    lldp.port_id.sub_value = 'port_id'
103 1
    dpid.value = "00:00:00:00:00:00:00:02"
104 1
    port_b.value = 2
105
106 1
    mock_unpack_non_empty.side_effect = [ethernet, lldp, dpid, port_b]
107 1
    mock_get_switch_by_dpid.return_value = get_switch_mock(dpid.value,
108
                                                           0x04)
109 1
    switch.get_interface_by_port_no = MagicMock(return_value=None)
110 1
    await napp.on_ofpt_packet_in(event)
111
112 1
    calls = [call(mock_ethernet, message.data),
113
             call(mock_lldp, ethernet.data),
114
             call(mock_dpid, lldp.chassis_id.sub_value),
115
             call(mock_ubint32, lldp.port_id.sub_value)]
116 1
    mock_unpack_non_empty.assert_has_calls(calls)
117 1
    switch.get_interface_by_port_no.assert_called()
118
    # early return shouldn't allow these to get called
119 1
    assert napp.loop_manager.process_if_looped.call_count == 0
120 1
    assert napp.liveness_manager.consume_hello_if_enabled.call_count == 0
121 1
    assert controller.buffers.app.aput.call_count == 0
122
123
124 1
async def test_on_table_enabled():
125
    """Test on_table_enabled"""
126
    # pylint: disable=bad-option-value, import-outside-toplevel
127 1
    from napps.kytos.of_lldp.main import Main
128 1
    controller = get_controller_mock()
129 1
    controller.buffers.app.aput = AsyncMock()
130 1
    napp = Main(controller)
131
132
    # Succesfully setting table groups
133 1
    content = {"of_lldp": {"base": 123}}
134 1
    event = KytosEvent(name="kytos/of_multi_table.enable_table",
135
                       content=content)
136 1
    await napp.on_table_enabled(event)
137 1
    assert napp.table_group == content["of_lldp"]
138 1
    assert controller.buffers.app.aput.call_count == 1
139
140
    # Failure at setting table groups
141 1
    content = {"of_lldp": {"unknown": 123}}
142 1
    event = KytosEvent(name="kytos/of_multi_table.enable_table",
143
                       content=content)
144 1
    await napp.on_table_enabled(event)
145 1
    assert controller.buffers.app.aput.call_count == 1
146
147
148
# pylint: disable=protected-access,too-many-public-methods
149 1
class TestMain:
150
    """Tests for the Main class."""
151
152 1
    def setup_method(self):
153
        """Execute steps before each tests."""
154
        # patch('kytos.core.helpers.run_on_thread', lambda x: x).start()
155
        # pylint: disable=bad-option-value, import-outside-toplevel
156 1
        from napps.kytos.of_lldp.main import Main
157 1
        Main.get_liveness_controller = MagicMock()
158 1
        self.topology = get_topology_mock()
159 1
        controller = get_controller_mock()
160 1
        controller.switches = self.topology.switches
161 1
        self.base_endpoint = "kytos/of_lldp/v1"
162 1
        self.napp = Main(controller)
163 1
        self.api_client = get_test_client(controller, self.napp)
164
165 1
    def teardown_method(self) -> None:
166
        """Teardown."""
167 1
        patch.stopall()
168
169 1
    def get_topology_interfaces(self):
170
        """Return interfaces present in topology."""
171 1
        interfaces = []
172 1
        for switch in list(self.topology.switches.values()):
173 1
            interfaces += list(switch.interfaces.values())
174 1
        return interfaces
175
176 1
    @patch('napps.kytos.of_lldp.main.of_msg_prio')
177 1
    @patch('napps.kytos.of_lldp.main.KytosEvent')
178 1
    @patch('napps.kytos.of_lldp.main.VLAN')
179 1
    @patch('napps.kytos.of_lldp.main.Ethernet')
180 1
    @patch('napps.kytos.of_lldp.main.DPID')
181 1
    @patch('napps.kytos.of_lldp.main.LLDP')
182 1
    def test_execute(self, *args):
183
        """Test execute method."""
184 1
        (_, _, mock_ethernet, _, mock_kytos_event, mock_of_msg_prio) = args
185 1
        mock_buffer_put = MagicMock()
186 1
        self.napp.controller.buffers.msg_out.put = mock_buffer_put
187
188 1
        ethernet = MagicMock()
189 1
        ethernet.pack.return_value = 'pack'
190 1
        interfaces = self.get_topology_interfaces()
191 1
        po_args = [(interface.switch.connection.protocol.version,
192
                    interface.port_number, 'pack') for interface in interfaces]
193
194 1
        mock_ethernet.return_value = ethernet
195 1
        mock_kytos_event.side_effect = po_args
196
197 1
        mock_publish_stopped = MagicMock()
198 1
        self.napp.try_to_publish_stopped_loops = mock_publish_stopped
199 1
        self.napp.execute()
200
201 1
        mock_of_msg_prio.assert_called()
202 1
        mock_buffer_put.assert_has_calls([call(arg)
203
                                          for arg in po_args])
204 1
        mock_publish_stopped.assert_called()
205
206 1
    @patch('napps.kytos.of_lldp.main.Main.get_flows_by_switch')
207 1
    def test_handle_lldp_flows(self, mock_flows, monkeypatch):
208
        """Test handle_lldp_flow method."""
209 1
        dpid = "00:00:00:00:00:00:00:01"
210 1
        switch = get_switch_mock("00:00:00:00:00:00:00:01", 0x04)
211 1
        self.napp.controller.switches = {dpid: switch}
212 1
        event_post = get_kytos_event_mock(name='kytos/topology.switch.enabled',
213
                                          content={'dpid': dpid})
214
215 1
        event_del = get_kytos_event_mock(name='kytos/topology.switch.disabled',
216
                                         content={'dpid': dpid})
217
218 1
        mock_post, mock_del = MagicMock(), MagicMock()
219 1
        mock_post.return_value = Response(status_code=202)
220 1
        mock_del.return_value = Response(status_code=202)
221 1
        monkeypatch.setattr("httpx.post", mock_post)
222 1
        monkeypatch.setattr("httpx.request", mock_del)
223
224 1
        mock_flows.return_value = {}
225 1
        self.napp.use_vlan = MagicMock()
226 1
        self.napp._handle_lldp_flows(event_post)
227 1
        mock_post.assert_called()
228 1
        self.napp.use_vlan.assert_called_with(switch)
229
230 1
        mock_flows.return_value = {"flows": "mocked_flows"}
231 1
        self.napp.make_vlan_available = MagicMock()
232 1
        self.napp._handle_lldp_flows(event_del)
233 1
        mock_del.assert_called()
234 1
        self.napp.make_vlan_available.assert_called_with(switch)
235
236 1
    @patch('napps.kytos.of_lldp.main.Main.get_flows_by_switch')
237 1
    @patch("time.sleep")
238 1
    def test_handle_lldp_flows_retries(self, _, mock_flows, monkeypatch):
239
        """Test handle_lldp_flow method retries."""
240 1
        dpid = "00:00:00:00:00:00:00:01"
241 1
        switch = get_switch_mock("00:00:00:00:00:00:00:01", 0x04)
242 1
        mock_flows.return_value = {}
243 1
        mock_post = MagicMock()
244 1
        monkeypatch.setattr("httpx.post", mock_post)
245 1
        self.napp.controller.switches = {dpid: switch}
246 1
        event_post = get_kytos_event_mock(name="kytos/topology.switch.enabled",
247
                                          content={"dpid": dpid})
248
249 1
        mock = MagicMock()
250 1
        mock.request.method = "POST"
251 1
        mock.status_code = 500
252 1
        mock.text = "some_err"
253 1
        mock_post.return_value = mock
254 1
        self.napp._handle_lldp_flows(event_post)
255 1
        assert mock_post.call_count == 3
256
257 1
    @patch('napps.kytos.of_lldp.main.log')
258 1
    def test_handle_lldp_flows_request_value_error(self, mock_log,
259
                                                   monkeypatch):
260
        """Test _handle_lldp_flows"""
261 1
        dpid = "00:00:00:00:00:00:00:01"
262 1
        mock_get = MagicMock()
263 1
        mock_get.return_value = MagicMock(
264
            status_code=400, is_server_error=False
265
        )
266 1
        event_post = get_kytos_event_mock(name='kytos/topology.switch.enabled',
267
                                          content={'dpid': dpid})
268 1
        monkeypatch.setattr("httpx.get", mock_get)
269 1
        self.napp._handle_lldp_flows(event_post)
270 1
        assert mock_log.error.call_count == 1
271
272 1
    @patch('napps.kytos.of_lldp.main.log')
273 1
    def test_handle_lldp_flows_request_error(self, mock_log):
274
        """Test _handle_lldp_flows"""
275 1
        dpid = "00:00:00:00:00:00:00:01"
276 1
        event_post = get_kytos_event_mock(name='kytos/topology.switch.enabled',
277
                                          content={'dpid': dpid})
278 1
        self.napp.get_flows_by_switch = MagicMock()
279 1
        exc = RetryError(MagicMock())
280 1
        self.napp.get_flows_by_switch.side_effect = exc
281 1
        self.napp._handle_lldp_flows(event_post)
282 1
        assert mock_log.error.call_count == 1
283
284 1
    @patch('napps.kytos.of_lldp.main.PO13')
285 1
    @patch('napps.kytos.of_lldp.main.AO13')
286 1
    def test_build_lldp_packet_out(self, *args):
287
        """Test _build_lldp_packet_out method."""
288 1
        (mock_ao13, mock_po13) = args
289
290 1
        ao13 = MagicMock()
291 1
        po13 = MagicMock()
292 1
        po13.actions = []
293
294 1
        mock_ao13.return_value = ao13
295 1
        mock_po13.return_value = po13
296
297 1
        packet_out13 = self.napp._build_lldp_packet_out(0x04, 2, 'data2')
298 1
        packet_out14 = self.napp._build_lldp_packet_out(0x05, 3, 'data3')
299
300 1
        assert packet_out13.data == 'data2'
301 1
        assert packet_out13.actions == [ao13]
302 1
        assert packet_out13.actions[0].port == 2
303 1
        assert packet_out14 is None
304
305 1
    @patch('napps.kytos.of_lldp.main.settings')
306 1
    @patch('napps.kytos.of_lldp.main.EtherType')
307 1
    @patch('napps.kytos.of_lldp.main.Port13')
308 1
    def test_build_lldp_flow(self, *args):
309
        """Test _build_lldp_flow method."""
310 1
        (mock_v0x04_port, mock_ethertype,
311
         mock_settings) = args
312 1
        self.napp.vlan_id = None
313 1
        mock_v0x04_port.OFPP_CONTROLLER = 1234
314
315 1
        mock_ethertype.LLDP = 10
316 1
        mock_settings.FLOW_VLAN_VID = None
317 1
        mock_settings.FLOW_PRIORITY = 1500
318 1
        dpid = "00:00:00:00:00:00:00:01"
319
320 1
        flow = {}
321 1
        match = {}
322 1
        flow['priority'] = 1500
323 1
        flow['table_id'] = 0
324 1
        match['dl_type'] = 10
325
326 1
        flow['match'] = match
327 1
        expected_flow_v0x04 = flow.copy()
328 1
        expected_flow_v0x04['cookie'] = get_cookie(dpid)
329 1
        expected_flow_v0x04['cookie_mask'] = 0xffffffffffffffff
330
331 1
        expected_flow_v0x04['actions'] = [{'action_type': 'output',
332
                                           'port': 1234}]
333 1
        expected_flow_v0x04['table_group'] = 'base'
334 1
        expected_flow_v0x04['owner'] = 'of_lldp'
335
336 1
        flow_mod10 = self.napp._build_lldp_flow(0x01, get_cookie(dpid))
337 1
        flow_mod13 = self.napp._build_lldp_flow(0x04, get_cookie(dpid))
338
339 1
        assert flow_mod10 is None
340 1
        assert flow_mod13 == expected_flow_v0x04
341
342 1
    def test_unpack_non_empty(self):
343
        """Test _unpack_non_empty method."""
344 1
        desired_class = MagicMock()
345 1
        data = MagicMock()
346 1
        data.value = 'data'
347
348 1
        obj = self.napp._unpack_non_empty(desired_class, data)
349
350 1
        obj.unpack.assert_called_with('data')
351
352 1
    def test_get_data(self, monkeypatch):
353
        """Test _get_data method."""
354 1
        interfaces = ['00:00:00:00:00:00:00:01:1', '00:00:00:00:00:00:00:01:2']
355 1
        monkeypatch.setattr("napps.kytos.of_lldp.main.get_json_or_400",
356
                            lambda req, loop: {"interfaces": interfaces})
357 1
        data = self.napp._get_data(MagicMock())
358 1
        assert data == interfaces
359
360 1
    def test_load_liveness(self) -> None:
361
        """Test load_liveness."""
362 1
        self.napp.load_liveness()
363 1
        count = self.napp.liveness_controller.get_enabled_interfaces.call_count
364 1
        assert count == 1
365
366 1
    async def test_on_topology_loaded(self) -> None:
367
        """Test on_topology_loaded."""
368 1
        event = KytosEvent("kytos/topology.topology_loaded",
369
                           content={"topology": {}})
370 1
        self.napp.load_liveness = MagicMock()
371 1
        self.napp.loop_manager.handle_topology_loaded = AsyncMock()
372 1
        await self.napp.on_topology_loaded(event)
373 1
        assert self.napp.loop_manager.handle_topology_loaded.call_count == 1
374 1
        assert self.napp.load_liveness.call_count == 1
375
376 1
    def test_publish_liveness_status(self) -> None:
377
        """Test publish_liveness_status."""
378 1
        self.napp.controller.buffers.app.put = MagicMock()
379 1
        event_suffix, interfaces = "up", [MagicMock(id=1), MagicMock(id=2)]
380 1
        self.napp.publish_liveness_status(event_suffix, interfaces)
381 1
        assert self.napp.controller.buffers.app.put.call_count == 1
382 1
        event = self.napp.controller.buffers.app.put.call_args[0][0]
383 1
        assert event.name == f"kytos/of_lldp.liveness.{event_suffix}"
384 1
        assert event.content["interfaces"] == interfaces
385
386 1
    def test_get_interfaces(self):
387
        """Test _get_interfaces method."""
388 1
        expected_interfaces = self.get_topology_interfaces()
389 1
        interfaces = self.napp._get_interfaces()
390 1
        assert interfaces == expected_interfaces
391
392 1
    def test_get_interfaces_dict(self):
393
        """Test _get_interfaces_dict method."""
394 1
        interfaces = self.napp._get_interfaces()
395 1
        expected_interfaces = {inter.id: inter for inter in interfaces}
396 1
        interfaces_dict = self.napp._get_interfaces_dict(interfaces)
397 1
        assert interfaces_dict == expected_interfaces
398
399 1
    def test_get_lldp_interfaces(self):
400
        """Test _get_lldp_interfaces method."""
401 1
        lldp_interfaces = self.napp._get_lldp_interfaces()
402 1
        expected_interfaces = ['00:00:00:00:00:00:00:01:1',
403
                               '00:00:00:00:00:00:00:01:2',
404
                               '00:00:00:00:00:00:00:02:1',
405
                               '00:00:00:00:00:00:00:02:2']
406 1
        assert lldp_interfaces == expected_interfaces
407
408 1
    async def test_rest_get_lldp_interfaces(self):
409
        """Test get_lldp_interfaces method."""
410 1
        endpoint = f"{self.base_endpoint}/interfaces"
411 1
        response = await self.api_client.get(endpoint)
412 1
        expected_data = {"interfaces": ['00:00:00:00:00:00:00:01:1',
413
                                        '00:00:00:00:00:00:00:01:2',
414
                                        '00:00:00:00:00:00:00:02:1',
415
                                        '00:00:00:00:00:00:00:02:2']}
416 1
        assert response.status_code == 200
417 1
        assert response.json() == expected_data
418
419 1
    async def test_enable_disable_lldp_200(self, event_loop):
420
        """Test 200 response for enable_lldp and disable_lldp methods."""
421 1
        data = {"interfaces": ['00:00:00:00:00:00:00:01:1',
422
                               '00:00:00:00:00:00:00:01:2',
423
                               '00:00:00:00:00:00:00:02:1',
424
                               '00:00:00:00:00:00:00:02:2']}
425 1
        self.napp.controller.loop = event_loop
426 1
        self.napp.publish_liveness_status = MagicMock()
427 1
        endpoint = f"{self.base_endpoint}/interfaces/disable"
428 1
        response = await self.api_client.post(endpoint, json=data)
429 1
        assert response.status_code == 200
430 1
        assert self.napp.liveness_controller.disable_interfaces.call_count == 1
431 1
        assert self.napp.publish_liveness_status.call_count == 1
432 1
        endpoint = f"{self.base_endpoint}/interfaces/enable"
433 1
        response = await self.api_client.post(endpoint, json=data)
434 1
        assert response.status_code == 200
435
436 1
    async def test_enable_disable_lldp_404(self):
437
        """Test 404 response for enable_lldp and disable_lldp methods."""
438 1
        data = {"interfaces": []}
439 1
        self.napp.controller.switches = {}
440 1
        endpoint = f"{self.base_endpoint}/disable"
441 1
        response = await self.api_client.post(endpoint, json=data)
442 1
        assert response.status_code == 404
443 1
        endpoint = f"{self.base_endpoint}/enable"
444 1
        response = await self.api_client.post(endpoint, json=data)
445 1
        assert response.status_code == 404
446
447 1
    async def test_enable_disable_lldp_400(self, event_loop):
448
        """Test 400 response for enable_lldp and disable_lldp methods."""
449 1
        data = {"interfaces": ['00:00:00:00:00:00:00:01:1',
450
                               '00:00:00:00:00:00:00:01:2',
451
                               '00:00:00:00:00:00:00:02:1',
452
                               '00:00:00:00:00:00:00:02:2',
453
                               '00:00:00:00:00:00:00:03:1',
454
                               '00:00:00:00:00:00:00:03:2',
455
                               '00:00:00:00:00:00:00:04:1']}
456 1
        self.napp.controller.loop = event_loop
457 1
        self.napp.publish_liveness_status = MagicMock()
458 1
        url = f'{self.base_endpoint}/interfaces/disable'
459 1
        response = await self.api_client.post(url, json=data)
460 1
        assert response.status_code == 400
461 1
        assert self.napp.publish_liveness_status.call_count == 1
462
463 1
        url = f'{self.base_endpoint}/interfaces/enable'
464 1
        response = await self.api_client.post(url, json=data)
465 1
        assert response.status_code == 400
466
467 1
    async def test_get_time(self):
468
        """Test get polling time."""
469 1
        url = f"{self.base_endpoint}/polling_time"
470 1
        response = await self.api_client.get(url)
471 1
        assert response.status_code == 200
472
473 1
    async def test_set_polling_time(self):
474
        """Test update polling time."""
475 1
        url = f"{self.base_endpoint}/polling_time"
476 1
        data = {'polling_time': 5}
477 1
        response = await self.api_client.post(url, json=data)
478 1
        assert response.status_code == 200
479
480 1
    async def test_set_time_400(self):
481
        """Test fail case the update polling time."""
482 1
        url = f"{self.base_endpoint}/polling_time"
483 1
        data = {'polling_time': 'A'}
484 1
        response = await self.api_client.post(url, json=data)
485 1
        assert response.status_code == 400
486
487 1
    async def test_endpoint_enable_liveness(self, event_loop):
488
        """Test POST v1/liveness/enable."""
489 1
        self.napp.controller.loop = event_loop
490 1
        self.napp.liveness_manager.enable = MagicMock()
491 1
        self.napp.publish_liveness_status = MagicMock()
492 1
        url = f"{self.base_endpoint}/liveness/enable"
493 1
        data = {"interfaces": ["00:00:00:00:00:00:00:01:1"]}
494 1
        response = await self.api_client.post(url, json=data)
495 1
        assert response.status_code == 200
496 1
        assert response.json() == {}
497 1
        assert self.napp.liveness_controller.enable_interfaces.call_count == 1
498 1
        assert self.napp.liveness_manager.enable.call_count == 1
499 1
        assert self.napp.publish_liveness_status.call_count == 1
500
501 1
    async def test_endpoint_disable_liveness(self, event_loop):
502
        """Test POST v1/liveness/disable."""
503 1
        self.napp.controller.loop = event_loop
504 1
        self.napp.liveness_manager.disable = MagicMock()
505 1
        self.napp.publish_liveness_status = MagicMock()
506 1
        url = f"{self.base_endpoint}/liveness/disable"
507 1
        data = {"interfaces": ["00:00:00:00:00:00:00:01:1"]}
508 1
        response = await self.api_client.post(url, json=data)
509 1
        assert response.status_code == 200
510 1
        assert response.json() == {}
511 1
        assert self.napp.liveness_controller.disable_interfaces.call_count == 1
512 1
        assert self.napp.liveness_manager.disable.call_count == 1
513 1
        assert self.napp.publish_liveness_status.call_count == 1
514
515 1
    async def test_endpoint_get_liveness(self):
516
        """Test GET v1/liveness/."""
517 1
        self.napp.liveness_manager.enable = MagicMock()
518 1
        self.napp.publish_liveness_status = MagicMock()
519 1
        url = f"{self.base_endpoint}/liveness/"
520 1
        response = await self.api_client.get(url)
521 1
        assert response.status_code == 200
522 1
        assert response.json() == {"interfaces": []}
523
524 1
    async def test_endpoint_get_pair_liveness(self):
525
        """Test GET v1/liveness//pair."""
526 1
        self.napp.liveness_manager.enable = MagicMock()
527 1
        self.napp.publish_liveness_status = MagicMock()
528 1
        url = f"{self.base_endpoint}/liveness/pair"
529 1
        response = await self.api_client.get(url)
530 1
        assert response.status_code == 200
531 1
        assert response.json() == {"pairs": []}
532
533 1
    def test_set_flow_table_group_owner(self):
534
        """Test set_flow_table_group_owner"""
535 1
        self.napp.table_group = {"base": 2}
536 1
        flow = {}
537 1
        self.napp.set_flow_table_group_owner(flow, "base")
538 1
        assert "table_group" in flow
539 1
        assert "owner" in flow
540 1
        assert flow["table_id"] == 2
541
542 1
    @patch('napps.kytos.of_lldp.main.log')
543 1
    def test_use_vlan(self, mock_log):
544
        """Test use_vlan"""
545 1
        switch = get_switch_mock("00:00:00:00:00:00:00:01", 0x04)
546 1
        interface_a = get_interface_mock("mock_a", 1, switch)
547 1
        interface_a.use_tags = MagicMock()
548 1
        interface_b = get_interface_mock("mock_b", 2, switch)
549 1
        interface_b.use_tags = MagicMock()
550 1
        switch.interfaces = {1: interface_a, 2: interface_b}
551 1
        self.napp.use_vlan(switch)
552 1
        assert interface_a.use_tags.call_count == 1
553 1
        assert interface_b.use_tags.call_count == 1
554
555 1
        interface_a.use_tags.side_effect = KytosTagsAreNotAvailable([], "1")
556 1
        self.napp.use_vlan(switch)
557 1
        assert interface_a.use_tags.call_count == 2
558 1
        assert interface_b.use_tags.call_count == 2
559 1
        assert mock_log.error.call_count == 1
560
561 1
        self.napp.vlan_id = None
562 1
        self.napp.use_vlan(switch)
563 1
        assert interface_a.use_tags.call_count == 2
564 1
        assert interface_b.use_tags.call_count == 2
565
566 1
    @patch('napps.kytos.of_lldp.main.log')
567 1
    def test_make_vlan_available(self, mock_log):
568
        """Test make_vlan_available"""
569 1
        switch = get_switch_mock("00:00:00:00:00:00:00:01", 0x04)
570 1
        interface_a = get_interface_mock("mock_a", 1, switch)
571 1
        interface_a.make_tags_available = MagicMock()
572 1
        a_make_ava = interface_a.make_tags_available
573 1
        a_make_ava.return_value = []
574 1
        interface_b = get_interface_mock("mock_b", 2, switch)
575 1
        interface_b.make_tags_available = MagicMock()
576 1
        b_make_ava = interface_b.make_tags_available
577 1
        b_make_ava.return_value = []
578 1
        switch.interfaces = {1: interface_a, 2: interface_b}
579 1
        self.napp.make_vlan_available(switch)
580 1
        assert interface_a.make_tags_available.call_count == 1
581 1
        assert interface_b.make_tags_available.call_count == 1
582
583 1
        a_make_ava.return_value = [[3799, 3799]]
584 1
        self.napp.make_vlan_available(switch)
585 1
        assert interface_a.make_tags_available.call_count == 2
586 1
        assert interface_b.make_tags_available.call_count == 2
587 1
        assert mock_log.warning.call_count == 1
588
589 1
        self.napp.vlan_id = None
590 1
        self.napp.make_vlan_available(switch)
591 1
        assert interface_a.make_tags_available.call_count == 2
592 1
        assert interface_b.make_tags_available.call_count == 2
593
594 1
        self.napp.vlan_id = 3799
595 1
        b_make_ava.side_effect = KytosTagsNotInTagRanges(
596
            [[3799, 3799]], "01:2"
597
        )
598 1
        self.napp.make_vlan_available(switch)
599 1
        assert interface_a.make_tags_available.call_count == 3
600 1
        assert interface_b.make_tags_available.call_count == 3
601 1
        assert mock_log.error.call_count == 1
602
603 1 View Code Duplication
    @patch('napps.kytos.of_lldp.main.Main.use_vlan')
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
604 1
    def test_send_flow_enabled(self, mock_use, monkeypatch):
605
        """Test send_flows when switch is enabled"""
606 1
        mock_post = MagicMock()
607 1
        monkeypatch.setattr("httpx.post", mock_post)
608 1
        mock_post.return_value = MagicMock(
609
            status_code=202, is_server_error=False
610
        )
611 1
        event_name = 'kytos/topology.switch.enabled'
612 1
        switch = get_switch_mock("00:00:00:00:00:00:00:01", 0x04)
613 1
        data = {'flows': [{'cookie_mask': "mock_cookie"}]}
614 1
        self.napp.send_flow(switch, event_name, data=data)
615
616 1
        assert mock_use.call_count == 1
617 1
        assert mock_use.call_args[0][0] == switch
618 1
        assert data['flows'] == [{}]
619
620 1 View Code Duplication
    @patch('napps.kytos.of_lldp.main.Main.make_vlan_available')
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
621 1
    def test_send_flow_disabled(self, mock_avaialble, monkeypatch):
622
        """Test send_flows when switch is disabled"""
623 1
        mock_request = MagicMock()
624 1
        monkeypatch.setattr("httpx.request", mock_request)
625 1
        mock_request.return_value = MagicMock(
626
            status_code=202, is_server_error=False
627
        )
628 1
        event_name = 'kytos/topology.switch.disabled'
629 1
        switch = get_switch_mock("00:00:00:00:00:00:00:01", 0x04)
630 1
        data = {'flows': [{'cookie_mask': "mock_cookie"}]}
631 1
        self.napp.send_flow(switch, event_name, data=data)
632
633 1
        assert mock_avaialble.call_count == 1
634 1
        assert mock_avaialble.call_args[0][0] == switch
635
        assert data['flows'] == [{'cookie_mask': "mock_cookie"}]
636