/
test_crud_basic.py
1859 lines (1594 loc) · 80.7 KB
/
test_crud_basic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
import gevent
import os
import sys
import socket
import errno
import uuid
import logging
import coverage
import cgitb
cgitb.enable(format='text')
import fixtures
import testtools
from testtools.matchers import Equals, MismatchError, Not, Contains, LessThan
from testtools import content, content_type, ExpectedException
import unittest
from flexmock import flexmock
import re
import json
import copy
from lxml import etree
import inspect
import pycassa
import kombu
import requests
import bottle
import stevedore
from vnc_api.vnc_api import *
from vnc_api.common import exceptions as vnc_exceptions
import vnc_api.gen.vnc_api_test_gen
from vnc_api.gen.resource_test import *
import cfgm_common
from cfgm_common import vnc_plugin_base
from cfgm_common import imid
sys.path.append('../common/tests')
from test_utils import *
import test_common
import test_case
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
class TestCrudBasic(object):
#class TestCrudBasic(gen.vnc_api_test_gen.VncApiTestGen):
def setUp(self):
super(TestCrudBasic, self).setUp()
test_common.setup_flexmock()
api_server_ip = socket.gethostbyname(socket.gethostname())
api_server_port = get_free_port()
http_server_port = get_free_port()
self._api_svr = gevent.spawn(test_common.launch_api_server,
api_server_ip, api_server_port,
http_server_port)
block_till_port_listened(api_server_ip, api_server_port)
self._vnc_lib = VncApi('u', 'p', api_server_host=api_server_ip,
api_server_port=api_server_port)
# end setUp
def tearDown(self):
super(TestCrudBasic, self).tearDown()
#gevent.kill(self._api_svr, gevent.GreenletExit)
# gevent.joinall([self._api_svr])
# end tearDown
def test_virtual_DNS_crud(self):
vdns_fixt = self.useFixture(VirtualDnsTestFixtureGen(self._vnc_lib))
vdns = vdns_fixt._obj
d = vdns.get_virtual_DNS_data()
d.set_domain_name('test-domain')
vdns.set_virtual_DNS_data(d)
self._vnc_lib.virtual_DNS_update(vdns)
# end test_virtual_DNS_crud
def test_virtual_DNS_record_crud(self):
vdns_fixt = self.useFixture(VirtualDnsTestFixtureGen(self._vnc_lib))
self.useFixture(VirtualDnsRecordTestFixtureGen(self._vnc_lib,
parent_fixt=vdns_fixt))
# end test_virtual_DNS_record_crud
def test_access_control_list_crud(self):
sg_fixt = self.useFixture(SecurityGroupTestFixtureGen(self._vnc_lib))
self.useFixture(AccessControlListTestFixtureGen(self._vnc_lib,
parent_fixt=sg_fixt))
vn_fixt = self.useFixture(VirtualNetworkTestFixtureGen(self._vnc_lib))
self.useFixture(AccessControlListTestFixtureGen(self._vnc_lib,
parent_fixt=vn_fixt))
#end test_access_control_list_crud
def test_instance_ip_crud(self):
pass
# end test_instance_ip_crud
def test_floating_ip_crud(self):
pass
# end test_floating_ip_crud
def test_id_perms(self):
# create object in enabled state
# create object in disabled state
# update to enable
# create with description set
# create with perms set
# update perms
# update id, verify fails
pass
# end test_id_perms
# end class TestCrudBasic
class TestFixtures(test_case.ApiServerTestCase):
def test_fixture_ref(self):
proj_fixt = self.useFixture(
ProjectTestFixtureGen(self._vnc_lib, project_name='admin'))
# 2 policies, 2 VNs associate and check
pol_1_fixt = self.useFixture(NetworkPolicyTestFixtureGen(
self._vnc_lib, network_policy_name='policy1111',
parent_fixt=proj_fixt))
pol_2_fixt = self.useFixture(NetworkPolicyTestFixtureGen(
self._vnc_lib, network_policy_name='policy2222',
parent_fixt=proj_fixt))
ref_tuple = [(pol_1_fixt._obj,
VirtualNetworkPolicyType(
sequence=SequenceType(major=0, minor=0)))]
ref_tuple2 = [(pol_2_fixt._obj,
VirtualNetworkPolicyType(
sequence=SequenceType(major=0, minor=0)))]
vn_blue = self.useFixture(
VirtualNetworkTestFixtureGen(
self._vnc_lib, virtual_network_name='vnblue',
parent_fixt=proj_fixt, id_perms=IdPermsType(enable=True),
network_policy_ref_infos=ref_tuple))
vn_red = self.useFixture(
VirtualNetworkTestFixtureGen(
self._vnc_lib, virtual_network_name='vnred',
parent_fixt=proj_fixt, id_perms=IdPermsType(enable=True),
network_policy_ref_infos=ref_tuple2))
policy_name = vn_blue.get_network_policys()[0].fixture()[0].name
self.assertThat(policy_name, Equals('policy1111'))
policy_name = vn_red.get_network_policys()[0].fixture()[0].name
self.assertThat(policy_name, Equals('policy2222'))
# ipam referring to virtual dns
vdns_data = VirtualDnsType(domain_name='abc.net', record_order='fixed',
default_ttl_seconds=360)
vdns_fixt = self.useFixture(
VirtualDnsTestFixtureGen(self._vnc_lib, virtual_DNS_name='vdns1',
virtual_DNS_data=vdns_data))
dns_method = "virtual-dns-server"
dns_server = IpamDnsAddressType(
virtual_dns_server_name=vdns_fixt.getObj().get_fq_name_str())
ipam_mgmt = IpamType(
ipam_dns_method=dns_method, ipam_dns_server=dns_server)
ipam_fixt = self.useFixture(
NetworkIpamTestFixtureGen(
self._vnc_lib, network_ipam_name='ipam1',
parent_fixt=proj_fixt,
network_ipam_mgmt=ipam_mgmt,
virtual_DNS_refs=[vdns_fixt.getObj()]))
# end test_fixture_ref
def test_fixture_reuse_policy(self):
proj_fixt = self.useFixture(
ProjectTestFixtureGen(self._vnc_lib, project_name='admin'))
pol_fixt = self.useFixture(NetworkPolicyTestFixtureGen(
self._vnc_lib, network_policy_name='policy1111',
parent_fixt=proj_fixt))
ref_tuple = [(pol_fixt._obj,
VirtualNetworkPolicyType(
sequence=SequenceType(major=0, minor=0)))]
vn1 = self.useFixture(
VirtualNetworkTestFixtureGen(
self._vnc_lib, virtual_network_name='vn1',
parent_fixt=proj_fixt, id_perms=IdPermsType(enable=True),
network_policy_ref_infos=ref_tuple))
vn2 = self.useFixture(
VirtualNetworkTestFixtureGen(
self._vnc_lib, virtual_network_name='vn2',
parent_fixt=proj_fixt, id_perms=IdPermsType(enable=True),
network_policy_ref_infos=ref_tuple))
vn3 = self.useFixture(
VirtualNetworkTestFixtureGen(
self._vnc_lib, virtual_network_name='vn3',
parent_fixt=proj_fixt, id_perms=IdPermsType(enable=True),
network_policy_ref_infos=ref_tuple))
vn4 = self.useFixture(
VirtualNetworkTestFixtureGen(
self._vnc_lib, virtual_network_name='vn4',
parent_fixt=proj_fixt, id_perms=IdPermsType(enable=True),
network_policy_ref_infos=ref_tuple))
vn5 = self.useFixture(
VirtualNetworkTestFixtureGen(
self._vnc_lib, virtual_network_name='vn5',
parent_fixt=proj_fixt, id_perms=IdPermsType(enable=True),
network_policy_ref_infos=ref_tuple))
npolicy_children = len(proj_fixt.getObj().get_network_policys())
self.assertThat(npolicy_children, Equals(1))
# end test_fixture_reuse_policy
# end class TestFixtures
class TestNetAddrAlloc(object):
#class TestNetAddrAlloc(testtools.TestCase, fixtures.TestWithFixtures):
def setUp(self):
super(TestNetAddrAlloc, self).setUp()
test_common.setup_flexmock()
api_server_ip = socket.gethostbyname(socket.gethostname())
api_server_port = get_free_port()
http_server_port = get_free_port()
self._api_svr = gevent.spawn(test_common.launch_api_server,
api_server_ip, api_server_port,
http_server_port)
block_till_port_listened(api_server_ip, api_server_port)
self._vnc_lib = VncApi('u', 'p', api_server_host=api_server_ip,
api_server_port=api_server_port)
# end setUp
def tearDown(self):
super(TestNetAddrAlloc, self).tearDown()
#gevent.kill(self._api_svr, gevent.GreenletExit)
# gevent.joinall([self._api_svr])
# end tearDown
def test_ip_alloc_on_net(self):
# create subnet on default-virtual-network, auto allocate ip
ipam_fixt = self.useFixture(NetworkIpamTestFixtureGen(self._vnc_lib))
vn_fixt = self.useFixture(VirtualNetworkTestFixtureGen(self._vnc_lib))
subnet_vnc = IpamSubnetType(subnet=SubnetType('1.1.1.0', 24))
vnsn_data = VnSubnetsType([subnet_vnc])
logger.info("Creating subnet 1.1.1.0/24")
vn_fixt.add_network_ipam(ipam_fixt.getObj(), vnsn_data)
logger.info("Creating auto-alloc instance-ip, expecting 1.1.1.253...")
iip_fixt = self.useFixture(
InstanceIpTestFixtureGen(
self._vnc_lib, 'iip1', auto_prop_val=False,
virtual_network_refs=[vn_fixt.getObj()]))
ip_allocated = iip_fixt.getObj().instance_ip_address
self.assertThat(ip_allocated, Equals('1.1.1.253'))
logger.info("...verified")
logger.info("Creating specific instance-ip, expecting 1.1.1.2...")
iip_fixt = self.useFixture(
InstanceIpTestFixtureGen(
self._vnc_lib, 'iip2', auto_prop_val=False,
instance_ip_address='1.1.1.2',
virtual_network_refs=[vn_fixt.getObj()]))
ip_allocated = iip_fixt.getObj().instance_ip_address
self.assertThat(ip_allocated, Equals('1.1.1.2'))
logger.info("...verified")
logger.info("Creating floating-ip-pool")
fip_pool_fixt = self.useFixture(
FloatingIpPoolTestFixtureGen(self._vnc_lib, 'fip-pool',
parent_fixt=vn_fixt,
auto_prop_val=False))
logger.info("Creating auto-alloc floating-ip, expecting 1.1.1.252...")
fip_fixt = self.useFixture(
FloatingIpTestFixtureGen(
self._vnc_lib, 'fip1', parent_fixt=fip_pool_fixt,
auto_prop_val=False))
ip_allocated = fip_fixt.getObj().floating_ip_address
self.assertThat(ip_allocated, Equals('1.1.1.252'))
logger.info("...verified")
logger.info("Creating specific floating-ip, expecting 1.1.1.3...")
fip_fixt = self.useFixture(
FloatingIpTestFixtureGen(
self._vnc_lib, 'fip2', parent_fixt=fip_pool_fixt,
auto_prop_val=False, floating_ip_address='1.1.1.3'))
ip_allocated = fip_fixt.getObj().floating_ip_address
self.assertThat(ip_allocated, Equals('1.1.1.3'))
logger.info("...verified")
logger.info("Creating subnet 2.2.2.0/24, gateway 2.2.2.128")
subnet_vnc = IpamSubnetType(subnet=SubnetType('2.2.2.0', 24),
default_gateway='2.2.2.128')
vnsn_data.add_ipam_subnets(subnet_vnc)
vn_fixt.add_network_ipam(ipam_fixt.getObj(), vnsn_data)
logger.info("Creating specific instance-ip, expecting 2.2.2.254...")
iip_fixt = self.useFixture(
InstanceIpTestFixtureGen(
self._vnc_lib, 'iip3', auto_prop_val=False,
instance_ip_address='2.2.2.254',
virtual_network_refs=[vn_fixt.getObj()]))
ip_allocated = iip_fixt.getObj().instance_ip_address
self.assertThat(ip_allocated, Equals('2.2.2.254'))
logger.info("...verified")
# Create a subnet with ip. try deleting subnet verify it fails.
# Remove the ip and retry delete and verify it passes.
logger.info("Creating subnet 3.3.3.0/24, and instance-ip in it")
vn_obj = vn_fixt.getObj()
subnet_vnc_3 = IpamSubnetType(subnet=SubnetType('3.3.3.0', 24))
vnsn_data.add_ipam_subnets(subnet_vnc_3)
vn_fixt.add_network_ipam(ipam_fixt.getObj(), vnsn_data)
iip_obj = InstanceIp(instance_ip_address='3.3.3.1')
iip_obj.add_virtual_network(vn_obj)
self._vnc_lib.instance_ip_create(iip_obj)
logger.info("Trying to remove 3.3.3.0/24, expecting failure...")
vnsn_data.delete_ipam_subnets(subnet_vnc_3)
vn_obj.set_network_ipam(ipam_fixt.getObj(), vnsn_data)
#with self.assertRaises(vnc_exceptions.RefsExistError) as e:
try:
self._vnc_lib.virtual_network_update(vn_obj)
except vnc_exceptions.RefsExistError as e:
logger.info("...verified")
logger.info("Removing IIP and delete 3.3.3.0/24, expecting success...")
self._vnc_lib.instance_ip_delete(id=iip_obj.uuid)
self._vnc_lib.virtual_network_update(vn_obj)
logger.info("...verified")
# end test_ip_alloc_on_net
def test_ip_alloc_on_ip_fabric(self):
pass
# end test_ip_alloc_on_ip_fabric
def test_ip_alloc_on_link_local(self):
pass
# end test_ip_alloc_on_link_local
def test_alloc_with_subnet_id(self):
ipam_fixt = self.useFixture(NetworkIpamTestFixtureGen(self._vnc_lib))
subnet_vnc = IpamSubnetType(subnet=SubnetType('1.1.1.0', 24))
vnsn_data = VnSubnetsType([subnet_vnc])
subnet_vnc_1 = IpamSubnetType(subnet=SubnetType('2.2.2.0', 24),
default_gateway='2.2.2.128')
vnsn_data.add_ipam_subnets(subnet_vnc_1)
vn_fixt = self.useFixture(VirtualNetworkTestFixtureGen(self._vnc_lib,
network_ipam_ref_infos=[(ipam_fixt.getObj(), vnsn_data)]))
vn_fixt.getObj().set_router_external(True)
self._vnc_lib.virtual_network_update(vn_fixt.getObj())
vn_obj = self._vnc_lib.virtual_network_read(fq_name=vn_fixt.getobj().get_fq_name())
ipam_subnets = vn_obj.network_ipam_refs[0]['attr'].get_ipam_subnets()
# This should be using the first subnet, ie 1.1.1.x
iip_fixt_1 = self.useFixture(
InstanceIpTestFixtureGen(
self._vnc_lib, 'iip1', auto_prop_val=False,
virtual_network_refs=[vn_fixt.getObj()]))
self.assertEqual(iip_fixt_1.getObj().instance_ip_address[:6], "1.1.1.")
# This should be using the first subnet since its uuid is used
iip_fixt_2 = self.useFixture(
InstanceIpTestFixtureGen(
self._vnc_lib, 'iip2', auto_prop_val=False,
subnet_uuid=ipam_subnets[0].subnet_uuid,
virtual_network_refs=[vn_fixt.getObj()]))
self.assertEqual(iip_fixt_2.getObj().instance_ip_address[:6], "1.1.1.")
# Since second subnet's uuid is used, we should get IP from that
iip_fixt_3 = self.useFixture(
InstanceIpTestFixtureGen(
self._vnc_lib, 'iip3', auto_prop_val=False,
subnet_uuid=ipam_subnets[1].subnet_uuid,
virtual_network_refs=[vn_fixt.getObj()]))
self.assertEqual(iip_fixt_3.getObj().instance_ip_address[:6], "2.2.2.")
# Mismatched UUID and IP address combination, should catch an exception
with self.assertRaises(cfgm_common.exceptions.HttpError) as e:
iip_fixt_4 = self.useFixture(
InstanceIpTestFixtureGen(
self._vnc_lib, 'iip4', auto_prop_val=False,
subnet_uuid=ipam_subnets[1].subnet_uuid,
instance_ip_address='1.1.1.4',
virtual_network_refs=[vn_fixt.getObj()]))
#end test_alloc_with_subnet_id
# end class TestNetAddrAlloc
class DemoFixture(object):
#class DemoFixture(fixtures.Fixture):
def __init__(self, vnc_lib):
self._vnc_lib = vnc_lib
# end __init__
def setUp(self):
super(DemoFixture, self).setUp()
dom_fixt = self.useFixture(
gen.vnc_api_test_gen.DomainTestFixtureGen(self._vnc_lib))
proj_1_fixt = self.useFixture(
gen.vnc_api_test_gen.ProjectTestFixtureGen(self._vnc_lib,
'proj-1', dom_fixt))
proj_2_fixt = self.useFixture(
gen.vnc_api_test_gen.ProjectTestFixtureGen(self._vnc_lib,
'proj-2', dom_fixt))
self.useFixture(gen.vnc_api_test_gen.VirtualNetworkTestFixtureGen(
self._vnc_lib, 'front-end', proj_1_fixt))
self.useFixture(gen.vnc_api_test_gen.VirtualNetworkTestFixtureGen(
self._vnc_lib, 'back-end', proj_1_fixt))
self.useFixture(gen.vnc_api_test_gen.VirtualNetworkTestFixtureGen(
self._vnc_lib, 'public', proj_2_fixt))
# end setUp
def cleanUp(self):
super(DemoFixture, self).cleanUp()
# end cleanUp
# end class DemoFixture
# class TestDemo(testtools.TestCase, fixtures.TestWithFixtures):
class TestDemo(object):
def setUp(self):
super(TestDemo, self).setUp()
test_common.setup_flexmock()
api_server_ip = socket.gethostbyname(socket.gethostname())
api_server_port = get_free_port()
http_server_port = get_free_port()
self._api_svr = gevent.spawn(test_common.launch_api_server,
api_server_ip, api_server_port,
http_server_port)
block_till_port_listened(api_server_ip, api_server_port)
self._vnc_lib = VncApi('u', 'p', api_server_host=api_server_ip,
api_server_port=api_server_port)
# end setUp
def tearDown(self):
super(TestDemo, self).tearDown()
#gevent.kill(self._api_svr, gevent.GreenletExit)
# gevent.joinall([self._api_svr])
# end tearDown
def test_demo(self):
self.useFixture(DemoFixture(self._vnc_lib))
# end test_demo
# end class TestDemo
# class TestRefUpdate(unittest.TestCase):
class TestRefUpdate(object):
def setUp(self):
test_common.setup_flexmock()
api_server_ip = socket.gethostbyname(socket.gethostname())
api_server_port = get_free_port()
http_server_port = get_free_port()
gevent.spawn(test_common.launch_api_server,
api_server_ip, api_server_port, http_server_port)
block_till_port_listened(api_server_ip, api_server_port)
self._vnc_lib = VncApi('u', 'p', api_server_host=api_server_ip,
api_server_port=api_server_port)
# end setUp
def test_vn_ipam_ref(self):
vnc_lib = self._vnc_lib
# create with ref
vn_obj = VirtualNetwork('vn1')
ipam_obj = NetworkIpam('ipam1')
vn_obj.add_network_ipam(ipam_obj, VnSubnetsType())
vnc_lib.network_ipam_create(ipam_obj)
vnc_lib.virtual_network_create(vn_obj)
vn_obj = vnc_lib.virtual_network_read(id=vn_obj.uuid)
fq_name = vn_obj.get_network_ipam_refs()[0]['to']
ipam_name = vnc_lib.network_ipam_read(fq_name=fq_name).name
self.assertEqual(ipam_obj.name, ipam_name)
# ref after create
vn_obj = VirtualNetwork('vn2')
ipam_obj = NetworkIpam('ipam2')
vnc_lib.network_ipam_create(ipam_obj)
vnc_lib.virtual_network_create(vn_obj)
vn_obj.add_network_ipam(ipam_obj, VnSubnetsType())
vnc_lib.virtual_network_update(vn_obj)
vn_obj = vnc_lib.virtual_network_read(id=vn_obj.uuid)
fq_name = vn_obj.get_network_ipam_refs()[0]['to']
ipam_name = vnc_lib.network_ipam_read(fq_name=fq_name).name
self.assertEqual(ipam_obj.name, ipam_name)
# del should fail when someone is referring to us
with self.assertRaises(vnc_exceptions.RefsExistError) as e:
vnc_lib.network_ipam_delete(id=ipam_obj.uuid)
# del should succeed when refs are detached
vn_obj.del_network_ipam(ipam_obj)
vnc_lib.virtual_network_update(vn_obj)
vnc_lib.network_ipam_delete(id=ipam_obj.uuid)
# end test_vn_ipam_ref(self):
# end class TestRefUpdate
class TestListUpdate(test_case.ApiServerTestCase):
def test_policy_create_w_rules(self):
proj_fixt = self.useFixture(ProjectTestFixtureGen(self._vnc_lib))
policy_obj = NetworkPolicy(
'test-policy-create-w-rules', proj_fixt.getObj())
np_rules = [
PolicyRuleType(direction='<>',
action_list=ActionListType(simple_action='pass'),
protocol='any',
src_addresses=
[AddressType(virtual_network='local')],
src_ports=[PortType(-1, -1)],
dst_addresses=[AddressType(virtual_network='any')],
dst_ports=[PortType(-1, -1)]),
PolicyRuleType(direction='<>',
action_list=ActionListType(simple_action='deny'),
protocol='any',
src_addresses=
[AddressType(virtual_network='local')],
src_ports=[PortType(-1, -1)],
dst_addresses=[AddressType(virtual_network='any')],
dst_ports=[PortType(-1, -1)]),
]
policy_obj.set_network_policy_entries(PolicyEntriesType(np_rules))
self._vnc_lib.network_policy_create(policy_obj)
# cleanup
self._vnc_lib.network_policy_delete(id=policy_obj.uuid)
# end test_policy_create_w_rules
def test_policy_create_wo_rules(self):
proj_fixt = self.useFixture(ProjectTestFixtureGen(self._vnc_lib))
policy_obj = NetworkPolicy(
'test-policy-create-wo-rules', proj_fixt.getObj())
self._vnc_lib.network_policy_create(policy_obj)
np_rules = [
PolicyRuleType(direction='<>',
action_list=ActionListType(simple_action='pass'),
protocol='any',
src_addresses=
[AddressType(virtual_network='local')],
src_ports=[PortType(1, 2)],
dst_addresses=[AddressType(virtual_network='any')],
dst_ports=[PortType(3, 4)]),
PolicyRuleType(direction='<>',
action_list=ActionListType(simple_action='deny'),
protocol='any',
src_addresses=
[AddressType(virtual_network='local')],
src_ports=[PortType(5, 6)],
dst_addresses=[AddressType(virtual_network='any')],
dst_ports=[PortType(7, 8)]),
]
policy_entries = PolicyEntriesType(np_rules)
policy_obj.set_network_policy_entries(policy_entries)
self._vnc_lib.network_policy_update(policy_obj)
policy_entries.policy_rule.append(
PolicyRuleType(direction='<>',
action_list=ActionListType(simple_action= 'deny'),
protocol='any',
src_addresses=
[AddressType(virtual_network='local')],
src_ports=[PortType(9, 10)],
dst_addresses=[AddressType(virtual_network='any')],
dst_ports=[PortType(11, 12)])
)
policy_obj.set_network_policy_entries(policy_entries)
self._vnc_lib.network_policy_update(policy_obj)
# cleanup
self._vnc_lib.network_policy_delete(id=policy_obj.uuid)
# end test_policy_create_wo_rules
# end class TestListUpdate
class TestCrud(test_case.ApiServerTestCase):
def test_create(self):
test_obj = self._create_test_object()
self.assertTill(self.ifmap_has_ident, obj=test_obj)
class TestVncCfgApiServer(test_case.ApiServerTestCase):
def _create_vn_ri_vmi(self, obj_count=1):
vn_objs = []
ri_objs = []
vmi_objs = []
for i in range(obj_count):
vn_obj = VirtualNetwork('%s-vn-%s' %(self.id(), i))
self._vnc_lib.virtual_network_create(vn_obj)
vn_objs.append(vn_obj)
ri_obj = RoutingInstance('%s-ri-%s' %(self.id(), i),
parent_obj=vn_obj)
self._vnc_lib.routing_instance_create(ri_obj)
ri_objs.append(ri_obj)
vmi_obj = VirtualMachineInterface('%s-vmi-%s' %(self.id(), i),
parent_obj=Project())
vmi_obj.add_virtual_network(vn_obj)
self._vnc_lib.virtual_machine_interface_create(vmi_obj)
vmi_objs.append(vmi_obj)
return vn_objs, ri_objs, vmi_objs
# end _create_vn_ri_vmi
def test_fq_name_to_id_http_post(self):
test_obj = self._create_test_object()
test_uuid = self._vnc_lib.fq_name_to_id('virtual-network', test_obj.get_fq_name())
# check that format is correct
try:
uuid.UUID(test_uuid)
except ValueError:
self.assertTrue(False, 'Bad form UUID ' + test_uuid)
with ExpectedException(NoIdError) as e:
test_uuid = self._vnc_lib.fq_name_to_id('project', test_obj.get_fq_name())
def test_id_to_fq_name_http_post(self):
test_obj = self._create_test_object()
fq_name = self._vnc_lib.id_to_fq_name(test_obj.uuid)
self.assertEqual(test_obj.fq_name, fq_name)
with ExpectedException(NoIdError) as e:
self._vnc_lib.id_to_fq_name(str(uuid.uuid4()))
def test_useragent_kv_http_post(self):
# unikey store
test_body = json.dumps({'operation': 'STORE',
'key': 'fookey',
'value': 'fooval'})
self.addDetail('useragent-kv-post-store', content.json_content(test_body))
(code, msg) = self._http_post('/useragent-kv', test_body)
self.assertEqual(code, 200)
# unikey retrieve
test_body = json.dumps({'operation': 'RETRIEVE',
'key': 'fookey'})
self.addDetail('useragent-kv-post-retrieve', content.json_content(test_body))
(code, msg) = self._http_post('/useragent-kv', test_body)
self.assertEqual(code, 200)
self.assertEqual(json.loads(msg)['value'], 'fooval')
# multikey retrieve
test_body = json.dumps({'operation': 'STORE',
'key': 'barkey',
'value': 'barval'})
self.addDetail('useragent-kv-post-store', content.json_content(test_body))
(code, msg) = self._http_post('/useragent-kv', test_body)
self.assertEqual(code, 200)
test_body = json.dumps({'operation': 'RETRIEVE',
'key': ['fookey', 'barkey']})
self.addDetail('useragent-kv-post-multikey-retrieve',
content.json_content(test_body))
(code, msg) = self._http_post('/useragent-kv', test_body)
self.assertEqual(code, 200)
self.assertEqual(len(json.loads(msg)['value']), 2)
self.assertThat(json.loads(msg)['value'], Contains('fooval'))
self.assertThat(json.loads(msg)['value'], Contains('barval'))
# wrong op test
test_body = json.dumps({'operation': 'foo',
'key': 'fookey'})
self.addDetail('useragent-kv-post-wrongop', content.json_content(test_body))
(code, msg) = self._http_post('/useragent-kv', test_body)
self.assertEqual(code, 404)
def test_err_on_max_rabbit_pending(self):
api_server = test_common.vnc_cfg_api_server.server
max_pend_upd = 10
api_server._args.rabbit_max_pending_updates = str(max_pend_upd)
orig_rabbitq_pub = api_server._db_conn._msgbus._producer.publish
orig_rabbitq_conn = api_server._db_conn._msgbus._conn.connect
try:
def err_rabbitq_pub(*args, **kwargs):
raise Exception("Faking Rabbit publish failure")
def err_rabbitq_conn(*args, **kwargs):
gevent.sleep(0.1)
raise Exception("Faking RabbitMQ connection failure")
api_server._db_conn._msgbus._producer.publish = err_rabbitq_pub
api_server._db_conn._msgbus._conn.connect = err_rabbitq_conn
logger.info("Creating objects to hit max rabbit pending.")
# every create updates project quota
test_objs = self._create_test_objects(count=max_pend_upd+1)
def asserts_on_max_pending():
self.assertEqual(e.status_code, 500)
self.assertIn("Too many pending updates", e.content)
logger.info("Creating one more object expecting failure.")
obj = VirtualNetwork('vn-to-fail')
self.addDetail('expecting-failed-create', content.text_content(obj.name))
try:
self._vnc_lib.virtual_network_create(obj)
except HttpError as e:
asserts_on_max_pending()
else:
self.assertTrue(False, 'Create succeeded unexpectedly')
logger.info("Update of object should fail.")
test_objs[0].display_name = 'foo'
try:
self._vnc_lib.virtual_network_update(test_objs[0])
except HttpError as e:
asserts_on_max_pending()
else:
self.assertTrue(False, 'Update succeeded unexpectedly')
logger.info("Delete of object should fail.")
test_objs[0].display_name = 'foo'
try:
self._vnc_lib.virtual_network_delete(id=test_objs[0].uuid)
except HttpError as e:
asserts_on_max_pending()
else:
self.assertTrue(False, 'Delete succeeded unexpectedly')
logger.info("Read obj object should be ok.")
self._vnc_lib.virtual_network_read(id=test_objs[0].uuid)
finally:
api_server._db_conn._msgbus._producer.publish = orig_rabbitq_pub
api_server._db_conn._msgbus._conn.connect = orig_rabbitq_conn
def test_err_on_ifmap_publish(self):
api_server = test_common.vnc_cfg_api_server.server
orig_call_async_result = api_server._db_conn._ifmap_db._mapclient.call_async_result
def err_call_async_result(*args, **kwargs):
# restore orig method and return error to check handling
api_server._db_conn._ifmap_db._mapclient.call_async_result = orig_call_async_result
publish_err_xml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><ns3:Envelope xmlns:ns2="http://www.trustedcomputinggroup.org/2010/IFMAP/2" xmlns:ns3="http://www.w3.org/2003/05/soap-envelope"><ns3:Body><ns2:response><errorResult errorCode="AccessDenied"><errorString>Existing SSRC</errorString></errorResult></ns2:response></ns3:Body></ns3:Envelope>'
return publish_err_xml
api_server._db_conn._ifmap_db._mapclient.call_async_result = err_call_async_result
test_obj = self._create_test_object()
self.assertTill(self.ifmap_has_ident, obj=test_obj)
def test_reconnect_to_rabbit(self):
exceptions = [(FakeKombu.Connection.ConnectionException(), 'conn'),
(FakeKombu.Connection.ChannelException(), 'chan'),
(Exception(), 'generic')]
# fake problem on publish to rabbit
# restore, ensure retry and successful publish
for exc_obj, exc_type in exceptions:
obj = VirtualNetwork('%s-pub-%s' %(self.id(), exc_type))
obj.uuid = str(uuid.uuid4())
publish_captured = [False]
def err_on_publish(orig_method, *args, **kwargs):
msg = args[0]
if msg['oper'] == 'CREATE' and msg['uuid'] == obj.uuid:
publish_captured[0] = True
raise exc_obj
return orig_method(*args, **kwargs)
rabbit_producer = self._api_server._db_conn._msgbus._producer
with test_common.patch(rabbit_producer,
'publish', err_on_publish):
self._vnc_lib.virtual_network_create(obj)
self.assertTill(lambda: publish_captured[0] == True)
# unpatch err publish
self.assertTill(self.ifmap_has_ident, obj=obj)
# end exception types on publish
# fake problem on consume from rabbit
# restore, ensure retry and successful consume
for exc_obj, exc_type in exceptions:
obj = VirtualNetwork('%s-sub-%s' %(self.id(), exc_type))
obj.uuid = str(uuid.uuid4())
consume_captured = [False]
consume_test_payload = [None]
rabbit_consumer = self._api_server._db_conn._msgbus._consumer
def err_on_consume(orig_method, *args, **kwargs):
msg = orig_method()
payload = msg.payload
if payload['oper'] == 'UPDATE' and payload['uuid'] == obj.uuid:
if (consume_test_payload[0] == payload):
return msg
consume_captured[0] = True
consume_test_payload[0] = payload
rabbit_consumer.queues.put(payload, None)
raise exc_obj
return msg
with test_common.patch(rabbit_consumer.queues,
'get', err_on_consume):
# create the object to insert 'get' handler,
# update oper will test the error handling
self._vnc_lib.virtual_network_create(obj)
obj.display_name = 'test_update'
self._vnc_lib.virtual_network_update(obj)
self.assertTill(lambda: consume_captured[0] == True)
# unpatch err consume
def ifmap_has_ident_update():
ifmap_id = imid.get_ifmap_id_from_fq_name(obj.get_type(),
obj.get_fq_name())
node = FakeIfmapClient._graph.get(ifmap_id)
if not node:
return False
meta = node.get('links', {}).get('contrail:display-name',
{}).get('meta')
if not meta:
return False
if not 'test_update' in etree.tostring(meta):
return False
return True
self.assertTill(ifmap_has_ident_update)
# end exception types on consume
# fake problem on consume and publish at same time
# restore, ensure retry and successful publish + consume
obj = VirtualNetwork('%s-pub-sub' %(self.id()))
obj.uuid = str(uuid.uuid4())
msgbus = self._api_server._db_conn._msgbus
pub_greenlet = msgbus._publisher_greenlet
sub_greenlet = msgbus._connection_monitor_greenlet
setattr(pub_greenlet, 'unittest', {'name': 'producer'})
setattr(sub_greenlet, 'unittest', {'name': 'consumer'})
consume_captured = [False]
consume_test_payload = [None]
publish_connect_done = [False]
publish_captured = [False]
def err_on_consume(orig_method, *args, **kwargs):
msg = orig_method()
payload = msg.payload
if payload['oper'] == 'UPDATE' and payload['uuid'] == obj.uuid:
if (consume_test_payload[0] == payload):
return msg
consume_captured[0] = True
consume_test_payload[0] = payload
rabbit_consumer = self._api_server._db_conn._msgbus._consumer
rabbit_consumer.queues.put(payload, None)
raise exc_obj
return msg
def block_on_connect(orig_method, *args, **kwargs):
# block consumer till publisher does update,
# fake consumer connect exceptions till publisher connects fine
utvars = getattr(gevent.getcurrent(), 'unittest', None)
if utvars and utvars['name'] == 'producer':
publish_connect_done[0] = True
return orig_method(*args, **kwargs)
while not publish_captured[0]:
gevent.sleep(0.1)
while not publish_connect_done[0]:
gevent.sleep(0.1)
raise Exception('Faking connection fail')
return orig_method(*args, **kwargs)
rabbit_consumer = self._api_server._db_conn._msgbus._consumer
rabbit_conn = self._api_server._db_conn._msgbus._conn
with test_common.patch(rabbit_consumer.queues,
'get', err_on_consume):
with test_common.patch(rabbit_conn,
'connect', block_on_connect):
# create the object to insert 'get' handler,
# update oper will test the error handling
self._vnc_lib.virtual_network_create(obj)
obj.display_name = 'test_update_1'
self._vnc_lib.virtual_network_update(obj)
self.assertTill(lambda: consume_captured[0] == True)
def err_on_publish(orig_method, *args, **kwargs):
msg = args[0]
if msg['oper'] == 'UPDATE' and msg['uuid'] == obj.uuid:
publish_captured[0] = True
raise exc_obj
return orig_method(*args, **kwargs)
rabbit_producer = self._api_server._db_conn._msgbus._producer
with test_common.patch(rabbit_producer,
'publish', err_on_publish):
obj.display_name = 'test_update_2'
self._vnc_lib.virtual_network_update(obj)
self.assertTill(lambda: publish_captured[0] == True)
# unpatch err publish
# unpatch connect
# unpatch err consume
def ifmap_has_update_2():
ifmap_id = imid.get_ifmap_id_from_fq_name(obj.get_type(),
obj.get_fq_name())
node = FakeIfmapClient._graph.get(ifmap_id)
if not node:
return False
meta = node.get('links', {}).get('contrail:display-name',
{}).get('meta')
if meta is None:
return False
if not 'test_update_2' in etree.tostring(meta):
return False
return True
self.assertTill(ifmap_has_update_2)
# end test_reconnect_to_rabbit
def test_handle_trap_on_exception(self):
api_server = test_common.vnc_cfg_api_server.server
def exception_on_log_error(*args, **kwargs):
self.assertTrue(False)
def exception_on_vn_read(*args, **kwargs):
raise Exception("fake vn read exception")
try:
orig_config_log = api_server.config_log
api_server.config_log = exception_on_log_error
with ExpectedException(NoIdError):
self._vnc_lib.virtual_network_read(fq_name=['foo', 'bar', 'baz'])
finally:
api_server.config_log = orig_config_log
try:
orig_vn_read = api_server._db_conn._cassandra_db._cassandra_virtual_network_read
test_obj = self._create_test_object()
api_server._db_conn._cassandra_db._cassandra_virtual_network_read = exception_on_vn_read
with ExpectedException(HttpError):
self._vnc_lib.virtual_network_read(fq_name=test_obj.get_fq_name())
finally:
api_server._db_conn._cassandra_db._cassandra_virtual_network_read = orig_vn_read
def test_sandesh_trace(self):
from lxml import etree
api_server = test_common.vnc_cfg_api_server.server
# the test
test_obj = self._create_test_object()
self.assertTill(self.ifmap_has_ident, obj=test_obj)
self._vnc_lib.virtual_network_delete(id=test_obj.uuid)
# and validations
introspect_port = api_server._args.http_server_port
traces = requests.get('http://localhost:%s/Snh_SandeshTraceRequest?x=RestApiTraceBuf' %(introspect_port))
self.assertThat(traces.status_code, Equals(200))
top_elem = etree.fromstring(traces.text)
self.assertThat(top_elem[0][0][0].text, Contains('POST'))
self.assertThat(top_elem[0][0][0].text, Contains('200 OK'))
self.assertThat(top_elem[0][0][1].text, Contains('DELETE'))
self.assertThat(top_elem[0][0][1].text, Contains('200 OK'))
traces = requests.get('http://localhost:%s/Snh_SandeshTraceRequest?x=DBRequestTraceBuf' %(introspect_port))
self.assertThat(traces.status_code, Equals(200))
top_elem = etree.fromstring(traces.text)
self.assertThat(top_elem[0][0][-1].text, Contains('delete'))
self.assertThat(top_elem[0][0][-1].text, Contains(test_obj.name))
traces = requests.get('http://localhost:%s/Snh_SandeshTraceRequest?x=MessageBusNotifyTraceBuf' %(introspect_port))
self.assertThat(traces.status_code, Equals(200))
top_elem = etree.fromstring(traces.text)
self.assertThat(top_elem[0][0][-1].text, Contains('DELETE'))
self.assertThat(top_elem[0][0][-1].text, Contains(test_obj.name))
traces = requests.get('http://localhost:%s/Snh_SandeshTraceRequest?x=IfmapTraceBuf' %(introspect_port))
self.assertThat(traces.status_code, Equals(200))
top_elem = etree.fromstring(traces.text)
print top_elem[0][0][-1].text
self.assertThat(top_elem[0][0][-1].text, Contains('delete'))
self.assertThat(top_elem[0][0][-1].text, Contains(test_obj.name))
def test_dup_create_with_same_uuid(self):
dom_name = self.id() + '-domain'
logger.info('Creating Domain %s', dom_name)
domain_obj = Domain(dom_name)
self._vnc_lib.domain_create(domain_obj)