File: test_security_groups.py

package info (click to toggle)
python-shade 1.30.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 3,196 kB
  • sloc: python: 33,354; sh: 111; makefile: 15
file content (784 lines) | stat: -rw-r--r-- 30,058 bytes parent folder | download | duplicates (2)
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
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.


import copy

import shade
from shade.tests.unit import base
from shade.tests import fakes

# TODO(mordred): Move id and name to using a getUniqueString() value

neutron_grp_dict = fakes.make_fake_neutron_security_group(
    id='1',
    name='neutron-sec-group',
    description='Test Neutron security group',
    rules=[
        dict(id='1', port_range_min=80, port_range_max=81,
             protocol='tcp', remote_ip_prefix='0.0.0.0/0')
    ]
)


nova_grp_dict = fakes.make_fake_nova_security_group(
    id='2',
    name='nova-sec-group',
    description='Test Nova security group #1',
    rules=[
        fakes.make_fake_nova_security_group_rule(
            id='2', from_port=8000, to_port=8001, ip_protocol='tcp',
            cidr='0.0.0.0/0'),
    ]
)


class TestSecurityGroups(base.RequestsMockTestCase):

    def setUp(self):
        super(TestSecurityGroups, self).setUp()
        self.has_neutron = True

        def fake_has_service(*args, **kwargs):
            return self.has_neutron
        self.cloud.has_service = fake_has_service

    def test_list_security_groups_neutron(self):
        project_id = 42
        self.cloud.secgroup_source = 'neutron'
        self.register_uris([
            dict(method='GET',
                 uri=self.get_mock_url(
                     'network', 'public',
                     append=['v2.0', 'security-groups.json'],
                     qs_elements=["project_id=%s" % project_id]),
                 json={'security_groups': [neutron_grp_dict]})
        ])
        self.cloud.list_security_groups(filters={'project_id': project_id})
        self.assert_calls()

    def test_list_security_groups_nova(self):
        self.register_uris([
            dict(method='GET',
                 uri='{endpoint}/os-security-groups?project_id=42'.format(
                     endpoint=fakes.COMPUTE_ENDPOINT),
                 json={'security_groups': []}),
        ])
        self.cloud.secgroup_source = 'nova'
        self.has_neutron = False
        self.cloud.list_security_groups(filters={'project_id': 42})

        self.assert_calls()

    def test_list_security_groups_none(self):

        self.cloud.secgroup_source = None
        self.has_neutron = False
        self.assertRaises(shade.OpenStackCloudUnavailableFeature,
                          self.cloud.list_security_groups)

    def test_delete_security_group_neutron(self):
        sg_id = neutron_grp_dict['id']
        self.cloud.secgroup_source = 'neutron'
        self.register_uris([
            dict(method='GET',
                 uri=self.get_mock_url(
                     'network', 'public',
                     append=['v2.0', 'security-groups.json']),
                 json={'security_groups': [neutron_grp_dict]}),
            dict(method='DELETE',
                 uri=self.get_mock_url(
                     'network', 'public',
                     append=['v2.0', 'security-groups', '%s.json' % sg_id]),
                 json={})
        ])
        self.assertTrue(self.cloud.delete_security_group('1'))
        self.assert_calls()

    def test_delete_security_group_nova(self):
        self.cloud.secgroup_source = 'nova'
        self.has_neutron = False
        nova_return = [nova_grp_dict]
        self.register_uris([
            dict(method='GET',
                 uri='{endpoint}/os-security-groups'.format(
                     endpoint=fakes.COMPUTE_ENDPOINT),
                 json={'security_groups': nova_return}),
            dict(method='DELETE',
                 uri='{endpoint}/os-security-groups/2'.format(
                     endpoint=fakes.COMPUTE_ENDPOINT)),
        ])
        self.cloud.delete_security_group('2')
        self.assert_calls()

    def test_delete_security_group_neutron_not_found(self):
        self.cloud.secgroup_source = 'neutron'
        self.register_uris([
            dict(method='GET',
                 uri=self.get_mock_url(
                     'network', 'public',
                     append=['v2.0', 'security-groups.json']),
                 json={'security_groups': [neutron_grp_dict]})
        ])
        self.assertFalse(self.cloud.delete_security_group('10'))
        self.assert_calls()

    def test_delete_security_group_nova_not_found(self):
        self.cloud.secgroup_source = 'nova'
        self.has_neutron = False
        nova_return = [nova_grp_dict]
        self.register_uris([
            dict(method='GET',
                 uri='{endpoint}/os-security-groups'.format(
                     endpoint=fakes.COMPUTE_ENDPOINT),
                 json={'security_groups': nova_return}),
        ])
        self.assertFalse(self.cloud.delete_security_group('doesNotExist'))

    def test_delete_security_group_none(self):
        self.cloud.secgroup_source = None
        self.assertRaises(shade.OpenStackCloudUnavailableFeature,
                          self.cloud.delete_security_group,
                          'doesNotExist')

    def test_create_security_group_neutron(self):
        self.cloud.secgroup_source = 'neutron'
        group_name = self.getUniqueString()
        group_desc = self.getUniqueString('description')
        new_group = fakes.make_fake_neutron_security_group(
            id='2',
            name=group_name,
            description=group_desc,
            rules=[])
        self.register_uris([
            dict(method='POST',
                 uri=self.get_mock_url(
                     'network', 'public',
                     append=['v2.0', 'security-groups.json']),
                 json={'security_group': new_group},
                 validate=dict(
                     json={'security_group': {
                         'name': group_name,
                         'description': group_desc
                     }}))
        ])

        r = self.cloud.create_security_group(group_name, group_desc)
        self.assertEqual(group_name, r['name'])
        self.assertEqual(group_desc, r['description'])

        self.assert_calls()

    def test_create_security_group_neutron_specific_tenant(self):
        self.cloud.secgroup_source = 'neutron'
        project_id = "861808a93da0484ea1767967c4df8a23"
        group_name = self.getUniqueString()
        group_desc = 'security group from' \
                     ' test_create_security_group_neutron_specific_tenant'
        new_group = fakes.make_fake_neutron_security_group(
            id='2',
            name=group_name,
            description=group_desc,
            project_id=project_id,
            rules=[])
        self.register_uris([
            dict(method='POST',
                 uri=self.get_mock_url(
                     'network', 'public',
                     append=['v2.0', 'security-groups.json']),
                 json={'security_group': new_group},
                 validate=dict(
                     json={'security_group': {
                         'name': group_name,
                         'description': group_desc,
                         'tenant_id': project_id
                     }}))
        ])

        r = self.cloud.create_security_group(
            group_name,
            group_desc,
            project_id
        )
        self.assertEqual(group_name, r['name'])
        self.assertEqual(group_desc, r['description'])
        self.assertEqual(project_id, r['tenant_id'])

        self.assert_calls()

    def test_create_security_group_nova(self):
        group_name = self.getUniqueString()
        self.has_neutron = False
        group_desc = self.getUniqueString('description')
        new_group = fakes.make_fake_nova_security_group(
            id='2',
            name=group_name,
            description=group_desc,
            rules=[])
        self.register_uris([
            dict(method='POST',
                 uri='{endpoint}/os-security-groups'.format(
                     endpoint=fakes.COMPUTE_ENDPOINT),
                 json={'security_group': new_group},
                 validate=dict(json={
                     'security_group': {
                         'name': group_name,
                         'description': group_desc
                     }})),
        ])

        self.cloud.secgroup_source = 'nova'
        r = self.cloud.create_security_group(group_name, group_desc)
        self.assertEqual(group_name, r['name'])
        self.assertEqual(group_desc, r['description'])

        self.assert_calls()

    def test_create_security_group_none(self):
        self.cloud.secgroup_source = None
        self.has_neutron = False
        self.assertRaises(shade.OpenStackCloudUnavailableFeature,
                          self.cloud.create_security_group,
                          '', '')

    def test_update_security_group_neutron(self):
        self.cloud.secgroup_source = 'neutron'
        new_name = self.getUniqueString()
        sg_id = neutron_grp_dict['id']
        update_return = neutron_grp_dict.copy()
        update_return['name'] = new_name
        self.register_uris([
            dict(method='GET',
                 uri=self.get_mock_url(
                     'network', 'public',
                     append=['v2.0', 'security-groups.json']),
                 json={'security_groups': [neutron_grp_dict]}),
            dict(method='PUT',
                 uri=self.get_mock_url(
                     'network', 'public',
                     append=['v2.0', 'security-groups', '%s.json' % sg_id]),
                 json={'security_group': update_return},
                 validate=dict(json={
                     'security_group': {'name': new_name}}))
        ])
        r = self.cloud.update_security_group(sg_id, name=new_name)
        self.assertEqual(r['name'], new_name)
        self.assert_calls()

    def test_update_security_group_nova(self):
        self.has_neutron = False
        new_name = self.getUniqueString()
        self.cloud.secgroup_source = 'nova'
        nova_return = [nova_grp_dict]
        update_return = nova_grp_dict.copy()
        update_return['name'] = new_name

        self.register_uris([
            dict(method='GET',
                 uri='{endpoint}/os-security-groups'.format(
                     endpoint=fakes.COMPUTE_ENDPOINT),
                 json={'security_groups': nova_return}),
            dict(method='PUT',
                 uri='{endpoint}/os-security-groups/2'.format(
                     endpoint=fakes.COMPUTE_ENDPOINT),
                 json={'security_group': update_return}),
        ])

        r = self.cloud.update_security_group(
            nova_grp_dict['id'], name=new_name)
        self.assertEqual(r['name'], new_name)
        self.assert_calls()

    def test_update_security_group_bad_kwarg(self):
        self.assertRaises(TypeError,
                          self.cloud.update_security_group,
                          'doesNotExist', bad_arg='')

    def test_create_security_group_rule_neutron(self):
        self.cloud.secgroup_source = 'neutron'
        args = dict(
            port_range_min=-1,
            port_range_max=40000,
            protocol='tcp',
            remote_ip_prefix='0.0.0.0/0',
            remote_group_id='456',
            direction='egress',
            ethertype='IPv6'
        )
        expected_args = copy.copy(args)
        # For neutron, -1 port should be converted to None
        expected_args['port_range_min'] = None
        expected_args['security_group_id'] = neutron_grp_dict['id']

        expected_new_rule = copy.copy(expected_args)
        expected_new_rule['id'] = '1234'
        expected_new_rule['tenant_id'] = ''
        expected_new_rule['project_id'] = expected_new_rule['tenant_id']

        self.register_uris([
            dict(method='GET',
                 uri=self.get_mock_url(
                     'network', 'public',
                     append=['v2.0', 'security-groups.json']),
                 json={'security_groups': [neutron_grp_dict]}),
            dict(method='POST',
                 uri=self.get_mock_url(
                     'network', 'public',
                     append=['v2.0', 'security-group-rules.json']),
                 json={'security_group_rule': expected_new_rule},
                 validate=dict(json={
                     'security_group_rule': expected_args}))
        ])
        new_rule = self.cloud.create_security_group_rule(
            secgroup_name_or_id=neutron_grp_dict['id'], **args)
        # NOTE(slaweq): don't check location and properties in new rule
        new_rule.pop("location")
        new_rule.pop("properties")
        self.assertEqual(expected_new_rule, new_rule)
        self.assert_calls()

    def test_create_security_group_rule_neutron_specific_tenant(self):
        self.cloud.secgroup_source = 'neutron'
        args = dict(
            port_range_min=-1,
            port_range_max=40000,
            protocol='tcp',
            remote_ip_prefix='0.0.0.0/0',
            remote_group_id='456',
            direction='egress',
            ethertype='IPv6',
            project_id='861808a93da0484ea1767967c4df8a23'
        )
        expected_args = copy.copy(args)
        # For neutron, -1 port should be converted to None
        expected_args['port_range_min'] = None
        expected_args['security_group_id'] = neutron_grp_dict['id']
        expected_args['tenant_id'] = expected_args['project_id']
        expected_args.pop('project_id')

        expected_new_rule = copy.copy(expected_args)
        expected_new_rule['id'] = '1234'
        expected_new_rule['project_id'] = expected_new_rule['tenant_id']

        self.register_uris([
            dict(method='GET',
                 uri=self.get_mock_url(
                     'network', 'public',
                     append=['v2.0', 'security-groups.json']),
                 json={'security_groups': [neutron_grp_dict]}),
            dict(method='POST',
                 uri=self.get_mock_url(
                     'network', 'public',
                     append=['v2.0', 'security-group-rules.json']),
                 json={'security_group_rule': expected_new_rule},
                 validate=dict(json={
                     'security_group_rule': expected_args}))
        ])
        new_rule = self.cloud.create_security_group_rule(
            secgroup_name_or_id=neutron_grp_dict['id'], ** args)
        # NOTE(slaweq): don't check location and properties in new rule
        new_rule.pop("location")
        new_rule.pop("properties")
        self.assertEqual(expected_new_rule, new_rule)
        self.assert_calls()

    def test_create_security_group_rule_nova(self):
        self.has_neutron = False
        self.cloud.secgroup_source = 'nova'

        nova_return = [nova_grp_dict]

        new_rule = fakes.make_fake_nova_security_group_rule(
            id='xyz', from_port=1, to_port=2000, ip_protocol='tcp',
            cidr='1.2.3.4/32')

        self.register_uris([
            dict(method='GET',
                 uri='{endpoint}/os-security-groups'.format(
                     endpoint=fakes.COMPUTE_ENDPOINT),
                 json={'security_groups': nova_return}),
            dict(method='POST',
                 uri='{endpoint}/os-security-group-rules'.format(
                     endpoint=fakes.COMPUTE_ENDPOINT),
                 json={'security_group_rule': new_rule},
                 validate=dict(json={
                     "security_group_rule": {
                         "from_port": 1,
                         "ip_protocol": "tcp",
                         "to_port": 2000,
                         "parent_group_id": "2",
                         "cidr": "1.2.3.4/32",
                         "group_id": "123"}})),
        ])

        self.cloud.create_security_group_rule(
            '2', port_range_min=1, port_range_max=2000, protocol='tcp',
            remote_ip_prefix='1.2.3.4/32', remote_group_id='123')

        self.assert_calls()

    def test_create_security_group_rule_nova_no_ports(self):

        self.has_neutron = False
        self.cloud.secgroup_source = 'nova'

        new_rule = fakes.make_fake_nova_security_group_rule(
            id='xyz', from_port=1, to_port=65535, ip_protocol='tcp',
            cidr='1.2.3.4/32')

        nova_return = [nova_grp_dict]

        self.register_uris([
            dict(method='GET',
                 uri='{endpoint}/os-security-groups'.format(
                     endpoint=fakes.COMPUTE_ENDPOINT),
                 json={'security_groups': nova_return}),
            dict(method='POST',
                 uri='{endpoint}/os-security-group-rules'.format(
                     endpoint=fakes.COMPUTE_ENDPOINT),
                 json={'security_group_rule': new_rule},
                 validate=dict(json={
                     "security_group_rule": {
                         "from_port": 1,
                         "ip_protocol": "tcp",
                         "to_port": 65535,
                         "parent_group_id": "2",
                         "cidr": "1.2.3.4/32",
                         "group_id": "123"}})),
        ])

        self.cloud.create_security_group_rule(
            '2', protocol='tcp',
            remote_ip_prefix='1.2.3.4/32', remote_group_id='123')

        self.assert_calls()

    def test_create_security_group_rule_none(self):
        self.has_neutron = False
        self.cloud.secgroup_source = None
        self.assertRaises(shade.OpenStackCloudUnavailableFeature,
                          self.cloud.create_security_group_rule,
                          '')

    def test_delete_security_group_rule_neutron(self):
        rule_id = "xyz"
        self.cloud.secgroup_source = 'neutron'
        self.register_uris([
            dict(method='DELETE',
                 uri=self.get_mock_url(
                     'network', 'public',
                     append=['v2.0', 'security-group-rules',
                             '%s.json' % rule_id]),
                 json={})
        ])
        self.assertTrue(self.cloud.delete_security_group_rule(rule_id))
        self.assert_calls()

    def test_delete_security_group_rule_nova(self):
        self.has_neutron = False
        self.cloud.secgroup_source = 'nova'
        self.register_uris([
            dict(method='DELETE',
                 uri='{endpoint}/os-security-group-rules/xyz'.format(
                     endpoint=fakes.COMPUTE_ENDPOINT)),
        ])
        r = self.cloud.delete_security_group_rule('xyz')
        self.assertTrue(r)
        self.assert_calls()

    def test_delete_security_group_rule_none(self):
        self.has_neutron = False
        self.cloud.secgroup_source = None
        self.assertRaises(shade.OpenStackCloudUnavailableFeature,
                          self.cloud.delete_security_group_rule,
                          '')

    def test_delete_security_group_rule_not_found(self):
        rule_id = "doesNotExist"
        self.cloud.secgroup_source = 'neutron'
        self.register_uris([
            dict(method='GET',
                 uri=self.get_mock_url(
                     'network', 'public',
                     append=['v2.0', 'security-groups.json']),
                 json={'security_groups': [neutron_grp_dict]})
        ])
        self.assertFalse(self.cloud.delete_security_group(rule_id))
        self.assert_calls()

    def test_delete_security_group_rule_not_found_nova(self):
        self.has_neutron = False
        self.cloud.secgroup_source = 'nova'
        self.register_uris([
            dict(method='GET',
                 uri='{endpoint}/os-security-groups'.format(
                     endpoint=fakes.COMPUTE_ENDPOINT),
                 json={'security_groups': [nova_grp_dict]}),
        ])
        r = self.cloud.delete_security_group('doesNotExist')
        self.assertFalse(r)

        self.assert_calls()

    def test_nova_egress_security_group_rule(self):
        self.has_neutron = False
        self.cloud.secgroup_source = 'nova'
        self.register_uris([
            dict(method='GET',
                 uri='{endpoint}/os-security-groups'.format(
                     endpoint=fakes.COMPUTE_ENDPOINT),
                 json={'security_groups': [nova_grp_dict]}),
        ])
        self.assertRaises(shade.OpenStackCloudException,
                          self.cloud.create_security_group_rule,
                          secgroup_name_or_id='nova-sec-group',
                          direction='egress')

        self.assert_calls()

    def test_list_server_security_groups_nova(self):
        self.has_neutron = False

        server = dict(id='server_id')

        self.register_uris([
            dict(
                method='GET',
                uri='{endpoint}/servers/{id}/os-security-groups'.format(
                    endpoint=fakes.COMPUTE_ENDPOINT,
                    id='server_id'),
                json={'security_groups': [nova_grp_dict]}),
        ])
        groups = self.cloud.list_server_security_groups(server)
        self.assertIn('location', groups[0])
        self.assertEqual(
            groups[0]['security_group_rules'][0]['remote_ip_prefix'],
            nova_grp_dict['rules'][0]['ip_range']['cidr'])

        self.assert_calls()

    def test_list_server_security_groups_bad_source(self):
        self.has_neutron = False
        self.cloud.secgroup_source = 'invalid'
        server = dict(id='server_id')
        ret = self.cloud.list_server_security_groups(server)
        self.assertEqual([], ret)

    def test_add_security_group_to_server_nova(self):

        self.has_neutron = False
        self.cloud.secgroup_source = 'nova'

        self.register_uris([
            dict(
                method='GET',
                uri='{endpoint}/os-security-groups'.format(
                    endpoint=fakes.COMPUTE_ENDPOINT,
                    id='server_id'),
                json={'security_groups': [nova_grp_dict]}),
            dict(
                method='POST',
                uri='%s/servers/%s/action' % (fakes.COMPUTE_ENDPOINT, '1234'),
                validate=dict(
                    json={'addSecurityGroup': {'name': 'nova-sec-group'}}),
                status_code=202,
            ),
        ])

        ret = self.cloud.add_server_security_groups(
            dict(id='1234'), 'nova-sec-group')

        self.assertTrue(ret)

        self.assert_calls()

    def test_add_security_group_to_server_neutron(self):
        # fake to get server by name, server-name must match
        fake_server = fakes.make_fake_server('1234', 'server-name', 'ACTIVE')

        # use neutron for secgroup list and return an existing fake
        self.cloud.secgroup_source = 'neutron'

        self.register_uris([
            dict(method='GET',
                 uri=self.get_mock_url(
                     'compute', 'public',
                     append=['servers', 'detail']),
                 json={'servers': [fake_server]}),
            dict(method='GET',
                 uri=self.get_mock_url(
                     'network', 'public',
                     append=['v2.0', 'security-groups.json']),
                 json={'security_groups': [neutron_grp_dict]}),
            dict(method='POST',
                 uri='%s/servers/%s/action' % (fakes.COMPUTE_ENDPOINT, '1234'),
                 validate=dict(
                     json={'addSecurityGroup': {'name': 'neutron-sec-group'}}),
                 status_code=202),
        ])

        self.assertTrue(self.cloud.add_server_security_groups(
            'server-name', 'neutron-sec-group'))
        self.assert_calls()

    def test_remove_security_group_from_server_nova(self):

        self.has_neutron = False
        self.cloud.secgroup_source = 'nova'

        self.register_uris([
            dict(
                method='GET',
                uri='{endpoint}/os-security-groups'.format(
                    endpoint=fakes.COMPUTE_ENDPOINT),
                json={'security_groups': [nova_grp_dict]}),
            dict(
                method='POST',
                uri='%s/servers/%s/action' % (fakes.COMPUTE_ENDPOINT, '1234'),
                validate=dict(
                    json={'removeSecurityGroup': {'name': 'nova-sec-group'}}),
            ),
        ])

        ret = self.cloud.remove_server_security_groups(
            dict(id='1234'), 'nova-sec-group')
        self.assertTrue(ret)

        self.assert_calls()

    def test_remove_security_group_from_server_neutron(self):
        # fake to get server by name, server-name must match
        fake_server = fakes.make_fake_server('1234', 'server-name', 'ACTIVE')

        # use neutron for secgroup list and return an existing fake
        self.cloud.secgroup_source = 'neutron'

        validate = {'removeSecurityGroup': {'name': 'neutron-sec-group'}}
        self.register_uris([
            dict(method='GET',
                 uri=self.get_mock_url(
                     'compute', 'public',
                     append=['servers', 'detail']),
                 json={'servers': [fake_server]}),
            dict(method='GET',
                 uri=self.get_mock_url(
                     'network', 'public',
                     append=['v2.0', 'security-groups.json']),
                 json={'security_groups': [neutron_grp_dict]}),
            dict(method='POST',
                 uri='%s/servers/%s/action' % (fakes.COMPUTE_ENDPOINT, '1234'),
                 validate=dict(json=validate)),
        ])

        self.assertTrue(self.cloud.remove_server_security_groups(
            'server-name', 'neutron-sec-group'))
        self.assert_calls()

    def test_add_bad_security_group_to_server_nova(self):
        # fake to get server by name, server-name must match
        fake_server = fakes.make_fake_server('1234', 'server-name', 'ACTIVE')

        # use nova for secgroup list and return an existing fake
        self.has_neutron = False
        self.cloud.secgroup_source = 'nova'
        self.register_uris([
            dict(
                method='GET',
                uri='{endpoint}/servers/detail'.format(
                    endpoint=fakes.COMPUTE_ENDPOINT),
                json={'servers': [fake_server]}),
            dict(
                method='GET',
                uri='{endpoint}/os-security-groups'.format(
                    endpoint=fakes.COMPUTE_ENDPOINT),
                json={'security_groups': [nova_grp_dict]}),
        ])

        ret = self.cloud.add_server_security_groups('server-name',
                                                    'unknown-sec-group')
        self.assertFalse(ret)

        self.assert_calls()

    def test_add_bad_security_group_to_server_neutron(self):
        # fake to get server by name, server-name must match
        fake_server = fakes.make_fake_server('1234', 'server-name', 'ACTIVE')

        # use neutron for secgroup list and return an existing fake
        self.cloud.secgroup_source = 'neutron'

        self.register_uris([
            dict(method='GET',
                 uri=self.get_mock_url(
                     'compute', 'public',
                     append=['servers', 'detail']),
                 json={'servers': [fake_server]}),
            dict(method='GET',
                 uri=self.get_mock_url(
                     'network', 'public',
                     append=['v2.0', 'security-groups.json']),
                 json={'security_groups': [neutron_grp_dict]})
        ])
        self.assertFalse(self.cloud.add_server_security_groups(
            'server-name', 'unknown-sec-group'))
        self.assert_calls()

    def test_add_security_group_to_bad_server(self):
        # fake to get server by name, server-name must match
        fake_server = fakes.make_fake_server('1234', 'server-name', 'ACTIVE')

        self.register_uris([
            dict(
                method='GET',
                uri='{endpoint}/servers/detail'.format(
                    endpoint=fakes.COMPUTE_ENDPOINT),
                json={'servers': [fake_server]}),
        ])

        ret = self.cloud.add_server_security_groups('unknown-server-name',
                                                    'nova-sec-group')
        self.assertFalse(ret)

        self.assert_calls()

    def test_get_security_group_by_id_neutron(self):
        self.cloud.secgroup_source = 'neutron'
        self.register_uris([
            dict(method='GET',
                 uri=self.get_mock_url(
                     'network', 'public',
                     append=['v2.0',
                             'security-groups',
                             neutron_grp_dict['id']]),
                 json={'security_group': neutron_grp_dict})
        ])
        ret_sg = self.cloud.get_security_group_by_id(neutron_grp_dict['id'])
        self.assertEqual(neutron_grp_dict['id'], ret_sg['id'])
        self.assertEqual(neutron_grp_dict['name'], ret_sg['name'])
        self.assertEqual(neutron_grp_dict['description'],
                         ret_sg['description'])
        self.assert_calls()

    def test_get_security_group_by_id_nova(self):
        self.register_uris([
            dict(method='GET',
                 uri='{endpoint}/os-security-groups/{id}'.format(
                     endpoint=fakes.COMPUTE_ENDPOINT,
                     id=nova_grp_dict['id']),
                 json={'security_group': nova_grp_dict}),
        ])
        self.cloud.secgroup_source = 'nova'
        self.has_neutron = False
        ret_sg = self.cloud.get_security_group_by_id(nova_grp_dict['id'])
        self.assertEqual(nova_grp_dict['id'], ret_sg['id'])
        self.assertEqual(nova_grp_dict['name'], ret_sg['name'])
        self.assert_calls()