Revision 13b954b0

b/api/actions.py
238 238

  
239 239
@network_action('add')
240 240
def add(request, net, args):
241
    # Normal Response Code: 202
242
    # Error Response Codes: computeFault (400, 500),
243
    #                       serviceUnavailable (503),
244
    #                       unauthorized (401),
245
    #                       badRequest (400),
246
    #                       badMediaType(415),
247
    #                       itemNotFound (404),
248
    #                       overLimit (413)
249
    
241 250
    server_id = args.get('serverRef', None)
242 251
    if not server_id:
243 252
        raise BadRequest('Malformed Request.')
......
248 257

  
249 258
@network_action('remove')
250 259
def remove(request, net, args):
260
    # Normal Response Code: 202
261
    # Error Response Codes: computeFault (400, 500),
262
    #                       serviceUnavailable (503),
263
    #                       unauthorized (401),
264
    #                       badRequest (400),
265
    #                       badMediaType(415),
266
    #                       itemNotFound (404),
267
    #                       overLimit (413)
268
    
251 269
    server_id = args.get('serverRef', None)
252 270
    if not server_id:
253 271
        raise BadRequest('Malformed Request.')
b/api/networks.py
84 84
    # Error Response Codes: computeFault (400, 500),
85 85
    #                       serviceUnavailable (503),
86 86
    #                       unauthorized (401),
87
    #                       badMediaType(415),
87 88
    #                       badRequest (400),
88 89
    #                       overLimit (413)
89 90
    
......
104 105
@api_method('GET')
105 106
def get_network_details(request, network):
106 107
    # Normal Response Codes: 200, 203
108
    # Error Response Codes: computeFault (400, 500),
109
    #                       serviceUnavailable (503),
110
    #                       unauthorized (401),
111
    #                       badRequest (400),
112
    #                       itemNotFound (404),
113
    #                       overLimit (413)
107 114
    
108 115
    net = get_network(network, request.user)
109 116
    netdict = network_to_dict(net)
......
112 119
@api_method('PUT')
113 120
def update_network_name(request, network):
114 121
    # Normal Response Code: 204
115

  
122
    # Error Response Codes: computeFault (400, 500),
123
    #                       serviceUnavailable (503),
124
    #                       unauthorized (401),
125
    #                       badRequest (400),
126
    #                       badMediaType(415),
127
    #                       itemNotFound (404),
128
    #                       overLimit (413)
129
    
116 130
    req = get_request_dict(request)
117 131

  
118 132
    try:
......
128 142
@api_method('DELETE')
129 143
def delete_network(request, network):
130 144
    # Normal Response Code: 204
145
    # Error Response Codes: computeFault (400, 500),
146
    #                       serviceUnavailable (503),
147
    #                       unauthorized (401),
148
    #                       itemNotFound (404),
149
    #                       unauthorized (401),
150
    #                       overLimit (413)
131 151
    
132 152
    net = get_network(network, request.user)
133 153
    net.delete()
......
135 155

  
136 156
@api_method('POST')
137 157
def network_action(request, network):
138
    # Normal Response Code: 202
139
    # Error Response Codes: computeFault (400, 500),
140
    #                       serviceUnavailable (503),
141
    #                       unauthorized (401),
142
    #                       badRequest (400),
143
    #                       itemNotFound (404),
144
    #                       overLimit (413)
145
    
146 158
    net = get_network(network, request.user)
147 159
    req = get_request_dict(request)
148 160
    if len(req) != 1:
b/api/tests.py
364 364
            meta_value='Value %d' % (i + 1),
365 365
            vm = choice(servers))
366 366

  
367
def create_networks(n):
368
    users = SynnefoUser.objects.all()
369
    for i in range(n):
370
        Network.objects.create(
371
            name='Network%d' % (i + 1),
372
            owner=choice(users))
373

  
367 374

  
368 375
class AssertInvariant(object):
369 376
    def __init__(self, callable, *args, **kwargs):
......
386 393
    SERVERS = 1
387 394
    SERVER_METADATA = 0
388 395
    IMAGE_METADATA = 0
396
    NETWORKS = 0
389 397
    
390 398
    def setUp(self):
391 399
        self.client = AaiClient()
......
395 403
        create_image_metadata(self.IMAGE_METADATA)
396 404
        create_servers(self.SERVERS)
397 405
        create_server_metadata(self.SERVER_METADATA)
406
        create_networks(self.NETWORKS)
398 407
    
399 408
    def assertFault(self, response, status_code, name):
400 409
        self.assertEqual(response.status_code, status_code)
......
473 482
        for m in ImageMetadata.objects.all():
474 483
            metadata[m.image.id][m.meta_key] = m.meta_value
475 484
        return metadata
485
    
486
    def list_networks(self, detail=False):
487
        path = '/api/v1.1/networks'
488
        if detail:
489
            path += '/detail'
490
        response = self.client.get(path)
491
        self.assertTrue(response.status_code in (200, 203))
492
        reply = json.loads(response.content)
493
        self.assertEqual(reply.keys(), ['networks'])
494
        self.assertEqual(reply['networks'].keys(), ['values'])
495
        return reply['networks']['values']
496
    
497
    def create_network(self, name):
498
        path = '/api/v1.1/networks'
499
        data = json.dumps({'network': {'name': name}})
500
        response = self.client.post(path, data, content_type='application/json')
501
        self.assertEqual(response.status_code, 202)
502
        reply = json.loads(response.content)
503
        self.assertEqual(reply.keys(), ['network'])
504
        return reply
505
    
506
    def get_network_details(self, name):
507
        path = '/api/v1.1/networks/%s' % name
508
        response = self.client.get(path)
509
        self.assertEqual(response.status_code, 200)
510
        reply = json.loads(response.content)
511
        self.assertEqual(reply.keys(), ['network'])
512
        return reply['network']
513
    
514
    def update_network_name(self, name, new_name):
515
        path = '/api/v1.1/networks/%s' % name
516
        data = json.dumps({'network': {'name': new_name}})
517
        response = self.client.put(path, data, content_type='application/json')
518
        self.assertEqual(response.status_code, 204)
519
    
520
    def delete_network(self, name):
521
        path = '/api/v1.1/networks/%s' % name
522
        response = self.client.delete(path)
523
        self.assertEqual(response.status_code, 204)
524
    
525
    def add_to_network(self, network_name, server_id):
526
        path = '/api/v1.1/networks/%s/action' % network_name
527
        data = json.dumps({'add': {'serverRef': server_id}})
528
        response = self.client.post(path, data, content_type='application/json')
529
        self.assertEqual(response.status_code, 202)
530
    
531
    def remove_from_network(self, network_name, server_id):
532
        path = '/api/v1.1/networks/%s/action' % network_name
533
        data = json.dumps({'remove': {'serverRef': server_id}})
534
        response = self.client.post(path, data, content_type='application/json')
535
        self.assertEqual(response.status_code, 202)
536

  
537

  
538
def popdict(l, **kwargs):
539
    """Pops a dict from list `l` based on the predicates given as `kwargs`."""
540
    
541
    for i in range(len(l)):
542
        item = l[i]
543
        match = True
544
        for key, val in kwargs.items():
545
            if item[key] != val:
546
                match = False
547
                break
548
        if match:
549
            del l[i]
550
            return item
551
    return None
476 552

  
477 553

  
478 554
class ListImages(BaseTestCase):
479 555
    IMAGES = 10
480 556
    
481
    def _pop_image(self, images, image_id):
482
        for i in range(len(images)):
483
            image = images[i]
484
            if image['id'] == image_id:
485
                del images[i]
486
                return image
487
        return None
488
    
489 557
    def test_list_images(self):
490 558
        images = self.list_images()
491 559
        keys = set(['id', 'name'])
492 560
        for img in Image.objects.all():
493
            image = self._pop_image(images, img.id)
561
            image = popdict(images, id=img.id)
494 562
            self.assertTrue(image is not None)
495 563
            self.assertEqual(set(image.keys()), keys)
496 564
            self.assertEqual(image['id'], img.id)
......
501 569
        images = self.list_images(detail=True)
502 570
        keys = set(['id', 'name', 'updated', 'created', 'status', 'progress'])
503 571
        for img in Image.objects.all():
504
            image = self._pop_image(images, img.id)
572
            image = popdict(images, id=img.id)
505 573
            self.assertTrue(image is not None)
506 574
            self.assertEqual(set(image.keys()), keys)
507 575
            self.assertEqual(image['id'], img.id)
......
738 806
        console = reply['console']
739 807
        self.assertEqual(console['type'], 'vnc')
740 808
        self.assertEqual(set(console.keys()), set(['type', 'host', 'port', 'password']))
809

  
810

  
811
class ListNetworks(BaseTestCase):
812
    SERVERS = 5
813
    NETWORKS = 5
814
    
815
    def setUp(self):
816
        BaseTestCase.setUp(self)
817
        machines = VirtualMachine.objects.all()
818
        for network in Network.objects.all():
819
            n = randint(0, self.SERVERS)
820
            network.machines.add(*sample(machines, n))
821
            network.save()
822
    
823
    def test_list_networks(self):
824
        networks = self.list_networks()
825
        for net in Network.objects.all():
826
            popdict(networks, name=net.name)
827
        self.assertEqual(networks, [])
828
    
829
    def test_list_networks_detail(self):
830
        networks = self.list_networks(detail=True)
831
        for net in Network.objects.all():
832
            network = popdict(networks, name=net.name)
833
            machines = set(vm.id for vm in net.machines.all())
834
            self.assertEqual(set(network['servers']['values']), machines)
835
        self.assertEqual(networks, [])
836

  
837

  
838
class CreateNetwork(BaseTestCase):
839
    def test_create_network(self):
840
        self.assertEqual(self.list_networks(), [])
841
        self.create_network('net')
842
        networks = self.list_networks()
843
        self.assertEqual(len(networks), 1)
844
        network = networks[0]
845
        self.assertEqual(network['name'], 'net')
846

  
847

  
848
class GetNetworkDetails(BaseTestCase):
849
    SERVERS = 5
850
    NETWORKS = 1
851
    
852
    def test_get_network_details(self):
853
        servers = VirtualMachine.objects.all()
854
        network = Network.objects.all()[0]
855
        name = network.name
856
        
857
        net = self.get_network_details(name)
858
        self.assertEqual(net['servers']['values'], [])
859
        
860
        server_id = choice(servers).id
861
        self.add_to_network(name, server_id)
862
        net = self.get_network_details(name)
863
        self.assertEqual(net['servers']['values'], [server_id])
864

  
865

  
866
class UpdateNetworkName(BaseTestCase):
867
    NETWORKS = 5
868
    
869
    def test_update_network_name(self):
870
        networks = self.list_networks(detail=True)
871
        network = choice(networks)
872
        name = network['name']
873
        new_name = name + '_2'
874
        self.update_network_name(name, new_name)
875
        
876
        network['name'] = new_name
877
        self.assertEqual(self.get_network_details(new_name), network)
878
        
879
        response = self.client.get('/api/v1.1/networks/' + name)
880
        self.assertItemNotFound(response)
881

  
882

  
883
class DeleteNetwork(BaseTestCase):
884
    NETWORKS = 5
885
    
886
    def test_delete_network(self):
887
        networks = self.list_networks()
888
        network = choice(networks)
889
        name = network['name']
890
        self.delete_network(name)
891
        
892
        response = self.client.get('/api/v1.1/networks/' + name)
893
        self.assertItemNotFound(response)
894
        
895
        networks.remove(network)
896
        self.assertEqual(self.list_networks(), networks)
897

  
898

  
899
class NetworkActions(BaseTestCase):
900
    SERVERS = 20
901
    NETWORKS = 1
902
    
903
    def test_add_remove_server(self):
904
        server_ids = [vm.id for vm in VirtualMachine.objects.all()]
905
        network = self.list_networks(detail=True)[0]
906
        name = network['name']
907
        
908
        to_add = set(sample(server_ids, 10))
909
        for server_id in to_add:
910
            self.add_to_network(name, server_id)
911
            net = self.get_network_details(name)
912
            self.assertTrue(server_id in net['servers']['values'])
913
        
914
        net = self.get_network_details(name)
915
        self.assertEqual(set(net['servers']['values']), to_add)
916
        
917
        to_remove = set(sample(to_add, 5))
918
        for server_id in to_remove:
919
            self.remove_from_network(name, server_id)
920
            net = self.get_network_details(name)
921
            self.assertTrue(server_id not in net['servers']['values'])
922
        
923
        net = self.get_network_details(name)
924
        self.assertEqual(set(net['servers']['values']), to_add - to_remove)
b/api/util.py
123 123
        return Network.objects.get(name=network, owner=owner)
124 124
    except ValueError:
125 125
        raise BadRequest('Invalid network name.')
126
    except Image.DoesNotExist:
126
    except Network.DoesNotExist:
127 127
        raise ItemNotFound('Network not found.')
128 128

  
129 129

  

Also available in: Unified diff