Passed
Pull Request — master (#76)
by macartur
02:24
created

TestMain.test_create_a_circuit()   B

Complexity

Conditions 1

Size

Total Lines 64
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 45
nop 2
dl 0
loc 64
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
"""Module to test the main napp file."""
2
import json
3
from unittest import TestCase
4
from unittest.mock import Mock, patch
5
6
from kytos.core import Controller
7
from kytos.core.config import KytosConfig
8
9
from napps.kytos.mef_eline.main import Main
10
11
12
class TestMain(TestCase):
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(self.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.*.link.down',
28
                           'kytos.*.link.under_maintenance',
29
                           'kytos.*.link.up',
30
                           'kytos.*.link.end_maintenance',
31
                           'kytos/topology.updated']
32
        actual_events = self.napp.listeners()
33
        self.assertEqual(expected_events, actual_events)
34
35
    def test_verify_api_urls(self):
36
        """Verify all APIs registered."""
37
        expected_urls = [
38
            ({}, {'OPTIONS', 'POST'},
39
             '/api/kytos/mef_eline/v2/evc/'),
40
            ({}, {'OPTIONS', 'HEAD', 'GET'},
41
             '/api/kytos/mef_eline/v2/evc/'),
42
            ({'circuit_id': '[circuit_id]'}, {'OPTIONS', 'HEAD', 'GET'},
43
             '/api/kytos/mef_eline/v2/evc/<circuit_id>'),
44
            ({'circuit_id': '[circuit_id]'}, {'OPTIONS', 'PATCH'},
45
             '/api/kytos/mef_eline/v2/evc/<circuit_id>')]
46
        urls = self.get_napp_urls(self.napp)
47
        self.assertEqual(expected_urls, urls)
48
49
    def test_list_without_circuits(self):
50
        """Test if list circuits return 'no circuit stored.'."""
51
        api = self.get_app_test_client(self.napp)
52
        url = f'{self.server_name_url}/v2/evc/'
53
        response = api.get(url)
54
        self.assertEqual(response.status_code, 200)
55
        self.assertEqual(json.loads(response.data.decode()),
56
                         {"response": "No circuit stored."})
57
58
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.get_data')
59
    def test_list_with_circuits_stored(self, storehouse_data_mock):
60
        """Test if list circuits return all circuts stored."""
61
        circuits = {'1': {'name': 'circuit_1'},
62
                    '2': {'name': 'circuit_2'}}
63
        storehouse_data_mock.return_value = circuits
64
65
        api = self.get_app_test_client(self.napp)
66
        url = f'{self.server_name_url}/v2/evc/'
67
68
        response = api.get(url)
69
        expected_result = circuits
70
        self.assertEqual(json.loads(response.data), expected_result)
71
72 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...
73
    def test_circuit_with_valid_id(self, storehouse_data_mock):
74
        """Test if get_cirguit return the ciruit attributes."""
75
        circuits = {'1': {'name': 'circuit_1'},
76
                    '2': {'name': 'circuit_2'}}
77
        storehouse_data_mock.return_value = circuits
78
79
        api = self.get_app_test_client(self.napp)
80
        url = f'{self.server_name_url}/v2/evc/1'
81
        response = api.get(url)
82
        expected_result = circuits['1']
83
        self.assertEqual(json.loads(response.data), expected_result)
84
85 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...
86
    def test_circuit_with_invalid_id(self, storehouse_data_mock):
87
        """Test if get_circuit return invalid circuit_id."""
88
        circuits = {'1': {'name': 'circuit_1'},
89
                    '2': {'name': 'circuit_2'}}
90
        storehouse_data_mock.return_value = circuits
91
92
        api = self.get_app_test_client(self.napp)
93
        url = f'{self.server_name_url}/v2/evc/3'
94
        response = api.get(url)
95
        expected_result = {'response': 'circuit_id 3 not found'}
96
        self.assertEqual(json.loads(response.data), expected_result)
97
98
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.get_data')
99
    @patch('napps.kytos.mef_eline.scheduler.Scheduler.add')
100
    @patch('napps.kytos.mef_eline.main.Main.uni_from_dict')
101
    @patch('napps.kytos.mef_eline.storehouse.StoreHouse.save_evc')
102
    @patch('napps.kytos.mef_eline.main.EVC.as_dict')
103
    @patch('napps.kytos.mef_eline.models.EVC._validate')
104
    def test_create_a_circuit_case_1(self, *args):
105
        """Test create a new circuit."""
106
        (validate_mock, evc_as_dict_mock, save_evc_mock,
107
         uni_from_dict_mock, sched_add_mock, storehouse_data_mock) = args
108
109
        validate_mock.return_value = True
110
        save_evc_mock.return_value = True
111
        uni_from_dict_mock.side_effect = ['uni_a', 'uni_z']
112
        evc_as_dict_mock.return_value = {}
113
        sched_add_mock.return_value = True
114
        storehouse_data_mock.return_value = {}
115
116
        api = self.get_app_test_client(self.napp)
117
        url = f'{self.server_name_url}/v2/evc/'
118
        payload = {
119
                   "name": "my evc1",
120
                   "frequency": "* * * * *",
121
                   "uni_a": {
122
                     "interface_id": "00:00:00:00:00:00:00:01:1",
123
                     "tag": {
124
                       "tag_type": 1,
125
                       "value": 80
126
                     }
127
                   },
128
                   "uni_z": {
129
                     "interface_id": "00:00:00:00:00:00:00:02:2",
130
                     "tag": {
131
                       "tag_type": 1,
132
                       "value": 1
133
                     }
134
                   }
135
                 }
136
137
        response = api.post(url, json=payload)
138
        current_data = json.loads(response.data)
139
140
        # verify expected result from request
141
        self.assertEqual(201, response.status_code)
142
        self.assertIn('circuit_id', current_data)
143
144
        # verify uni called
145
        uni_from_dict_mock.called_twice()
146
        uni_from_dict_mock.assert_any_call(payload['uni_z'])
147
        uni_from_dict_mock.assert_any_call(payload['uni_a'])
148
149
        # verify validation called
150
        validate_mock.assert_called_once()
151
        validate_mock.assert_called_with(frequency='* * * * *',
152
                                         name='my evc1',
153
                                         uni_a='uni_a',
154
                                         uni_z='uni_z')
155
        # verify save method is called
156
        save_evc_mock.assert_called_once()
157
158
        # verify evc as dict is called to save in the box
159
        evc_as_dict_mock.assert_called_once()
160
        # verify add circuit in sched
161
        sched_add_mock.assert_called_once()
162
163
    @staticmethod
164
    def get_controller_mock():
165
        """Return a controller mock."""
166
        options = KytosConfig().options['daemon']
167
        controller = Controller(options)
168
        controller.log = Mock()
169
        return controller
170
171
    @staticmethod
172
    def get_napp_urls(napp):
173
        """Return the kytos/mef_eline urls.
174
175
        The urls will be like:
176
177
        urls = [
178
            (options, methods, url)
179
        ]
180
181
        """
182
        controller = napp.controller
183
        controller.api_server.register_napp_endpoints(napp)
184
185
        urls = []
186
        for rule in controller.api_server.app.url_map.iter_rules():
187
            options = {}
188
            for arg in rule.arguments:
189
                options[arg] = "[{0}]".format(arg)
190
191
            if f'{napp.username}/{napp.name}' in str(rule):
192
                urls.append((options, rule.methods, f'{str(rule)}'))
193
194
        return urls
195
196
    @staticmethod
197
    def get_app_test_client(napp):
198
        """Return a flask api test client."""
199
        napp.controller.api_server.register_napp_endpoints(napp)
200
        return napp.controller.api_server.app.test_client()
201
202
    def test_create_a_circuit_case_2(self):
203
        """Test create a new circuit trying to send request without a json."""
204
        api = self.get_app_test_client(self.napp)
205
        url = f'{self.server_name_url}/v2/evc/'
206
207
        response = api.post(url)
208
        current_data = json.loads(response.data)
209
        expected_data = 'Bad request: The request do not have a json.'
210
211
        self.assertEqual(400, response.status_code)
212
        self.assertEqual(current_data, expected_data)
213