Passed
Pull Request — master (#36)
by Vinicius
02:59
created

TestMain.test_is_lldp_looped()   A

Complexity

Conditions 3

Size

Total Lines 19
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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