Passed
Push — master ( 127cfb...14f54d )
by Vinicius
02:06 queued 12s
created

TestMain.test_notify_uplink_detected()   B

Complexity

Conditions 1

Size

Total Lines 52
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 45
nop 2
dl 0
loc 52
rs 8.8
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
"""Test Main methods."""
2
from unittest import TestCase
3
from unittest.mock import MagicMock, call, patch
4
5
from kytos.lib.helpers import (get_controller_mock, get_kytos_event_mock,
6
                               get_switch_mock, get_test_client)
7
8
from kytos.core.events import KytosEvent
9
from napps.kytos.of_lldp.utils import get_cookie
10
from tests.helpers import get_topology_mock
11
12
13
@patch('napps.kytos.of_lldp.managers.LivenessManager.consume_hello_if_enabled')
14
@patch('napps.kytos.of_lldp.loop_manager.LoopManager.process_if_looped')
15
@patch('kytos.core.buffers.KytosEventBuffer.aput')
16
@patch('kytos.core.controller.Controller.get_switch_by_dpid')
17
@patch('napps.kytos.of_lldp.main.Main._unpack_non_empty')
18
@patch('napps.kytos.of_lldp.main.UBInt32')
19
@patch('napps.kytos.of_lldp.main.DPID')
20
@patch('napps.kytos.of_lldp.main.LLDP')
21
@patch('napps.kytos.of_lldp.main.Ethernet')
22
async def test_on_ofpt_packet_in(*args):
23
    """Test on_ofpt_packet_in."""
24
    (mock_ethernet, mock_lldp, mock_dpid, mock_ubint32,
25
     mock_unpack_non_empty, mock_get_switch_by_dpid,
26
     _, mock_process_looped, mock_consume_hello_if_enabled) = args
27
28
    # pylint: disable=bad-option-value, import-outside-toplevel
29
    from napps.kytos.of_lldp.main import Main
30
    Main.get_liveness_controller = MagicMock()
31
    topology = get_topology_mock()
32
    controller = get_controller_mock()
33
    controller.switches = topology.switches
34
    napp = Main(controller)
35
36
    switch = get_switch_mock("00:00:00:00:00:00:00:01", 0x04)
37
    message = MagicMock(in_port=1, data='data')
38
    event = KytosEvent('ofpt_packet_in', content={'source': switch.connection,
39
                       'message': message})
40
41
    mocked, ethernet, lldp, dpid, port_b = [MagicMock() for _ in range(5)]
42
    mocked.value = 1
43
    mock_ubint32.return_value = mocked
44
    ethernet.ether_type = 0x88CC
45
    ethernet.data = 'eth_data'
46
    lldp.chassis_id.sub_value = 'chassis_id'
47
    lldp.port_id.sub_value = 'port_id'
48
    dpid.value = "00:00:00:00:00:00:00:02"
49
    port_b.value = 2
50
51
    mock_unpack_non_empty.side_effect = [ethernet, lldp, dpid, port_b]
52
    mock_get_switch_by_dpid.return_value = get_switch_mock(dpid.value,
53
                                                           0x04)
54
    await napp.on_ofpt_packet_in(event)
55
56
    calls = [call(mock_ethernet, message.data),
57
             call(mock_lldp, ethernet.data),
58
             call(mock_dpid, lldp.chassis_id.sub_value),
59
             call(mock_ubint32, lldp.port_id.sub_value)]
60
    mock_unpack_non_empty.assert_has_calls(calls)
61
    mock_process_looped.assert_called()
62
    assert mock_consume_hello_if_enabled.call_count == 1
63
    assert controller.buffers.app.aput.call_count == 1
64
65
66
# pylint: disable=protected-access,too-many-public-methods
67
class TestMain(TestCase):
68
    """Tests for the Main class."""
69
70
    def setUp(self):
71
        """Execute steps before each tests."""
72
        self.server_name_url = 'http://127.0.0.1:8181/api/kytos/of_lldp'
73
74
        patch('kytos.core.helpers.run_on_thread', lambda x: x).start()
75
        # pylint: disable=bad-option-value, import-outside-toplevel
76
        from napps.kytos.of_lldp.main import Main
77
        self.addCleanup(patch.stopall)
78
        Main.get_liveness_controller = MagicMock()
79
        self.topology = get_topology_mock()
80
        controller = get_controller_mock()
81
        controller.switches = self.topology.switches
82
83
        self.napp = Main(controller)
84
85
    def get_topology_interfaces(self):
86
        """Return interfaces present in topology."""
87
        interfaces = []
88
        for switch in list(self.topology.switches.values()):
89
            interfaces += list(switch.interfaces.values())
90
        return interfaces
91
92
    @patch('napps.kytos.of_lldp.main.of_msg_prio')
93
    @patch('kytos.core.buffers.KytosEventBuffer.put')
94
    @patch('napps.kytos.of_lldp.main.KytosEvent')
95
    @patch('napps.kytos.of_lldp.main.VLAN')
96
    @patch('napps.kytos.of_lldp.main.Ethernet')
97
    @patch('napps.kytos.of_lldp.main.DPID')
98
    @patch('napps.kytos.of_lldp.main.LLDP')
99
    def test_execute(self, *args):
100
        """Test execute method."""
101
        (_, _, mock_ethernet, _, mock_kytos_event,
102
         mock_buffer_put, mock_of_msg_prio) = args
103
104
        ethernet = MagicMock()
105
        ethernet.pack.return_value = 'pack'
106
        interfaces = self.get_topology_interfaces()
107
        po_args = [(interface.switch.connection.protocol.version,
108
                    interface.port_number, 'pack') for interface in interfaces]
109
110
        mock_ethernet.return_value = ethernet
111
        mock_kytos_event.side_effect = po_args
112
113
        mock_publish_stopped = MagicMock()
114
        self.napp.try_to_publish_stopped_loops = mock_publish_stopped
115
        self.napp.execute()
116
117
        mock_of_msg_prio.assert_called()
118
        mock_buffer_put.assert_has_calls([call(arg)
119
                                          for arg in po_args])
120
        mock_publish_stopped.assert_called()
121
122
    @patch('requests.delete')
123
    @patch('requests.post')
124
    def test_handle_lldp_flows(self, mock_post, mock_delete):
125
        """Test handle_lldp_flow method."""
126
        dpid = "00:00:00:00:00:00:00:01"
127
        switch = get_switch_mock("00:00:00:00:00:00:00:01", 0x04)
128
        self.napp.controller.switches = {dpid: switch}
129
        event_post = get_kytos_event_mock(name='kytos/topology.switch.enabled',
130
                                          content={'dpid': dpid})
131
132
        event_del = get_kytos_event_mock(name='kytos/topology.switch.disabled',
133
                                         content={'dpid': dpid})
134
135
        mock_post.return_value = MagicMock(status_code=202)
136
        mock_delete.return_value = MagicMock(status_code=202)
137
138
        self.napp._handle_lldp_flows(event_post)
139
        mock_post.assert_called()
140
141
        self.napp._handle_lldp_flows(event_del)
142
        mock_delete.assert_called()
143
144
    @patch("time.sleep")
145
    @patch("requests.post")
146
    def test_handle_lldp_flows_retries(self, mock_post, _):
147
        """Test handle_lldp_flow method retries."""
148
        dpid = "00:00:00:00:00:00:00:01"
149
        switch = get_switch_mock("00:00:00:00:00:00:00:01", 0x04)
150
        self.napp.controller.switches = {dpid: switch}
151
        event_post = get_kytos_event_mock(name="kytos/topology.switch.enabled",
152
                                          content={"dpid": dpid})
153
154
        mock = MagicMock()
155
        mock.request.method = "POST"
156
        mock.status_code = 500
157
        mock.text = "some_err"
158
        mock_post.return_value = mock
159
        self.napp._handle_lldp_flows(event_post)
160
        self.assertTrue(mock_post.call_count, 3)
161
162
    @patch('napps.kytos.of_lldp.main.PO13')
163
    @patch('napps.kytos.of_lldp.main.PO10')
164
    @patch('napps.kytos.of_lldp.main.AO13')
165
    @patch('napps.kytos.of_lldp.main.AO10')
166
    def test_build_lldp_packet_out(self, *args):
167
        """Test _build_lldp_packet_out method."""
168
        (mock_ao10, mock_ao13, mock_po10, mock_po13) = args
169
170
        ao10 = MagicMock()
171
        ao13 = MagicMock()
172
        po10 = MagicMock()
173
        po10.actions = []
174
        po13 = MagicMock()
175
        po13.actions = []
176
177
        mock_ao10.return_value = ao10
178
        mock_ao13.return_value = ao13
179
        mock_po10.return_value = po10
180
        mock_po13.return_value = po13
181
182
        packet_out10 = self.napp._build_lldp_packet_out(0x01, 1, 'data1')
183
        packet_out13 = self.napp._build_lldp_packet_out(0x04, 2, 'data2')
184
        packet_out14 = self.napp._build_lldp_packet_out(0x05, 3, 'data3')
185
186
        self.assertEqual(packet_out10.data, 'data1')
187
        self.assertEqual(packet_out10.actions, [ao10])
188
        self.assertEqual(packet_out10.actions[0].port, 1)
189
190
        self.assertEqual(packet_out13.data, 'data2')
191
        self.assertEqual(packet_out13.actions, [ao13])
192
        self.assertEqual(packet_out13.actions[0].port, 2)
193
194
        self.assertIsNone(packet_out14)
195
196
    @patch('napps.kytos.of_lldp.main.settings')
197
    @patch('napps.kytos.of_lldp.main.EtherType')
198
    @patch('napps.kytos.of_lldp.main.Port13')
199
    @patch('napps.kytos.of_lldp.main.Port10')
200
    def test_build_lldp_flow(self, *args):
201
        """Test _build_lldp_flow method."""
202
        (mock_v0x01_port, mock_v0x04_port, mock_ethertype,
203
         mock_settings) = args
204
        self.napp.vlan_id = None
205
        mock_v0x01_port.OFPP_CONTROLLER = 123
206
        mock_v0x04_port.OFPP_CONTROLLER = 1234
207
208
        mock_ethertype.LLDP = 10
209
        mock_settings.FLOW_VLAN_VID = None
210
        mock_settings.FLOW_PRIORITY = 1500
211
        mock_settings.TABLE_ID = 0
212
        dpid = "00:00:00:00:00:00:00:01"
213
214
        flow = {}
215
        match = {}
216
        flow['priority'] = 1500
217
        flow['table_id'] = 0
218
        match['dl_type'] = 10
219
220
        flow['match'] = match
221
        expected_flow_v0x01 = flow.copy()
222
        expected_flow_v0x04 = flow.copy()
223
        expected_flow_v0x01['cookie'] = get_cookie(dpid)
224
        expected_flow_v0x01['cookie_mask'] = 0xffffffffffffffff
225
        expected_flow_v0x04['cookie'] = get_cookie(dpid)
226
        expected_flow_v0x04['cookie_mask'] = 0xffffffffffffffff
227
228
        expected_flow_v0x01['actions'] = [{'action_type': 'output',
229
                                           'port': 123}]
230
231
        expected_flow_v0x04['actions'] = [{'action_type': 'output',
232
                                           'port': 1234}]
233
234
        flow_mod10 = self.napp._build_lldp_flow(0x01, get_cookie(dpid))
235
        flow_mod13 = self.napp._build_lldp_flow(0x04, get_cookie(dpid))
236
237
        self.assertDictEqual(flow_mod10, expected_flow_v0x01)
238
        self.assertDictEqual(flow_mod13, expected_flow_v0x04)
239
240
    def test_unpack_non_empty(self):
241
        """Test _unpack_non_empty method."""
242
        desired_class = MagicMock()
243
        data = MagicMock()
244
        data.value = 'data'
245
246
        obj = self.napp._unpack_non_empty(desired_class, data)
247
248
        obj.unpack.assert_called_with('data')
249
250
    def test_get_data(self):
251
        """Test _get_data method."""
252
        req = MagicMock()
253
        interfaces = ['00:00:00:00:00:00:00:01:1', '00:00:00:00:00:00:00:01:2']
254
        req.get_json.return_value = {'interfaces': interfaces}
255
256
        data = self.napp._get_data(req)
257
258
        self.assertEqual(data, interfaces)
259
260
    def test_load_liveness(self) -> None:
261
        """Test load_liveness."""
262
        self.napp.load_liveness()
263
        count = self.napp.liveness_controller.get_enabled_interfaces.call_count
264
        assert count == 1
265
266
    def test_handle_topology_loaded(self) -> None:
267
        """Test handle_topology_loaded."""
268
        event = KytosEvent("kytos/topology.topology_loaded",
269
                           content={"topology": {}})
270
        self.napp.load_liveness = MagicMock()
271
        self.napp.loop_manager.handle_topology_loaded = MagicMock()
272
        self.napp.handle_topology_loaded(event)
273
        assert self.napp.loop_manager.handle_topology_loaded.call_count == 1
274
        assert self.napp.load_liveness.call_count == 1
275
276
    def test_publish_liveness_status(self) -> None:
277
        """Test publish_liveness_status."""
278
        self.napp.controller.buffers.app.put = MagicMock()
279
        event_suffix, interfaces = "up", [MagicMock(id=1), MagicMock(id=2)]
280
        self.napp.publish_liveness_status(event_suffix, interfaces)
281
        assert self.napp.controller.buffers.app.put.call_count == 1
282
        event = self.napp.controller.buffers.app.put.call_args[0][0]
283
        assert event.name == f"kytos/of_lldp.liveness.{event_suffix}"
284
        assert event.content["interfaces"] == interfaces
285
286
    def test_get_interfaces(self):
287
        """Test _get_interfaces method."""
288
        expected_interfaces = self.get_topology_interfaces()
289
290
        interfaces = self.napp._get_interfaces()
291
292
        self.assertEqual(interfaces, expected_interfaces)
293
294
    def test_get_interfaces_dict(self):
295
        """Test _get_interfaces_dict method."""
296
        interfaces = self.napp._get_interfaces()
297
        expected_interfaces = {inter.id: inter for inter in interfaces}
298
299
        interfaces_dict = self.napp._get_interfaces_dict(interfaces)
300
301
        self.assertEqual(interfaces_dict, expected_interfaces)
302
303
    def test_get_lldp_interfaces(self):
304
        """Test _get_lldp_interfaces method."""
305
        lldp_interfaces = self.napp._get_lldp_interfaces()
306
307
        expected_interfaces = ['00:00:00:00:00:00:00:01:1',
308
                               '00:00:00:00:00:00:00:01:2',
309
                               '00:00:00:00:00:00:00:02:1',
310
                               '00:00:00:00:00:00:00:02:2',
311
                               '00:00:00:00:00:00:00:03:1',
312
                               '00:00:00:00:00:00:00:03:2']
313
314
        self.assertEqual(lldp_interfaces, expected_interfaces)
315
316
    def test_rest_get_lldp_interfaces(self):
317
        """Test get_lldp_interfaces method."""
318
        api = get_test_client(self.napp.controller, self.napp)
319
        url = f'{self.server_name_url}/v1/interfaces'
320
        response = api.open(url, method='GET')
321
322
        expected_data = {"interfaces": ['00:00:00:00:00:00:00:01:1',
323
                                        '00:00:00:00:00:00:00:01:2',
324
                                        '00:00:00:00:00:00:00:02:1',
325
                                        '00:00:00:00:00:00:00:02:2',
326
                                        '00:00:00:00:00:00:00:03:1',
327
                                        '00:00:00:00:00:00:00:03:2']}
328
        self.assertEqual(response.json, expected_data)
329
        self.assertEqual(response.status_code, 200)
330
331
    def test_enable_disable_lldp_200(self):
332
        """Test 200 response for enable_lldp and disable_lldp methods."""
333
        data = {"interfaces": ['00:00:00:00:00:00:00:01:1',
334
                               '00:00:00:00:00:00:00:01:2',
335
                               '00:00:00:00:00:00:00:02:1',
336
                               '00:00:00:00:00:00:00:02:2',
337
                               '00:00:00:00:00:00:00:03:1',
338
                               '00:00:00:00:00:00:00:03:2']}
339
340
        api = get_test_client(self.napp.controller, self.napp)
341
        self.napp.publish_liveness_status = MagicMock()
342
343
        url = f'{self.server_name_url}/v1/interfaces/disable'
344
        disable_response = api.open(url, method='POST', json=data)
345
        assert self.napp.liveness_controller.disable_interfaces.call_count == 1
346
        assert self.napp.publish_liveness_status.call_count == 1
347
348
        url = f'{self.server_name_url}/v1/interfaces/enable'
349
        enable_response = api.open(url, method='POST', json=data)
350
351
        self.assertEqual(disable_response.status_code, 200)
352
        self.assertEqual(enable_response.status_code, 200)
353
354
    def test_enable_disable_lldp_404(self):
355
        """Test 404 response for enable_lldp and disable_lldp methods."""
356
        data = {"interfaces": []}
357
358
        self.napp.controller.switches = {}
359
        api = get_test_client(self.napp.controller, self.napp)
360
361
        url = f'{self.server_name_url}/v1/interfaces/disable'
362
        disable_response = api.open(url, method='POST', json=data)
363
364
        url = f'{self.server_name_url}/v1/interfaces/enable'
365
        enable_response = api.open(url, method='POST', json=data)
366
367
        self.assertEqual(disable_response.status_code, 404)
368
        self.assertEqual(enable_response.status_code, 404)
369
370
    def test_enable_disable_lldp_400(self):
371
        """Test 400 response for enable_lldp and disable_lldp methods."""
372
        data = {"interfaces": ['00:00:00:00:00:00:00:01:1',
373
                               '00:00:00:00:00:00:00:01:2',
374
                               '00:00:00:00:00:00:00:02:1',
375
                               '00:00:00:00:00:00:00:02:2',
376
                               '00:00:00:00:00:00:00:03:1',
377
                               '00:00:00:00:00:00:00:03:2',
378
                               '00:00:00:00:00:00:00:04:1']}
379
380
        api = get_test_client(self.napp.controller, self.napp)
381
        self.napp.publish_liveness_status = MagicMock()
382
383
        url = f'{self.server_name_url}/v1/interfaces/disable'
384
        disable_response = api.open(url, method='POST', json=data)
385
        assert self.napp.publish_liveness_status.call_count == 1
386
387
        url = f'{self.server_name_url}/v1/interfaces/enable'
388
        enable_response = api.open(url, method='POST', json=data)
389
390
        self.assertEqual(disable_response.status_code, 400)
391
        self.assertEqual(enable_response.status_code, 400)
392
393
    def test_get_time(self):
394
        """Test get polling time."""
395
        api = get_test_client(self.napp.controller, self.napp)
396
397
        url = f'{self.server_name_url}/v1/polling_time'
398
        response = api.open(url, method='GET')
399
400
        self.assertEqual(response.status_code, 200)
401
402
    def test_set_time(self):
403
        """Test update polling time."""
404
        data = {"polling_time": 5}
405
406
        api = get_test_client(self.napp.controller, self.napp)
407
408
        url = f'{self.server_name_url}/v1/polling_time'
409
        response = api.open(url, method='POST', json=data)
410
411
        self.assertEqual(response.status_code, 200)
412
        self.assertEqual(self.napp.polling_time, data['polling_time'])
413
414
    def test_set_time_400(self):
415
        """Test fail case the update polling time."""
416
        api = get_test_client(self.napp.controller, self.napp)
417
418
        url = f'{self.server_name_url}/v1/polling_time'
419
420
        data = {'polling_time': 'A'}
421
        response = api.open(url, method='POST', json=data)
422
        self.assertEqual(response.status_code, 400)
423
424
    def test_endpoint_enable_liveness(self):
425
        """Test POST v1/liveness/enable."""
426
        self.napp.liveness_manager.enable = MagicMock()
427
        self.napp.publish_liveness_status = MagicMock()
428
        api = get_test_client(self.napp.controller, self.napp)
429
        url = f"{self.server_name_url}/v1/liveness/enable"
430
        data = {"interfaces": ["00:00:00:00:00:00:00:01:1"]}
431
        response = api.open(url, method="POST", json=data)
432
        assert self.napp.liveness_controller.enable_interfaces.call_count == 1
433
        assert self.napp.liveness_manager.enable.call_count == 1
434
        assert self.napp.publish_liveness_status.call_count == 1
435
        assert response.json == {}
436
        assert response.status_code == 200
437
438
    def test_endpoint_disable_liveness(self):
439
        """Test POST v1/liveness/disable."""
440
        self.napp.liveness_manager.disable = MagicMock()
441
        self.napp.publish_liveness_status = MagicMock()
442
        api = get_test_client(self.napp.controller, self.napp)
443
        url = f"{self.server_name_url}/v1/liveness/disable"
444
        data = {"interfaces": ["00:00:00:00:00:00:00:01:1"]}
445
        response = api.open(url, method='POST', json=data)
446
        assert self.napp.liveness_controller.disable_interfaces.call_count == 1
447
        assert self.napp.liveness_manager.disable.call_count == 1
448
        assert self.napp.publish_liveness_status.call_count == 1
449
        assert response.json == {}
450
        assert response.status_code == 200
451
452
    def test_endpoint_get_liveness(self):
453
        """Test GET v1/liveness/."""
454
        self.napp.liveness_manager.enable = MagicMock()
455
        self.napp.publish_liveness_status = MagicMock()
456
        api = get_test_client(self.napp.controller, self.napp)
457
        url = f"{self.server_name_url}/v1/liveness/"
458
        response = api.open(url, method="GET")
459
        assert response.json == {"interfaces": []}
460
        assert response.status_code == 200
461
462
    def test_endpoint_get_pair_liveness(self):
463
        """Test GET v1/liveness//pair."""
464
        self.napp.liveness_manager.enable = MagicMock()
465
        self.napp.publish_liveness_status = MagicMock()
466
        api = get_test_client(self.napp.controller, self.napp)
467
        url = f"{self.server_name_url}/v1/liveness/pair"
468
        response = api.open(url, method="GET")
469
        assert response.json == {"pairs": []}
470
        assert response.status_code == 200
471