Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / api / tests / networks.py @ 4911365b

History | View | Annotate | Download (15 kB)

1
# Copyright 2012-2013 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
from snf_django.utils.testing import (BaseAPITest, override_settings)
35
from django.utils import simplejson as json
36
from synnefo.cyclades_settings import cyclades_services
37
from synnefo.lib.services import get_service_path
38
from synnefo.lib import join_urls
39
import synnefo.db.models_factory as dbmf
40
from synnefo.db.models import Network
41
from django.conf import settings
42

    
43
COMPUTE_URL = get_service_path(cyclades_services, 'compute',
44
                               version='v2.0')
45
NETWORKS_URL = join_urls(COMPUTE_URL, "networks/")
46

    
47

    
48
class NetworkTest(BaseAPITest):
49
    def test_list_networks(self):
50
        response = self.get(NETWORKS_URL)
51
        self.assertSuccess(response)
52
        networks = json.loads(response.content)
53
        self.assertEqual(networks, {"networks": []})
54

    
55
    def test_invalid_create(self):
56
        """Test invalid flavor"""
57
        request = {'network': {}}
58
        response = self.post(NETWORKS_URL, "user1", params=json.dumps(request))
59
        self.assertBadRequest(response)
60
        request = {'network': {"type": "foo"}}
61
        response = self.post(NETWORKS_URL, "user1", params=json.dumps(request))
62
        self.assertBadRequest(response)
63
        request = {'network': {"type": "MAC_FILTERED"}}
64
        with override_settings(settings,
65
                               API_ENABLED_NETWORK_FLAVORS=["CUSTOM"]):
66
            response = self.post(NETWORKS_URL, "user1",
67
                                 params=json.dumps(request))
68
        self.assertEqual(response.status_code, 403)
69
        self.assertEqual(len(Network.objects.filter(userid='user1')), 0)
70

    
71
    def test_create(self):
72
        request = {
73
            "network": {
74
                "name": "sample_network",
75
                "type": "MAC_FILTERED"
76
            }
77
        }
78
        response = self.post(NETWORKS_URL, params=json.dumps(request))
79
        code = response.status_code
80
        self.assertEqual(code, 503)  # No MAC prefix pool
81
        dbmf.MacPrefixPoolTableFactory()
82
        response = self.post(NETWORKS_URL, params=json.dumps(request))
83
        code = response.status_code
84
        self.assertEqual(code, 201)
85
        res = json.loads(response.content)
86
        self.assertEqual(res["network"]["name"], "sample_network")
87

    
88
        # TEST QUOTAS!!!
89
        name, args, kwargs =\
90
            self.mocked_quotaholder.issue_one_commission.mock_calls[0]
91
        commission_resources = args[3]
92
        self.assertEqual(commission_resources, {"cyclades.network.private": 1})
93
        name, args, kwargs =\
94
            self.mocked_quotaholder.resolve_commissions.mock_calls[0]
95
        serial = Network.objects.get().serial.serial
96
        accepted_serials = args[1]
97
        rejected_serials = args[2]
98
        self.assertEqual(accepted_serials, [serial])
99
        self.assertEqual(rejected_serials, [])
100

    
101
        # test no name
102
        request["network"].pop("name")
103
        response = self.post(NETWORKS_URL, params=json.dumps(request))
104
        code = response.status_code
105
        self.assertEqual(code, 201)
106
        res = json.loads(response.content)
107
        self.assertEqual(res["network"]["name"], "")
108

    
109
    def test_get_unfound_network(self):
110
        url = join_urls(NETWORKS_URL, "123")
111
        response = self.get(url)
112
        self.assertItemNotFound(response)
113

    
114
    def test_get_network(self):
115
        test_net = dbmf.NetworkFactory()
116
        url = join_urls(NETWORKS_URL, str(test_net.id))
117
        response = self.get(url, user=test_net.userid)
118
        # validate response
119
        res = json.loads(response.content)
120
        net = res['network']
121
        keys = net.keys()
122
        must_send = set(["status", "subnets", "name", "admin_state_up",
123
                        "tenant_id", "id"])
124
        self.assertEqual(set(keys).issuperset(must_send), True)
125
        self.assertEqual(response.status_code, 200)
126

    
127
    def test_get_deleted_network(self):
128
        test_net = dbmf.NetworkFactory(flavor="CUSTOM")
129
        url = join_urls(NETWORKS_URL, str(test_net.id))
130
        self.delete(url, user=test_net.userid)
131
        response = self.get(url, user=test_net.userid)
132
        self.assertEqual(response.status_code, 200)
133

    
134
    def test_delete_unfound_network(self):
135
        url = join_urls(NETWORKS_URL, "123")
136
        response = self.delete(url)
137
        self.assertItemNotFound(response)
138

    
139
    def test_delete_network(self):
140
        test_net = dbmf.NetworkFactory(flavor="CUSTOM")
141
        dbmf.IPv4SubnetFactory(network=test_net)
142
        url = join_urls(NETWORKS_URL, str(test_net.id))
143
        response = self.delete(url, user=test_net.userid)
144
        self.assertEqual(response.status_code, 204)
145
        # But not the public network!!
146
        test_net.public = True
147
        test_net.save()
148
        response = self.delete(url, user=test_net.userid)
149
        self.assertFault(response, 403, 'forbidden')
150

    
151
    def test_delete_network_in_use(self):
152
        test_net = dbmf.NetworkFactory()
153
        dbmf.NetworkInterfaceFactory(network=test_net)
154
        url = join_urls(NETWORKS_URL, str(test_net.id))
155
        response = self.delete(url, user=test_net.userid)
156
        self.assertEqual(response.status_code, 409)
157

    
158
    def test_delete_network_with_floating_ips(self):
159
        test_net = dbmf.NetworkFactory()
160
        dbmf.IPv4AddressFactory(network=test_net, floating_ip=True, nic=None)
161
        url = join_urls(NETWORKS_URL, str(test_net.id))
162
        response = self.delete(url, user=test_net.userid)
163
        self.assertEqual(response.status_code, 409)
164

    
165
    def test_put_unfound_network(self):
166
        url = join_urls(NETWORKS_URL, "123")
167
        response = self.delete(url)
168
        self.assertItemNotFound(response)
169

    
170
    def test_put_network_wrong_data(self):
171
        test_net = dbmf.NetworkFactory()
172
        url = join_urls(NETWORKS_URL, str(test_net.id))
173
        request = {
174
            "network": {
175
                "wrong_field": "new_name"}
176
        }
177
        response = self.put(url, params=json.dumps(request),
178
                            user=test_net.userid)
179
        self.assertEqual(response.status_code, 400)
180

    
181
    def test_put_no_data(self):
182
        test_net = dbmf.NetworkFactory()
183
        url = join_urls(NETWORKS_URL, str(test_net.id))
184
        response = self.put(url, params="", user=test_net.userid)
185
        self.assertEqual(response.status_code, 400)
186

    
187
    def test_rename_network(self):
188
        test_net = dbmf.NetworkFactory(name="foo")
189
        url = join_urls(NETWORKS_URL, str(test_net.id))
190
        request = {'network': {'name': "new_name"}}
191
        response = self.put(url, test_net.userid, json.dumps(request), 'json')
192
        self.assertEqual(response.status_code, 200)
193
        self.assertEqual(Network.objects.get(id=test_net.id).name, "new_name")
194
        # test if server deleted
195
        test_net.deleted = True
196
        test_net.save()
197
        response = self.put(url, test_net.userid, json.dumps(request), 'json')
198
        self.assertBadRequest(response)
199
        test_net.deleted = False
200
        test_net.public = True
201
        test_net.save()
202
        response = self.put(url, test_net.userid, json.dumps(request), 'json')
203
        self.assertFault(response, 403, 'forbidden')
204

    
205
    def test_method_not_allowed(self, *args):
206
        # /networks/ allows only POST, GET
207
        response = self.put(NETWORKS_URL, '', '')
208
        self.assertMethodNotAllowed(response)
209
        response = self.delete(NETWORKS_URL)
210
        self.assertMethodNotAllowed(response)
211

    
212
        # /networks/<srvid>/ allows only GET, PUT, DELETE
213
        url = join_urls(NETWORKS_URL, "42")
214
        response = self.post(url)
215
        self.assertMethodNotAllowed(response)
216

    
217

    
218
#class NetworkNICsAPITest(BaseAPITest):
219
#    def test_get_network_building_nics(self, mrapi):
220
#        net = dbmf.NetworkFactory()
221
#        machine = dbmf.VirtualMachineFactory(userid=net.userid)
222
#        dbmf.NetworkInterfaceFactory(network=net, machine=machine,
223
#                                     state="BUILDING")
224
#        response = self.myget('networks/%d' % net.id, net.userid)
225
#        self.assertSuccess(response)
226
#        api_net = json.loads(response.content)["network"]
227
#        self.assertEqual(len(api_net["attachments"]), 0)
228
#
229
#
230
#    def test_add_nic(self, mrapi):
231
#        user = 'userr'
232
#        vm = dbmf.VirtualMachineFactory(name='yo', userid=user)
233
#        net = dbmf.NetworkFactory(state='ACTIVE', userid=user)
234
#        mrapi().ModifyInstance.return_value = 1
235
#        request = {'add': {'serverRef': vm.id}}
236
#        response = self.mypost('networks/%d/action' % net.id,
237
#                               net.userid, json.dumps(request), 'json')
238
#        self.assertEqual(response.status_code, 202)
239
#
240
#    def test_add_nic_to_deleted_network(self, mrapi):
241
#        user = 'userr'
242
#        vm = dbmf.VirtualMachineFactory(name='yo', userid=user,
243
#                                            operstate="ACTIVE")
244
#        net = dbmf.NetworkFactory(state='ACTIVE', userid=user,
245
#                                      deleted=True)
246
#        request = {'add': {'serverRef': vm.id}}
247
#        response = self.mypost('networks/%d/action' % net.id,
248
#                               net.userid, json.dumps(request), 'json')
249
#        self.assertBadRequest(response)
250
#        self.assertFalse(mrapi.called)
251
#
252
#    def test_add_nic_to_public_network(self, mrapi):
253
#        user = 'userr'
254
#        vm = dbmf.VirtualMachineFactory(name='yo', userid=user)
255
#        net = dbmf.NetworkFactory(state='ACTIVE', userid=user, public=True)
256
#        request = {'add': {'serverRef': vm.id}}
257
#        response = self.mypost('networks/%d/action' % net.id,
258
#                               net.userid, json.dumps(request), 'json')
259
#        self.assertFault(response, 403, 'forbidden')
260
#        self.assertFalse(mrapi.called)
261
#
262
#    def test_add_nic_malformed_1(self, mrapi):
263
#        user = 'userr'
264
#        vm = dbmf.VirtualMachineFactory(name='yo', userid=user)
265
#        net = dbmf.NetworkFactory(state='ACTIVE', userid=user)
266
#        request = {'add': {'serveRef': vm.id}}
267
#        response = self.mypost('networks/%d/action' % net.id,
268
#                               net.userid, json.dumps(request), 'json')
269
#        self.assertBadRequest(response)
270
#        self.assertFalse(mrapi.called)
271
#
272
#    def test_add_nic_malformed_2(self, mrapi):
273
#        user = 'userr'
274
#        vm = dbmf.VirtualMachineFactory(name='yo', userid=user)
275
#        net = dbmf.NetworkFactory(state='ACTIVE', userid=user)
276
#        request = {'add': {'serveRef': [vm.id, 22]}}
277
#        response = self.mypost('networks/%d/action' % net.id,
278
#                               net.userid, json.dumps(request), 'json')
279
#        self.assertBadRequest(response)
280
#        self.assertFalse(mrapi.called)
281
#
282
#    def test_add_nic_not_active(self, mrapi):
283
#        """Test connecting VM to non-active network"""
284
#        user = 'dummy'
285
#        vm = dbmf.VirtualMachineFactory(name='yo', userid=user)
286
#        net = dbmf.NetworkFactory(state='PENDING', subnet='10.0.0.0/31',
287
#                                      userid=user)
288
#        request = {'add': {'serverRef': vm.id}}
289
#        response = self.mypost('networks/%d/action' % net.id,
290
#                               net.userid, json.dumps(request), 'json')
291
#        # Test that returns BuildInProgress
292
#        self.assertEqual(response.status_code, 409)
293
#        self.assertFalse(mrapi.called)
294
#
295
#    def test_add_nic_full_network(self, mrapi):
296
#        """Test connecting VM to a full network"""
297
#        user = 'userr'
298
#        vm = dbmf.VirtualMachineFactory(name='yo', userid=user,
299
#                                            operstate="STARTED")
300
#        net = dbmf.NetworkFactory(state='ACTIVE', subnet='10.0.0.0/30',
301
#                                      userid=user, dhcp=True)
302
#        pool = net.get_pool()
303
#        while not pool.empty():
304
#            pool.get()
305
#        pool.save()
306
#        pool = net.get_pool()
307
#        self.assertTrue(pool.empty())
308
#        request = {'add': {'serverRef': vm.id}}
309
#        response = self.mypost('networks/%d/action' % net.id,
310
#                               net.userid, json.dumps(request), 'json')
311
#        # Test that returns OverLimit
312
#        self.assertEqual(response.status_code, 413)
313
#        self.assertFalse(mrapi.called)
314
#
315
#    def test_remove_nic(self, mrapi):
316
#        user = 'userr'
317
#        vm = dbmf.VirtualMachineFactory(name='yo', userid=user,
318
#                                            operstate="ACTIVE")
319
#        net = dbmf.NetworkFactory(state='ACTIVE', userid=user)
320
#        nic = dbmf.NetworkInterfaceFactory(machine=vm, network=net)
321
#        mrapi().ModifyInstance.return_value = 1
322
#        request = {'remove': {'attachment': "%s" % nic.id}}
323
#        response = self.mypost('networks/%d/action' % net.id,
324
#                               net.userid, json.dumps(request), 'json')
325
#        self.assertEqual(response.status_code, 202)
326
#        vm.task = None
327
#        vm.task_job_id = None
328
#        vm.save()
329
#
330
#    def test_remove_nic_malformed(self, mrapi):
331
#        user = 'userr'
332
#        vm = dbmf.VirtualMachineFactory(name='yo', userid=user)
333
#        net = dbmf.NetworkFactory(state='ACTIVE', userid=user)
334
#        nic = dbmf.NetworkInterfaceFactory(machine=vm, network=net)
335
#        request = {'remove': {'att234achment': '%s' % nic.id}}
336
#        response = self.mypost('networks/%d/action' % net.id,
337
#                               net.userid, json.dumps(request), 'json')
338
#        self.assertBadRequest(response)
339
#
340
#    def test_remove_nic_malformed_2(self, mrapi):
341
#        user = 'userr'
342
#        vm = dbmf.VirtualMachineFactory(name='yo', userid=user)
343
#        net = dbmf.NetworkFactory(state='ACTIVE', userid=user)
344
#        request = {'remove': {'attachment': 'nic-%s' % vm.id}}
345
#        response = self.mypost('networks/%d/action' % net.id,
346
#                               net.userid, json.dumps(request), 'json')
347
#        self.assertBadRequest(response)