Passed
Pull Request — master (#117)
by Carlos
02:58
created

TestMain.test_no_strict_delete()   A

Complexity

Conditions 1

Size

Total Lines 49
Code Lines 34

Duplication

Lines 49
Ratio 100 %

Importance

Changes 0
Metric Value
cc 1
eloc 34
nop 2
dl 49
loc 49
rs 9.064
c 0
b 0
f 0
1
"""Test Main methods."""
2
from unittest import TestCase
3
from unittest.mock import MagicMock, patch
4
5
from kytos.lib.helpers import (get_connection_mock, get_controller_mock,
6
                               get_kytos_event_mock, get_switch_mock,
7
                               get_test_client)
8
9
10
# pylint: disable=protected-access
11
class TestMain(TestCase):
12
    """Tests for the Main class."""
13
14
    API_URL = 'http://localhost:8181/api/kytos/flow_manager'
15
16
    def setUp(self):
17
        patch('kytos.core.helpers.run_on_thread', lambda x: x).start()
18
        # pylint: disable=import-outside-toplevel
19
        from napps.kytos.flow_manager.main import Main
20
21
        self.addCleanup(patch.stopall)
22
23
        controller = get_controller_mock()
24
        self.switch_01 = get_switch_mock("00:00:00:00:00:00:00:01", 0x04)
25
        self.switch_01.is_enabled.return_value = True
26
        self.switch_01.flows = []
27
28
        self.switch_02 = get_switch_mock("00:00:00:00:00:00:00:02", 0x04)
29
        self.switch_02.is_enabled.return_value = False
30
        self.switch_02.flows = []
31
32
        controller.switches = {"00:00:00:00:00:00:00:01": self.switch_01,
33
                               "00:00:00:00:00:00:00:02": self.switch_02}
34
35
        self.napp = Main(controller)
36
37
    def test_rest_list_without_dpid(self):
38
        """Test list rest method withoud dpid."""
39
        flow_1 = MagicMock()
40
        flow_1.as_dict.return_value = {'flow_1': 'data'}
41
        flow_2 = MagicMock()
42
        flow_2.as_dict.return_value = {'flow_2': 'data'}
43
        self.switch_01.flows.append(flow_1)
44
        self.switch_02.flows.append(flow_2)
45
46
        api = get_test_client(self.napp.controller, self.napp)
47
        url = f'{self.API_URL}/v2/flows'
48
49
        response = api.get(url)
50
        expected = {'00:00:00:00:00:00:00:01': {'flows': [{'flow_1': 'data'}]},
51
                    '00:00:00:00:00:00:00:02': {'flows': [{'flow_2': 'data'}]}}
52
53
        self.assertEqual(response.json, expected)
54
        self.assertEqual(response.status_code, 200)
55
56
    def test_rest_list_with_dpid(self):
57
        """Test list rest method with dpid."""
58
        flow_1 = MagicMock()
59
        flow_1.as_dict.return_value = {'flow_1': 'data'}
60
        self.switch_01.flows.append(flow_1)
61
62
        api = get_test_client(self.napp.controller, self.napp)
63
        url = f'{self.API_URL}/v2/flows/00:00:00:00:00:00:00:01'
64
65
        response = api.get(url)
66
        expected = {'00:00:00:00:00:00:00:01': {'flows': [{'flow_1': 'data'}]}}
67
68
        self.assertEqual(response.json, expected)
69
        self.assertEqual(response.status_code, 200)
70
71
    @patch('napps.kytos.flow_manager.main.Main._install_flows')
72
    def test_rest_add_and_delete_without_dpid(self, mock_install_flows):
73
        """Test add and delete rest method without dpid."""
74
        api = get_test_client(self.napp.controller, self.napp)
75
76
        for method in ['flows', 'delete']:
77
            url = f'{self.API_URL}/v2/{method}'
78
79
            response_1 = api.post(url, json={'data': '123'})
80
            response_2 = api.post(url)
81
82
            self.assertEqual(response_1.status_code, 200)
83
            self.assertEqual(response_2.status_code, 404)
84
85
        self.assertEqual(mock_install_flows.call_count, 2)
86
87
    @patch('napps.kytos.flow_manager.main.Main._install_flows')
88
    def test_rest_add_and_delete_with_dpid(self, mock_install_flows):
89
        """Test add and delete rest method with dpid."""
90
        api = get_test_client(self.napp.controller, self.napp)
91
92
        for method in ['flows', 'delete']:
93
            url_1 = f'{self.API_URL}/v2/{method}/00:00:00:00:00:00:00:01'
94
            url_2 = f'{self.API_URL}/v2/{method}/00:00:00:00:00:00:00:02'
95
            url_3 = f'{self.API_URL}/v2/{method}/00:00:00:00:00:00:00:03'
96
97
            response_1 = api.post(url_1)
98
            response_2 = api.post(url_1, json={'data': '123'})
99
            response_3 = api.post(url_2, json={'data': '123'})
100
            response_4 = api.post(url_3, json={'data': '123'})
101
102
            self.assertEqual(response_1.status_code, 404)
103
            self.assertEqual(response_2.status_code, 200)
104
            if method == 'flows':
105
                self.assertEqual(response_3.status_code, 404)
106
            else:
107
                self.assertEqual(response_3.status_code, 200)
108
            self.assertEqual(response_4.status_code, 404)
109
110
        self.assertEqual(mock_install_flows.call_count, 3)
111
112
    def test_get_all_switches_enabled(self):
113
        """Test _get_all_switches_enabled method."""
114
        switches = self.napp._get_all_switches_enabled()
115
116
        self.assertEqual(switches, [self.switch_01])
117
118
    @patch('napps.kytos.flow_manager.main.Main._store_changed_flows')
119
    @patch('napps.kytos.flow_manager.main.Main._send_napp_event')
120
    @patch('napps.kytos.flow_manager.main.Main._add_flow_mod_sent')
121
    @patch('napps.kytos.flow_manager.main.Main._send_flow_mod')
122
    @patch('napps.kytos.flow_manager.main.FlowFactory.get_class')
123
    def test_install_flows(self, *args):
124
        """Test _install_flows method."""
125
        (mock_flow_factory, mock_send_flow_mod, mock_add_flow_mod_sent,
126
         mock_send_napp_event, _) = args
127
        serializer = MagicMock()
128
        flow = MagicMock()
129
        flow_mod = MagicMock()
130
131
        flow.as_of_add_flow_mod.return_value = flow_mod
132
        serializer.from_dict.return_value = flow
133
        mock_flow_factory.return_value = serializer
134
135
        flows_dict = {'flows': [MagicMock()]}
136
        switches = [self.switch_01]
137
        self.napp._install_flows('add', flows_dict, switches)
138
139
        mock_send_flow_mod.assert_called_with(flow.switch, flow_mod)
140
        mock_add_flow_mod_sent.assert_called_with(flow_mod.header.xid,
141
                                                  flow, 'add')
142
        mock_send_napp_event.assert_called_with(self.switch_01, flow, 'add')
143
144
    def test_add_flow_mod_sent(self):
145
        """Test _add_flow_mod_sent method."""
146
        xid = 0
147
        flow = MagicMock()
148
149
        self.napp._add_flow_mod_sent(xid, flow, 'add')
150
151
        self.assertEqual(self.napp._flow_mods_sent[xid], (flow, 'add'))
152
153
    @patch('kytos.core.buffers.KytosEventBuffer.put')
154
    def test_send_flow_mod(self, mock_buffers_put):
155
        """Test _send_flow_mod method."""
156
        switch = get_switch_mock("00:00:00:00:00:00:00:01", 0x04)
157
        flow_mod = MagicMock()
158
159
        self.napp._send_flow_mod(switch, flow_mod)
160
161
        mock_buffers_put.assert_called()
162
163
    @patch('kytos.core.buffers.KytosEventBuffer.put')
164
    def test_send_napp_event(self, mock_buffers_put):
165
        """Test _send_napp_event method."""
166
        switch = get_switch_mock("00:00:00:00:00:00:00:01", 0x04)
167
        flow = MagicMock()
168
169
        for command in ['add', 'delete', 'error']:
170
            self.napp._send_napp_event(switch, flow, command)
171
172
        self.assertEqual(mock_buffers_put.call_count, 3)
173
174
    @patch('napps.kytos.flow_manager.main.Main._send_napp_event')
175
    def test_handle_errors(self, mock_send_napp_event):
176
        """Test handle_errors method."""
177
        flow = MagicMock()
178
        self.napp._flow_mods_sent[0] = (flow, 'add')
179
180
        switch = get_switch_mock("00:00:00:00:00:00:00:01")
181
        switch.connection = get_connection_mock(
182
            0x04, get_switch_mock("00:00:00:00:00:00:00:02"))
183
184
        protocol = MagicMock()
185
        protocol.unpack.return_value = 'error_packet'
186
187
        switch.connection.protocol = protocol
188
189
        message = MagicMock()
190
        message.header.xid.value = 0
191
        message.error_type = 2
192
        message.code = 5
193
        event = get_kytos_event_mock(name='.*.of_core.*.ofpt_error',
194
                                     content={'message': message,
195
                                              'source': switch.connection})
196
        self.napp.handle_errors(event)
197
198
        mock_send_napp_event.assert_called_with(flow.switch, flow, 'error',
199
                                                error_command='add',
200
                                                error_code=5, error_type=2)
201
202
    @patch("napps.kytos.flow_manager.main.StoreHouse.get_data")
203
    def test_load_flows(self, mock_storehouse):
204
        """Test load flows."""
205
        self.napp._load_flows()
206
        mock_storehouse.assert_called()
207
208
    @patch("napps.kytos.flow_manager.main.Main._install_flows")
209
    def test_resend_stored_flows(self, mock_install_flows):
210
        """Test resend stored flows."""
211
        dpid = "00:00:00:00:00:00:00:01"
212
        switch = get_switch_mock(dpid, 0x04)
213
        mock_event = MagicMock()
214
        flow = {"command": "add", "flow": MagicMock()}
215
216
        flows = {"flow_list": [flow]}
217
        mock_event.content = {"switch": switch}
218
        self.napp.controller.switches = {dpid: switch}
219
        self.napp.stored_flows = {dpid: flows}
220
        self.napp.resend_stored_flows(mock_event)
221
        mock_install_flows.assert_called()
222
223
    @patch("napps.kytos.of_core.flow.FlowFactory.get_class")
224
    @patch("napps.kytos.flow_manager.main.StoreHouse.save_flow")
225
    def test_store_changed_flows(self, mock_save_flow, _):
226
        """Test store changed flows."""
227
        dpid = "00:00:00:00:00:00:00:01"
228
        switch = get_switch_mock(dpid, 0x04)
229
        switch.id = dpid
230
        flow = {
231
            "priority": 17,
232
            "cookie": 84114964,
233
            "command": "add",
234
            "match": {"dl_dst": "00:15:af:d5:38:98"},
235
        }
236
        match_fields = {
237
            "priority": 17,
238
            "cookie": 84114964,
239
            "command": "add",
240
            "dl_dst": "00:15:af:d5:38:98",
241
        }
242
        flows = {"flow": flow}
243
244
        command = "add"
245
        flow_list = {
246
            "flow_list": [
247
                {"match_fields": match_fields, "command": "delete",
248
                 "flow": flow}
249
            ]
250
        }
251
        self.napp.stored_flows = {dpid: flow_list}
252
        self.napp._store_changed_flows(command, flows, switch)
253
        mock_save_flow.assert_called()
254
255
        self.napp.stored_flows = {}
256
        self.napp._store_changed_flows(command, flows, switch)
257
        mock_save_flow.assert_called()
258
259 View Code Duplication
    @patch('napps.kytos.flow_manager.main.Main._install_flows')
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
260
    @patch('napps.kytos.flow_manager.main.FlowFactory.get_class')
261
    def test_check_switch_consistency_add(self, *args):
262
        """Test check_switch_consistency method.
263
264
        This test checks the case when a flow is missing in switch and have the
265
        ADD command.
266
        """
267
        (mock_flow_factory, mock_install_flows) = args
268
        dpid = "00:00:00:00:00:00:00:01"
269
        switch = get_switch_mock(dpid, 0x04)
270
        switch.flows = []
271
272
        flow_1 = MagicMock()
273
        flow_1.as_dict.return_value = {'flow_1': 'data'}
274
275
        flow_list = [{"command": "add",
276
                      "flow": {'flow_1': 'data'}
277
                      }]
278
        serializer = MagicMock()
279
280
        mock_flow_factory.return_value = serializer
281
        self.napp.stored_flows = {dpid: {"flow_list": flow_list}}
282
        self.napp.check_switch_consistency(switch)
283
        mock_install_flows.assert_called()
284
285 View Code Duplication
    @patch('napps.kytos.flow_manager.main.Main._install_flows')
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
286
    @patch('napps.kytos.flow_manager.main.FlowFactory.get_class')
287
    def test_check_switch_consistency_delete(self, *args):
288
        """Test check_switch_consistency method.
289
290
        This test checks the case when a flow is missing in switch and have the
291
        DELETE command.
292
        """
293
        (mock_flow_factory, mock_install_flows) = args
294
        dpid = "00:00:00:00:00:00:00:01"
295
        switch = get_switch_mock(dpid, 0x04)
296
297
        flow_1 = MagicMock()
298
        flow_1.as_dict.return_value = {'flow_1': 'data'}
299
300
        flow_list = [{"command": "delete",
301
                      "flow": {'flow_1': 'data'}
302
                      }]
303
        serializer = MagicMock()
304
        serializer.from_dict.return_value = flow_1
305
306
        switch.flows = [flow_1]
307
308
        mock_flow_factory.return_value = serializer
309
        self.napp.stored_flows = {dpid: {"flow_list": flow_list}}
310
        self.napp.check_switch_consistency(switch)
311
        mock_install_flows.assert_called()
312
313 View Code Duplication
    @patch('napps.kytos.flow_manager.main.Main._install_flows')
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
314
    @patch('napps.kytos.flow_manager.main.FlowFactory.get_class')
315
    def test_check_storehouse_consistency(self, *args):
316
        """Test check_storehouse_consistency method.
317
318
        This test checks the case when a flow is missing in storehouse.
319
        """
320
        (mock_flow_factory, mock_install_flows) = args
321
        dpid = "00:00:00:00:00:00:00:01"
322
        switch = get_switch_mock(dpid, 0x04)
323
324
        flow_1 = MagicMock()
325
        flow_1.as_dict.return_value = {'flow_1': 'data'}
326
327
        switch.flows = [flow_1]
328
329
        flow_list = [{"command": "add",
330
                      "flow": {'flow_2': 'data'}
331
                      }]
332
        serializer = MagicMock()
333
334
        mock_flow_factory.return_value = serializer
335
        self.napp.stored_flows = {dpid: {"flow_list": flow_list}}
336
        self.napp.check_storehouse_consistency(switch)
337
        mock_install_flows.assert_called()
338
339 View Code Duplication
    @patch('napps.kytos.flow_manager.main.Main._install_flows')
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
340
    @patch('napps.kytos.flow_manager.main.FlowFactory.get_class')
341
    @patch("napps.kytos.flow_manager.main.StoreHouse.save_flow")
342
    def test_no_strict_delete(self, *args):
343
        """Test the non-strict matching method.
344
345
        Test non-strict matching to delete a Flow using a cookie.
346
        """
347
        (mock_save_flow, _, _) = args
348
        dpid = "00:00:00:00:00:00:00:01"
349
        switch = get_switch_mock(dpid, 0x04)
350
        switch.id = dpid
351
        stored_flow = {
352
                        "command": "add",
353
                        "flow": {
354
                            "actions": [
355
                                {
356
                                    "action_type": "set_vlan",
357
                                    "vlan_id": 300
358
                                }
359
                            ],
360
                            "cookie": 6191162389751548793,
361
                            "match": {
362
                                "dl_vlan": 300,
363
                                "in_port": 1
364
                            }
365
                        }
366
                    }
367
        stored_flow2 = {
368
                        "command": "add",
369
                        "flow": {
370
                                "actions": [],
371
                                "cookie": 4961162389751548787,
372
                                "match": {
373
                                    "in_port": 2
374
                                    }
375
                                }
376
                        }
377
        flow_to_install = {
378
                            "cookie": 6191162389751548793,
379
                            "cookie_mask": 18446744073709551615
380
                        }
381
        flow_list = {"flow_list": [stored_flow, stored_flow2]}
382
        command = "delete"
383
        self.napp.stored_flows = {dpid: flow_list}
384
385
        self.napp._store_changed_flows(command, flow_to_install, switch)
386
        mock_save_flow.assert_called()
387
        self.assertEqual(len(self.napp.stored_flows), 1)
388
389 View Code Duplication
    @patch('napps.kytos.flow_manager.main.Main._install_flows')
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
390
    @patch('napps.kytos.flow_manager.main.FlowFactory.get_class')
391
    @patch("napps.kytos.flow_manager.main.StoreHouse.save_flow")
392
    def test_no_strict_delete_with_ipv4(self, *args):
393
        """Test the non-strict matching method.
394
395
        Test non-strict matching to delete a Flow using IPv4.
396
        """
397
        (mock_save_flow, _, _) = args
398
        dpid = "00:00:00:00:00:00:00:01"
399
        switch = get_switch_mock(dpid, 0x04)
400
        switch.id = dpid
401
        stored_flow = {
402
                    "command": "add",
403
                    "flow": {
404
                        "priority": 10,
405
                        "cookie": 84114904,
406
                        "match": {
407
                            "ipv4_src": "192.168.1.120",
408
                            "ipv4_dst": "192.168.0.2",
409
                        },
410
                        "actions": []
411
                        }
412
                    }
413
        stored_flow2 = {
414
                        "command": "add",
415
                        "flow": {
416
                                    "actions": [],
417
                                    "cookie": 4961162389751548787,
418
                                    "match": {
419
                                        "in_port": 2
420
                                    }
421
                                }
422
                        }
423
        flow_to_install = {"match": {"ipv4_src": '192.168.1.1/24'}}
424
        flow_list = {"flow_list": [stored_flow, stored_flow2]}
425
        command = "delete"
426
        self.napp.stored_flows = {dpid: flow_list}
427
428
        self.napp._store_changed_flows(command, flow_to_install, switch)
429
        mock_save_flow.assert_called()
430
        self.assertEqual(len(self.napp.stored_flows[dpid]['flow_list']), 2)
431
432 View Code Duplication
    @patch('napps.kytos.flow_manager.main.Main._install_flows')
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
433
    @patch('napps.kytos.flow_manager.main.FlowFactory.get_class')
434
    @patch("napps.kytos.flow_manager.main.StoreHouse.save_flow")
435
    def test_no_strict_delete_with_ipv4_fail(self, *args):
436
        """Test the non-strict matching method.
437
438
        Test non-strict Fail case matching to delete a Flow using IPv4.
439
        """
440
        (mock_save_flow, _, _) = args
441
        dpid = "00:00:00:00:00:00:00:01"
442
        switch = get_switch_mock(dpid, 0x04)
443
        switch.id = dpid
444
        stored_flow = {
445
                    "command": "add",
446
                    "flow": {
447
                        "priority": 10,
448
                        "cookie": 84114904,
449
                        "match": {
450
                            "ipv4_src": "192.168.2.1",
451
                            "ipv4_dst": "192.168.0.2",
452
                        },
453
                        "actions": []
454
                        }
455
                    }
456
        stored_flow2 = {
457
                        "command": "add",
458
                        "flow": {
459
                                    "actions": [],
460
                                    "cookie": 4961162389751548787,
461
                                    "match": {
462
                                        "in_port": 2
463
                                    }
464
                                }
465
                        }
466
        flow_to_install = {"match": {"ipv4_src": '192.168.1.1/24'}}
467
        flow_list = {"flow_list": [stored_flow, stored_flow2]}
468
        command = "delete"
469
        self.napp.stored_flows = {dpid: flow_list}
470
471
        self.napp._store_changed_flows(command, flow_to_install, switch)
472
        mock_save_flow.assert_called()
473
        self.assertEqual(len(self.napp.stored_flows[dpid]['flow_list']), 3)
474