Test Failed
Pull Request — master (#87)
by Gleyberson
01:58
created

test_main.FakeBox.__init__()   A

Complexity

Conditions 1

Size

Total Lines 8
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nop 2
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
"""Module to test the main napp file."""
2
from unittest import TestCase
3
from unittest.mock import Mock, patch
4
5
from kytos.core.events import KytosEvent
6
from tests.integration.helpers import (get_controller_mock, get_interface_mock,
7
                                       get_switch_mock)
8
9
LINK_DATA = {
10
    "active": False,
11
    "enabled": True,
12
    "endpoint_a": {
13
        "id": "00:00:00:00:00:00:00:01:1",
14
        "link": "26927949-df3c-4c25-874b-3da30d8ae983",
15
        "mac": "26:fb:42:20:b8:b1",
16
        "name": "s1-eth1",
17
        "nni": False,
18
        "port_number": 1,
19
        "speed": "10 Gbps",
20
        "switch": "00:00:00:00:00:00:00:01",
21
        "type": "interface",
22
        "uni": True
23
    },
24
    "endpoint_b": {
25
        "id": "00:00:00:00:00:00:00:01:1",
26
        "link": "26927949-df3c-4c25-874b-3da30d8ae983",
27
        "mac": "26:fb:42:20:b8:b1",
28
        "name": "s1-eth1",
29
        "nni": False,
30
        "port_number": 1,
31
        "speed": "10 Gbps",
32
        "switch": "00:00:00:00:00:00:00:01",
33
        "type": "interface",
34
        "uni": True
35
    }
36
}
37
38
SWITCH_DATA = {
39
    "id": "00:00:00:00:00:00:00:01",
40
    "name": "my-beautiful-switch",
41
    "serial": "string",
42
    "software": "Version 2.3.4",
43
    "ofp_version": "0x01",
44
    "connection": "127.0.0.1:49330",
45
    "data_path": "string",
46
    "manufacturer": "Unkown Manufactor",
47
    "hardware": "Hardware version 2.0",
48
    "type": "switch",
49
    "active": True,
50
    "enabled": False,
51
    "dpid": "00:00:00:00:00:00:00:01",
52
    "metadata": {},
53
    "interfaces": {
54
        "additionalProp1": {
55
            "id": "00:00:00:00:00:00:00:01:1",
56
            "link": "26927949-df3c-4c25-874b-3da30d8ae983",
57
            "mac": "26:fb:42:20:b8:b1",
58
            "name": "s1-eth1",
59
            "nni": False,
60
            "port_number": 1,
61
            "speed": "10 Gbps",
62
            "switch": "00:00:00:00:00:00:00:01",
63
            "type": "interface",
64
            "uni": True
65
        },
66
        "additionalProp2": {
67
            "id": "00:00:00:00:00:00:00:01:1",
68
            "link": "26927949-df3c-4c25-874b-3da30d8ae983",
69
            "mac": "26:fb:42:20:b8:b1",
70
            "name": "s1-eth1",
71
            "nni": False,
72
            "port_number": 1,
73
            "speed": "10 Gbps",
74
            "switch": "00:00:00:00:00:00:00:01",
75
            "type": "interface",
76
            "uni": True
77
        },
78
        "additionalProp3": {
79
            "id": "00:00:00:00:00:00:00:01:1",
80
            "link": "26927949-df3c-4c25-874b-3da30d8ae983",
81
            "mac": "26:fb:42:20:b8:b1",
82
            "name": "s1-eth1",
83
            "nni": False,
84
            "port_number": 1,
85
            "speed": "10 Gbps",
86
            "switch": "00:00:00:00:00:00:00:01",
87
            "type": "interface",
88
            "uni": True
89
        }
90
    }
91
}
92
93
94
class FakeBox:
95
    """Simulate a Storehouse Box."""
96
97
    def __init__(self, data):
98
        """Initizalize default values to FakeBox."""
99
        self.data = data
100
        self.namespace = None
101
        self.name = None
102
        self.box_id = None
103
        self.created_at = None
104
        self.owner = None
105
106
107
# pylint: disable=import-outside-toplevel
108
class TestMain(TestCase):
109
    """Test the Main class."""
110
111
    def setUp(self):
112
        """Execute steps before each tests.
113
114
        Set the server_name_url from kytos/topology
115
        """
116
        self.server_name_url = 'http://localhost:8181/api/kytos/topology'
117
        self.init_napp()
118
119
    @patch('napps.kytos.topology.main.Main.verify_storehouse')
120
    def init_napp(self, mock_verify_storehouse=None):
121
        """Initialize a Topology NApp instance."""
122
        mock_verify_storehouse.return_value = None
123
        patch('kytos.core.helpers.run_on_thread', lambda x: x).start()
124
        # pylint: disable=bad-option-value
125
        from napps.kytos.topology.main import Main
126
        self.addCleanup(patch.stopall)
127
        self.napp = Main(get_controller_mock())
128
        self.napp.store_items = {
129
            "links": FakeBox(LINK_DATA),
130
            "switches": FakeBox(SWITCH_DATA)
131
        }
132
133
    def test_get_switches_dict(self):
134
        """Basic test for switch listing."""
135
        # pylint: disable=protected-access
136
        switches = self.napp._get_switches_dict()
137
        assert isinstance(switches['switches'], dict)
138
        assert switches['switches'] == {}
139
140
    def test_get_event_listeners(self):
141
        """Verify all event listeners registered."""
142
        expected_events = ['kytos/core.shutdown',
143
                           'kytos/core.shutdown.kytos/topology',
144
                           '.*.interface.is.nni',
145
                           '.*.connection.lost',
146
                           '.*.switch.interface.created',
147
                           '.*.switch.interface.deleted',
148
                           '.*.switch.interface.link_down',
149
                           '.*.switch.interface.link_up',
150
                           '.*.switch.(new|reconnected)',
151
                           '.*.switch.port.created',
152
                           'kytos/topology.*.metadata.*']
153
        actual_events = self.napp.listeners()
154
        self.assertEqual(expected_events, actual_events)
155
156
    def test_verify_api_urls(self):
157
        """Verify all APIs registered."""
158
        expected_urls = [
159
         ({}, {'GET', 'OPTIONS', 'HEAD'}, '/api/kytos/topology/v3/interfaces'),
160
         ({}, {'GET', 'OPTIONS', 'HEAD'}, '/api/kytos/topology/v3/switches'),
161
         ({}, {'GET', 'OPTIONS', 'HEAD'}, '/api/kytos/topology/v3/links'),
162
         ({}, {'GET', 'OPTIONS', 'HEAD'}, '/api/kytos/topology/v3/'),
163
         ({'key': '[key]', 'interface_id': '[interface_id]'},
164
          {'OPTIONS', 'DELETE'},
165
          '/api/kytos/topology/v3/interfaces/<interface_id>/metadata/<key>'),
166
         ({'interface_id': '[interface_id]'}, {'POST', 'OPTIONS'},
167
          '/api/kytos/topology/v3/interfaces/<interface_id>/metadata'),
168
         ({'interface_id': '[interface_id]'}, {'GET', 'OPTIONS', 'HEAD'},
169
          '/api/kytos/topology/v3/interfaces/<interface_id>/metadata'),
170
         ({'interface_id': '[interface_id]'}, {'POST', 'OPTIONS'},
171
          '/api/kytos/topology/v3/interfaces/<interface_id>/disable'),
172
         ({'interface_id': '[interface_id]'}, {'POST', 'OPTIONS'},
173
          '/api/kytos/topology/v3/interfaces/<interface_id>/enable'),
174
         ({'dpid': '[dpid]', 'key': '[key]'}, {'OPTIONS', 'DELETE'},
175
          '/api/kytos/topology/v3/switches/<dpid>/metadata/<key>'),
176
         ({'dpid': '[dpid]'}, {'POST', 'OPTIONS'},
177
          '/api/kytos/topology/v3/switches/<dpid>/metadata'),
178
         ({'dpid': '[dpid]'}, {'GET', 'OPTIONS', 'HEAD'},
179
          '/api/kytos/topology/v3/switches/<dpid>/metadata'),
180
         ({'dpid': '[dpid]'}, {'POST', 'OPTIONS'},
181
          '/api/kytos/topology/v3/switches/<dpid>/disable'),
182
         ({'dpid': '[dpid]'}, {'POST', 'OPTIONS'},
183
          '/api/kytos/topology/v3/switches/<dpid>/enable'),
184
         ({'link_id': '[link_id]', 'key': '[key]'}, {'OPTIONS', 'DELETE'},
185
          '/api/kytos/topology/v3/links/<link_id>/metadata/<key>'),
186
         ({'link_id': '[link_id]'}, {'POST', 'OPTIONS'},
187
          '/api/kytos/topology/v3/links/<link_id>/metadata'),
188
         ({'link_id': '[link_id]'}, {'GET', 'OPTIONS', 'HEAD'},
189
          '/api/kytos/topology/v3/links/<link_id>/metadata'),
190
         ({'link_id': '[link_id]'}, {'POST', 'OPTIONS'},
191
          '/api/kytos/topology/v3/links/<link_id>/disable'),
192
         ({'link_id': '[link_id]'}, {'POST', 'OPTIONS'},
193
          '/api/kytos/topology/v3/links/<link_id>/enable')]
194
195
        urls = self.get_napp_urls(self.napp)
196
        self.assertEqual(expected_urls, urls)
197
198
    @staticmethod
199
    def get_napp_urls(napp):
200
        """Return the kytos/topology urls.
201
202
        The urls will be like:
203
204
        urls = [
205
            (options, methods, url)
206
        ]
207
208
        """
209
        controller = napp.controller
210
        controller.api_server.register_napp_endpoints(napp)
211
212
        urls = []
213
        for rule in controller.api_server.app.url_map.iter_rules():
214
            options = {}
215
            for arg in rule.arguments:
216
                options[arg] = "[{0}]".format(arg)
217
218
            if f'{napp.username}/{napp.name}' in str(rule):
219
                urls.append((options, rule.methods, f'{str(rule)}'))
220
221
        return urls
222
223
    @staticmethod
224
    def get_app_test_client(napp):
225
        """Return a flask api test client."""
226
        napp.controller.api_server.register_napp_endpoints(napp)
227
        return napp.controller.api_server.app.test_client()
228
229
    def test_save_metadata_on_store(self):
230
        """Test save metadata on store."""
231
        event_name = 'kytos.storehouse.update'
232
        switch = get_switch_mock(0x04)
233
        event = KytosEvent(name=event_name,
234
                           content={'switch': switch})
235
        self.napp.save_metadata_on_store(event)
236
        event_response = self.napp.controller.buffers.app.get()
237
        self.assertEqual(event_response.name,
238
                         'kytos.storehouse.update')
239
240
    def test_handle_new_switch(self):
241
        """Test handle new switch."""
242
        event_name = '.*.switch.(new|reconnected)'
243
        switch = get_switch_mock(0x04)
244
        event = KytosEvent(name=event_name,
245
                           content={'switch': switch})
246
        self.napp.handle_new_switch(event)
247
        event_response = self.napp.controller.buffers.app.get()
248
        self.assertEqual(event_response.name,
249
                         'kytos/topology.updated')
250
251
    def test_handle_interface_created(self):
252
        """Test handle interface created."""
253
        event_name = '.*.switch.interface.created'
254
        interface = get_interface_mock("interface1", 7)
255
        stats_event = KytosEvent(name=event_name,
256
                                 content={'interface': interface})
257
        self.napp.handle_interface_created(stats_event)
258
        event_response = self.napp.controller.buffers.app.get()
259
        self.assertEqual(event_response.name,
260
                         'kytos/topology.updated')
261
262
    def test_handle_interface_deleted(self):
263
        """Test handle interface deleted."""
264
        event_name = '.*.switch.interface.deleted'
265
        interface = get_interface_mock("interface1", 7)
266
        stats_event = KytosEvent(name=event_name,
267
                                 content={'interface': interface})
268
        self.napp.handle_interface_deleted(stats_event)
269
        event_response = self.napp.controller.buffers.app.get()
270
        self.assertEqual(event_response.name,
271
                         'kytos/topology.updated')
272
273
    def test_handle_connection_lost(self):
274
        """Test handle connection lost."""
275
        event_name = '.*.connection.lost'
276
        source = Mock()
277
        stats_event = KytosEvent(name=event_name,
278
                                 content={'source': source})
279
        self.napp.handle_connection_lost(stats_event)
280
        event_response = self.napp.controller.buffers.app.get()
281
        self.assertEqual(event_response.name,
282
                         'kytos/topology.updated')
283