Passed
Pull Request — master (#140)
by Rogerio
03:44
created

TestMain.test_create_schedule()   B

Complexity

Conditions 1

Size

Total Lines 48
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 37
nop 2
dl 0
loc 48
rs 8.9919
c 0
b 0
f 0
1
"""Module to test the main napp file."""
2
import json
3
from unittest import TestCase
4
from unittest.mock import patch
5
6
from kytos.core.interface import UNI, Interface
7
8
from napps.kytos.mef_eline.main import Main
9
from tests.helpers import get_controller_mock
10
11
12
class TestMain(TestCase):  # pylint: disable=too-many-public-methods
13
    """Test the Main class."""
14
15
    def setUp(self):
16
        """Execute steps before each tests.
17
18
        Set the server_name_url_url from kytos/mef_eline
19
        """
20
        self.server_name_url = 'http://localhost:8181/api/kytos/mef_eline'
21
        self.napp = Main(get_controller_mock())
22
23
    def test_get_event_listeners(self):
24
        """Verify all event listeners registered."""
25
        expected_events = ['kytos/core.shutdown',
26
                           'kytos/core.shutdown.kytos/mef_eline',
27
                           'kytos/topology.link_up',
28
                           'kytos/topology.link_down']
29
        actual_events = self.napp.listeners()
30
31
        for _event in expected_events:
32
            self.assertIn(_event, actual_events, '%s' % _event)
33
34
    def test_verify_api_urls(self):
35
        """Verify all APIs registered."""
36
        expected_urls = [
37
            ({}, {'POST', 'OPTIONS'},
38
             '/api/kytos/mef_eline/v2/evc/'),
39
40
            ({}, {'OPTIONS', 'HEAD', 'GET'},
41
             '/api/kytos/mef_eline/v2/evc/'),
42
43
            ({'circuit_id': '[circuit_id]'}, {'OPTIONS', 'DELETE'},
44
             '/api/kytos/mef_eline/v2/evc/<circuit_id>'),
45
46
            ({'circuit_id': '[circuit_id]'}, {'OPTIONS', 'HEAD', 'GET'},
47
             '/api/kytos/mef_eline/v2/evc/<circuit_id>'),
48
49
            ({'circuit_id': '[circuit_id]'}, {'OPTIONS', 'PATCH'},
50
             '/api/kytos/mef_eline/v2/evc/<circuit_id>'),
51
52
            ({}, {'OPTIONS', 'GET', 'HEAD'},
53
             '/api/kytos/mef_eline/v2/evc/schedule'),
54
55
            ({}, {'POST', 'OPTIONS'},
56
             '/api/kytos/mef_eline/v2/evc/schedule/'),
57
58
            ({'schedule_id': '[schedule_id]'},
59
             {'OPTIONS', 'DELETE'},
60
             '/api/kytos/mef_eline/v2/evc/schedule/<schedule_id>'),
61
62
            ({'schedule_id': '[schedule_id]'},
63
             {'OPTIONS', 'PATCH'},
64
             '/api/kytos/mef_eline/v2/evc/schedule/<schedule_id>')
65
            ]
66
67
        urls = self.get_napp_urls(self.napp)
68
        self.assertCountEqual(expected_urls, urls)
69
70
    @patch('napps.kytos.mef_eline.main.Main.uni_from_dict')
71
    @patch('napps.kytos.mef_eline.models.EVCBase._validate')
72
    def test_evc_from_dict(self, _validate_mock, uni_from_dict_mock):
73
        """
74
        Test the helper method that create an EVN from dict.
75
76
        Verify object creation with circuit data and schedule data.
77
        """
78
        _validate_mock.return_value = True
79
        uni_from_dict_mock.side_effect = ['uni_a', 'uni_z']
80
        payload = {
81
            "name": "my evc1",
82
            "uni_a": {
83
                "interface_id": "00:00:00:00:00:00:00:01:1",
84
                "tag": {
85
                    "tag_type": 1,
86
                    "value": 80
87
                }
88
            },
89
            "uni_z": {
90
                "interface_id": "00:00:00:00:00:00:00:02:2",
91
                "tag": {
92
                    "tag_type": 1,
93
                    "value": 1
94
                }
95
            },
96
            "circuit_scheduler": [{
97
                "frequency": "* * * * *",
98
                "action": "create"
99
            }]
100
        }
101
        evc_response = self.napp.evc_from_dict(payload)
102
        self.assertIsNotNone(evc_response)
103
104
    def test_list_without_circuits(self):
105
        """Test if list circuits return 'no circuit stored.'."""
106
        api = self.get_app_test_client(self.napp)
107
        url = f'{self.server_name_url}/v2/evc/'
108
        response = api.get(url)
109
        self.assertEqual(response.status_code, 200, response.data)
110
        self.assertEqual(json.loads(response.data.decode()), {})
111
112
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.get_data')
113
    def test_list_no_circuits_stored(self, storehouse_data_mock):
114
        """Test if list circuits return all circuits stored."""
115
        circuits = {}
116
        storehouse_data_mock.return_value = circuits
117
118
        api = self.get_app_test_client(self.napp)
119
        url = f'{self.server_name_url}/v2/evc/'
120
121
        response = api.get(url)
122
        expected_result = circuits
123
        self.assertEqual(json.loads(response.data), expected_result)
124
125
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.get_data')
126
    def test_list_with_circuits_stored(self, storehouse_data_mock):
127
        """Test if list circuits return all circuits stored."""
128
        circuits = {'1': {'name': 'circuit_1'},
129
                    '2': {'name': 'circuit_2'}}
130
        storehouse_data_mock.return_value = circuits
131
132
        api = self.get_app_test_client(self.napp)
133
        url = f'{self.server_name_url}/v2/evc/'
134
135
        response = api.get(url)
136
        expected_result = circuits
137
        self.assertEqual(json.loads(response.data), expected_result)
138
139 View Code Duplication
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.get_data')
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
140
    def test_circuit_with_valid_id(self, storehouse_data_mock):
141
        """Test if get_circuit return the circuit attributes."""
142
        circuits = {'1': {'name': 'circuit_1'},
143
                    '2': {'name': 'circuit_2'}}
144
        storehouse_data_mock.return_value = circuits
145
146
        api = self.get_app_test_client(self.napp)
147
        url = f'{self.server_name_url}/v2/evc/1'
148
        response = api.get(url)
149
        expected_result = circuits['1']
150
        self.assertEqual(json.loads(response.data), expected_result)
151
152 View Code Duplication
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.get_data')
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
153
    def test_circuit_with_invalid_id(self, storehouse_data_mock):
154
        """Test if get_circuit return invalid circuit_id."""
155
        circuits = {'1': {'name': 'circuit_1'},
156
                    '2': {'name': 'circuit_2'}}
157
        storehouse_data_mock.return_value = circuits
158
159
        api = self.get_app_test_client(self.napp)
160
        url = f'{self.server_name_url}/v2/evc/3'
161
        response = api.get(url)
162
        expected_result = {'response': 'circuit_id 3 not found'}
163
        self.assertEqual(json.loads(response.data), expected_result)
164
165
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.get_data')
166
    @patch('napps.kytos.mef_eline.scheduler.Scheduler.add')
167
    @patch('napps.kytos.mef_eline.main.Main.uni_from_dict')
168
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.save_evc')
169
    @patch('napps.kytos.mef_eline.main.EVC.as_dict')
170
    @patch('napps.kytos.mef_eline.models.EVC._validate')
171
    def test_create_a_circuit_case_1(self, *args):
172
        """Test create a new circuit."""
173
        (validate_mock, evc_as_dict_mock, save_evc_mock,
174
         uni_from_dict_mock, sched_add_mock, storehouse_data_mock) = args
175
176
        validate_mock.return_value = True
177
        save_evc_mock.return_value = True
178
        uni_from_dict_mock.side_effect = ['uni_a', 'uni_z']
179
        evc_as_dict_mock.return_value = {}
180
        sched_add_mock.return_value = True
181
        storehouse_data_mock.return_value = {}
182
183
        api = self.get_app_test_client(self.napp)
184
        url = f'{self.server_name_url}/v2/evc/'
185
        payload = {
186
                   "name": "my evc1",
187
                   "frequency": "* * * * *",
188
                   "uni_a": {
189
                     "interface_id": "00:00:00:00:00:00:00:01:1",
190
                     "tag": {
191
                       "tag_type": 1,
192
                       "value": 80
193
                     }
194
                   },
195
                   "uni_z": {
196
                     "interface_id": "00:00:00:00:00:00:00:02:2",
197
                     "tag": {
198
                       "tag_type": 1,
199
                       "value": 1
200
                     }
201
                   }
202
                 }
203
204
        response = api.post(url, data=json.dumps(payload),
205
                            content_type='application/json')
206
        current_data = json.loads(response.data)
207
208
        # verify expected result from request
209
        self.assertEqual(201, response.status_code, response.data)
210
        self.assertIn('circuit_id', current_data)
211
212
        # verify uni called
213
        uni_from_dict_mock.called_twice()
214
        uni_from_dict_mock.assert_any_call(payload['uni_z'])
215
        uni_from_dict_mock.assert_any_call(payload['uni_a'])
216
217
        # verify validation called
218
        validate_mock.assert_called_once()
219
        validate_mock.assert_called_with(frequency='* * * * *',
220
                                         name='my evc1',
221
                                         uni_a='uni_a',
222
                                         uni_z='uni_z')
223
        # verify save method is called
224
        save_evc_mock.assert_called_once()
225
226
        # verify evc as dict is called to save in the box
227
        evc_as_dict_mock.assert_called_once()
228
        # verify add circuit in sched
229
        sched_add_mock.assert_called_once()
230
231
    @staticmethod
232
    def get_napp_urls(napp):
233
        """Return the kytos/mef_eline urls.
234
235
        The urls will be like:
236
237
        urls = [
238
            (options, methods, url)
239
        ]
240
241
        """
242
        controller = napp.controller
243
        controller.api_server.register_napp_endpoints(napp)
244
245
        urls = []
246
        for rule in controller.api_server.app.url_map.iter_rules():
247
            options = {}
248
            for arg in rule.arguments:
249
                options[arg] = "[{0}]".format(arg)
250
251
            if f'{napp.username}/{napp.name}' in str(rule):
252
                urls.append((options, rule.methods, f'{str(rule)}'))
253
254
        return urls
255
256
    @staticmethod
257
    def get_app_test_client(napp):
258
        """Return a flask api test client."""
259
        napp.controller.api_server.register_napp_endpoints(napp)
260
        return napp.controller.api_server.app.test_client()
261
262
    def test_create_a_circuit_case_2(self):
263
        """Test create a new circuit trying to send request without a json."""
264
        api = self.get_app_test_client(self.napp)
265
        url = f'{self.server_name_url}/v2/evc/'
266
267
        response = api.post(url)
268
        current_data = json.loads(response.data)
269
        expected_data = 'Bad request: The request do not have a json.'
270
271
        self.assertEqual(400, response.status_code, response.data)
272
        self.assertEqual(current_data, expected_data)
273
274
    @patch('napps.kytos.mef_eline.scheduler.Scheduler.add')
275
    @patch('napps.kytos.mef_eline.main.Main.uni_from_dict')
276
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.save_evc')
277
    @patch('napps.kytos.mef_eline.models.EVC._validate')
278
    @patch('napps.kytos.mef_eline.main.EVC.as_dict')
279
    def test_create_circuit_already_enabled(self, *args):
280
        """Test create an already created circuit."""
281
        (evc_as_dict_mock, validate_mock, save_evc_mock,
282
         uni_from_dict_mock, sched_add_mock) = args
283
284
        validate_mock.return_value = True
285
        save_evc_mock.return_value = True
286
        sched_add_mock.return_value = True
287
        uni_from_dict_mock.side_effect = ['uni_a', 'uni_z', 'uni_a', 'uni_z']
288
        payload1 = {'name': 'circuit_1'}
289
290
        api = self.get_app_test_client(self.napp)
291
        payload2 = {
292
            "name": "my evc1",
293
            "uni_a": {
294
                "interface_id": "00:00:00:00:00:00:00:01:1",
295
                "tag": {
296
                    "tag_type": 1,
297
                    "value": 80
298
                }
299
            },
300
            "uni_z": {
301
                "interface_id": "00:00:00:00:00:00:00:02:2",
302
                "tag": {
303
                    "tag_type": 1,
304
                    "value": 1
305
                }
306
            }
307
        }
308
309
        evc_as_dict_mock.return_value = payload1
310
        response = api.post(f'{self.server_name_url}/v2/evc/',
311
                            data=json.dumps(payload1),
312
                            content_type='application/json')
313
        self.assertEqual(201, response.status_code)
314
315
        evc_as_dict_mock.return_value = payload2
316
        response = api.post(f'{self.server_name_url}/v2/evc/',
317
                            data=json.dumps(payload2),
318
                            content_type='application/json')
319
        self.assertEqual(201, response.status_code)
320
321
        response = api.post(f'{self.server_name_url}/v2/evc/',
322
                            data=json.dumps(payload2),
323
                            content_type='application/json')
324
        current_data = json.loads(response.data)
325
        expected_data = 'Not Acceptable: This evc already exists.'
326
        self.assertEqual(current_data, expected_data)
327
        self.assertEqual(409, response.status_code)
328
329
    def test_list_schedules__no_data(self):
330
        """Test list of schedules."""
331
        api = self.get_app_test_client(self.napp)
332
        url = f'{self.server_name_url}/v2/evc/schedule'
333
        response = api.get(url)
334
        self.assertEqual(response.status_code, 200, response.data)
335
        self.assertEqual(json.loads(response.data.decode()), {})
336
337
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.get_data')
338
    def test_list_schedules__no_data_stored(self, storehouse_data_mock):
339
        """Test if list circuits return all circuits stored."""
340
        circuits = {}
341
        storehouse_data_mock.return_value = circuits
342
343
        api = self.get_app_test_client(self.napp)
344
        url = f'{self.server_name_url}/v2/evc/schedule'
345
346
        response = api.get(url)
347
        expected_result = circuits
348
349
        self.assertEqual(response.status_code, 200, response.data)
350
        self.assertEqual(json.loads(response.data), expected_result)
351
352
    # pylint: disable=no-self-use
353
    def _add_storehouse_schedule_data(self, storehouse_data_mock):
354
        """Add schedule data to storehouse mock object."""
355
        circuits = {}
356
        payload_1 = {
357
            "id": "aa:aa:aa",
358
            "name": "my evc1",
359
            "uni_a": {
360
                "interface_id": "00:00:00:00:00:00:00:01:1",
361
                "tag": {
362
                    "tag_type": 1,
363
                    "value": 80
364
                }
365
            },
366
            "uni_z": {
367
                "interface_id": "00:00:00:00:00:00:00:02:2",
368
                "tag": {
369
                    "tag_type": 1,
370
                    "value": 1
371
                }
372
            },
373
            "circuit_scheduler": [
374
                {
375
                    "id": "1",
376
                    "frequency": "* * * * *",
377
                    "action": "create"
378
                },
379
                {
380
                    "id": "2",
381
                    "frequency": "1 * * * *",
382
                    "action": "remove"
383
                }
384
            ]
385
        }
386
        circuits.update({"aa:aa:aa": payload_1})
387
        payload_2 = {
388
            "id": "bb:bb:bb",
389
            "name": "my second evc2",
390
            "uni_a": {
391
                "interface_id": "00:00:00:00:00:00:00:01:2",
392
                "tag": {
393
                    "tag_type": 1,
394
                    "value": 90
395
                }
396
            },
397
            "uni_z": {
398
                "interface_id": "00:00:00:00:00:00:00:03:2",
399
                "tag": {
400
                    "tag_type": 1,
401
                    "value": 100
402
                }
403
            },
404
            "circuit_scheduler": [
405
                {
406
                    "id": "3",
407
                    "frequency": "1 * * * *",
408
                    "action": "create"
409
                },
410
                {
411
                    "id": "4",
412
                    "frequency": "2 * * * *",
413
                    "action": "remove"
414
                }
415
            ]
416
        }
417
        circuits.update({"bb:bb:bb": payload_2})
418
        payload_3 = {
419
            "id": "cc:cc:cc",
420
            "name": "my third evc3",
421
            "uni_a": {
422
                "interface_id": "00:00:00:00:00:00:00:03:1",
423
                "tag": {
424
                    "tag_type": 1,
425
                    "value": 90
426
                }
427
            },
428
            "uni_z": {
429
                "interface_id": "00:00:00:00:00:00:00:04:2",
430
                "tag": {
431
                    "tag_type": 1,
432
                    "value": 100
433
                }
434
            }
435
        }
436
        circuits.update({"cc:cc:cc": payload_3})
437
        # Add one circuit to the storehouse.
438
        storehouse_data_mock.return_value = circuits
439
440
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.get_data')
441
    def test_list_schedules_from_storehouse(self, storehouse_data_mock):
442
        """Test if list circuits return specific circuits stored."""
443
        self._add_storehouse_schedule_data(storehouse_data_mock)
444
445
        api = self.get_app_test_client(self.napp)
446
        url = f'{self.server_name_url}/v2/evc/schedule'
447
448
        # Call URL
449
        response = api.get(url)
450
        # Expected JSON data from response
451
        expected = [{"aa:aa:aa":
452
                    [{"action": "create",
453
                      "frequency": "* * * * *",
454
                      "id": "1"},
455
                     {"action": "remove",
456
                      "frequency": "1 * * * *",
457
                      "id": "2"}]},
458
                    {"bb:bb:bb":
459
                        [{"action": "create",
460
                          "frequency": "1 * * * *",
461
                          "id": "3"},
462
                         {"action": "remove",
463
                          "frequency": "2 * * * *",
464
                          "id": "4"}]}
465
466
                    ]
467
468
        self.assertEqual(response.status_code, 200, response.data)
469
        self.assertEqual(expected, json.loads(response.data))
470
471
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.get_data')
472
    def test_get_specific_schedule_from_storehouse(self, storehouse_data_mock):
473
        """Test get schedules from a circuit."""
474
        self._add_storehouse_schedule_data(storehouse_data_mock)
475
476
        requested_circuit_id = "bb:bb:bb"
477
        api = self.get_app_test_client(self.napp)
478
        url = f'{self.server_name_url}/v2/evc/{requested_circuit_id}'
479
480
        # Call URL
481
        response = api.get(url)
482
483
        # Expected JSON data from response
484
        expected = [{'action': 'create', 'frequency': '1 * * * *', 'id': '3'},
485
                    {'action': 'remove', 'frequency': '2 * * * *', 'id': '4'}]
486
487
        self.assertEqual(response.status_code, 200)
488
        self.assertEqual(expected,
489
                         json.loads(response.data)["circuit_scheduler"])
490
491
    def test_get_specific_schedules_from_storehouse_not_found(self):
492
        """Test get specific schedule ID that does not exist."""
493
        requested_id = "blah"
494
        api = self.get_app_test_client(self.napp)
495
        url = f'{self.server_name_url}/v2/evc/{requested_id}'
496
497
        # Call URL
498
        response = api.get(url)
499
500
        expected = {'response': 'circuit_id blah not found'}
501
        # Assert response not found
502
        self.assertEqual(response.status_code, 404, response.data)
503
        self.assertEqual(expected, json.loads(response.data))
504
505
    def _uni_from_dict_side_effect(self, uni_dict):
506
        interface_id = uni_dict.get("interface_id")
507
        tag_dict = uni_dict.get("tag")
508
        interface = Interface(interface_id, "0", "switch")
509
        return UNI(interface, tag_dict)
510
511
    @patch('apscheduler.schedulers.background.BackgroundScheduler.add_job')
512
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.get_data')
513
    @patch('napps.kytos.mef_eline.scheduler.Scheduler.add')
514
    @patch('napps.kytos.mef_eline.main.Main.uni_from_dict')
515
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.save_evc')
516
    @patch('napps.kytos.mef_eline.main.EVC.as_dict')
517
    @patch('napps.kytos.mef_eline.models.EVC._validate')
518
    def test_create_schedule(self, *args):  # pylint: disable=too-many-locals
519
        """Test create a circuit schedule."""
520
        (validate_mock, evc_as_dict_mock, save_evc_mock,
521
         uni_from_dict_mock, sched_add_mock, storehouse_data_mock,
522
         scheduler_add_job_mock) = args
523
524
        validate_mock.return_value = True
525
        save_evc_mock.return_value = True
526
        uni_from_dict_mock.side_effect = self._uni_from_dict_side_effect
527
        evc_as_dict_mock.return_value = {}
528
        sched_add_mock.return_value = True
529
        storehouse_data_mock.return_value = {}
530
531
        self._add_storehouse_schedule_data(storehouse_data_mock)
532
533
        requested_id = "bb:bb:bb"
534
        api = self.get_app_test_client(self.napp)
535
        url = f'{self.server_name_url}/v2/evc/schedule/'
536
537
        payload = {
538
              "circuit_id": requested_id,
539
              "schedule": {
540
                "frequency": "1 * * * *",
541
                "action": "create"
542
              }
543
            }
544
545
        # Call URL
546
        response = api.post(url, data=json.dumps(payload),
547
                            content_type='application/json')
548
549
        response_json = json.loads(response.data)
550
551
        self.assertEqual(response.status_code, 201, response.data)
552
        scheduler_add_job_mock.assert_called_once()
553
        save_evc_mock.assert_called_once()
554
        self.assertEqual(payload["schedule"]["frequency"],
555
                         response_json["frequency"])
556
        self.assertEqual(payload["schedule"]["action"],
557
                         response_json["action"])
558
        self.assertIsNotNone(response_json["id"])
559
560
    @patch('apscheduler.schedulers.background.BackgroundScheduler.remove_job')
561
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.get_data')
562
    @patch('napps.kytos.mef_eline.scheduler.Scheduler.add')
563
    @patch('napps.kytos.mef_eline.main.Main.uni_from_dict')
564
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.save_evc')
565
    @patch('napps.kytos.mef_eline.main.EVC.as_dict')
566
    @patch('napps.kytos.mef_eline.models.EVC._validate')
567
    def test_update_schedule(self, *args):  # pylint: disable=too-many-locals
568
        """Test create a circuit schedule."""
569
        (validate_mock, evc_as_dict_mock, save_evc_mock,
570
         uni_from_dict_mock, sched_add_mock, storehouse_data_mock,
571
         scheduler_remove_job_mock) = args
572
573
        storehouse_payload_1 = {
574
            "aa:aa:aa": {
575
                "id": "aa:aa:aa",
576
                "name": "my evc1",
577
                "uni_a": {
578
                    "interface_id": "00:00:00:00:00:00:00:01:1",
579
                    "tag": {
580
                        "tag_type": 1,
581
                        "value": 80
582
                    }
583
                },
584
                "uni_z": {
585
                    "interface_id": "00:00:00:00:00:00:00:02:2",
586
                    "tag": {
587
                        "tag_type": 1,
588
                        "value": 1
589
                    }
590
                },
591
                "circuit_scheduler": [{
592
                    "id": "1",
593
                    "frequency": "* * * * *",
594
                    "action": "create"
595
                }
596
                ]
597
            }
598
        }
599
600
        validate_mock.return_value = True
601
        save_evc_mock.return_value = True
602
        sched_add_mock.return_value = True
603
        uni_from_dict_mock.side_effect = ['uni_a', 'uni_z']
604
        evc_as_dict_mock.return_value = {}
605
        storehouse_data_mock.return_value = storehouse_payload_1
606
        scheduler_remove_job_mock.return_value = True
607
608
        requested_schedule_id = "1"
609
        api = self.get_app_test_client(self.napp)
610
        url = f'{self.server_name_url}/v2/evc/schedule/{requested_schedule_id}'
611
612
        payload = {
613
            "frequency": "*/1 * * * *",
614
            "action": "create"
615
        }
616
617
        # Call URL
618
        response = api.patch(url, data=json.dumps(payload),
619
                             content_type='application/json')
620
621
        response_json = json.loads(response.data)
622
623
        self.assertEqual(response.status_code, 200, response.data)
624
        scheduler_remove_job_mock.assert_called_once()
625
        save_evc_mock.assert_called_once()
626
        self.assertEqual(payload["frequency"], response_json["frequency"])
627
        self.assertEqual(payload["action"], response_json["action"])
628
        self.assertIsNotNone(response_json["id"])
629
630
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.get_data')
631
    @patch('napps.kytos.mef_eline.scheduler.Scheduler.add')
632
    @patch('napps.kytos.mef_eline.main.Main.uni_from_dict')
633
    @patch('napps.kytos.mef_eline.main.EVC.as_dict')
634
    @patch('napps.kytos.mef_eline.models.EVC._validate')
635
    def test_update_schedule_archived(self, *args):
636
        """Test create a circuit schedule."""
637
        # pylint: disable=too-many-locals
638
        (validate_mock, evc_as_dict_mock,
639
         uni_from_dict_mock, sched_add_mock, storehouse_data_mock) = args
640
641
        storehouse_payload_1 = {
642
            "aa:aa:aa": {
643
                "id": "aa:aa:aa",
644
                "name": "my evc1",
645
                "archived": True,
646
                "circuit_scheduler": [{
647
                    "id": "1",
648
                    "frequency": "* * * * *",
649
                    "action": "create"
650
                }
651
                ]
652
            }
653
        }
654
655
        validate_mock.return_value = True
656
        sched_add_mock.return_value = True
657
        uni_from_dict_mock.side_effect = ['uni_a', 'uni_z']
658
        evc_as_dict_mock.return_value = {}
659
        storehouse_data_mock.return_value = storehouse_payload_1
660
661
        requested_schedule_id = "1"
662
        api = self.get_app_test_client(self.napp)
663
        url = f'{self.server_name_url}/v2/evc/schedule/{requested_schedule_id}'
664
665
        payload = {
666
            "frequency": "*/1 * * * *",
667
            "action": "create"
668
        }
669
670
        # Call URL
671
        response = api.patch(url, data=json.dumps(payload),
672
                             content_type='application/json')
673
674
        self.assertEqual(response.status_code, 403, response.data)
675
676
    @patch('apscheduler.schedulers.background.BackgroundScheduler.remove_job')
677
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.get_data')
678
    @patch('napps.kytos.mef_eline.main.Main.uni_from_dict')
679
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.save_evc')
680
    @patch('napps.kytos.mef_eline.main.EVC.as_dict')
681
    @patch('napps.kytos.mef_eline.models.EVC._validate')
682
    def test_delete_schedule(self, *args):
683
        """Test create a circuit schedule."""
684
        (validate_mock, evc_as_dict_mock, save_evc_mock,
685
         uni_from_dict_mock, storehouse_data_mock,
686
         scheduler_remove_job_mock) = args
687
688
        storehouse_payload_1 = {
689
            "2": {
690
                "id": "2",
691
                "name": "my evc1",
692
                "uni_a": {
693
                    "interface_id": "00:00:00:00:00:00:00:01:1",
694
                    "tag": {
695
                        "tag_type": 1,
696
                        "value": 80
697
                    }
698
                },
699
                "uni_z": {
700
                    "interface_id": "00:00:00:00:00:00:00:02:2",
701
                    "tag": {
702
                        "tag_type": 1,
703
                        "value": 1
704
                    }
705
                },
706
                "circuit_scheduler": [{
707
                    "id": "1",
708
                    "frequency": "* * * * *",
709
                    "action": "create"
710
                }]
711
            }
712
        }
713
714
        validate_mock.return_value = True
715
        save_evc_mock.return_value = True
716
        uni_from_dict_mock.side_effect = ['uni_a', 'uni_z']
717
        evc_as_dict_mock.return_value = {}
718
        storehouse_data_mock.return_value = storehouse_payload_1
719
        scheduler_remove_job_mock.return_value = True
720
721
        requested_schedule_id = "1"
722
        api = self.get_app_test_client(self.napp)
723
        url = f'{self.server_name_url}/v2/evc/schedule/{requested_schedule_id}'
724
725
        # Call URL
726
        response = api.delete(url)
727
728
        self.assertEqual(response.status_code, 200, response.data)
729
        scheduler_remove_job_mock.assert_called_once()
730
        save_evc_mock.assert_called_once()
731
        self.assertIn("Schedule removed", f"{response.data}")
732
733
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.get_data')
734
    @patch('napps.kytos.mef_eline.main.Main.uni_from_dict')
735
    @patch('napps.kytos.mef_eline.main.EVC.as_dict')
736
    @patch('napps.kytos.mef_eline.models.EVC._validate')
737
    def test_delete_schedule_archived(self, *args):
738
        """Test create a circuit schedule."""
739
        (validate_mock, evc_as_dict_mock,
740
         uni_from_dict_mock, storehouse_data_mock) = args
741
742
        storehouse_payload_1 = {
743
            "2": {
744
                "id": "2",
745
                "name": "my evc1",
746
                "archived": True,
747
                "circuit_scheduler": [{
748
                    "id": "1",
749
                    "frequency": "* * * * *",
750
                    "action": "create"
751
                }]
752
            }
753
        }
754
755
        validate_mock.return_value = True
756
        uni_from_dict_mock.side_effect = ['uni_a', 'uni_z']
757
        evc_as_dict_mock.return_value = {}
758
        storehouse_data_mock.return_value = storehouse_payload_1
759
760
        requested_schedule_id = "1"
761
        api = self.get_app_test_client(self.napp)
762
        url = f'{self.server_name_url}/v2/evc/schedule/{requested_schedule_id}'
763
764
        # Call URL
765
        response = api.delete(url)
766
767
        self.assertEqual(response.status_code, 403, response.data)
768