summaryrefslogtreecommitdiff
path: root/nova/tests/unit/volume/test_cinder.py
blob: e53ebe3cb8f00c900d886fb933a30cad29a06690 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
# Copyright 2013 Mirantis, Inc.
# Copyright 2013 OpenStack Foundation
#
#    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.

from unittest import mock

from cinderclient import api_versions as cinder_api_versions
from cinderclient import exceptions as cinder_exception
from cinderclient.v3 import limits as cinder_limits
from keystoneauth1 import loading as ks_loading
from keystoneauth1 import session
from keystoneclient import exceptions as keystone_exception
from oslo_utils.fixture import uuidsentinel as uuids
from oslo_utils import timeutils

import nova.conf
from nova import context
from nova import exception
from nova import test
from nova.tests.unit.fake_instance import fake_instance_obj
from nova.volume import cinder


CONF = nova.conf.CONF


class FakeVolume(object):

    def __init__(self, volume_id, size=1, attachments=None, multiattach=False):
        self.id = volume_id
        self.name = 'volume_name'
        self.description = 'volume_description'
        self.status = 'available'
        self.created_at = timeutils.utcnow()
        self.size = size
        self.availability_zone = 'nova'
        self.attachments = attachments or []
        self.volume_type = 99
        self.bootable = False
        self.snapshot_id = 'snap_id_1'
        self.metadata = {}
        self.multiattach = multiattach

    def get(self, volume_id):
        return self.volume_id


class FakeSnapshot(object):

    def __init__(self, snapshot_id, volume_id, size=1):
        self.id = snapshot_id
        self.name = 'snapshot_name'
        self.description = 'snapshot_description'
        self.status = 'available'
        self.size = size
        self.created_at = timeutils.utcnow()
        self.progress = '99%'
        self.volume_id = volume_id
        self.project_id = 'fake_project'


class FakeVolumeType(object):
    def __init__(self, volume_type_name, volume_type_id):
        self.id = volume_type_id
        self.name = volume_type_name


class FakeAttachment(object):

    def __init__(self):
        self.id = uuids.attachment_id
        self.status = 'attaching'
        self.instance = uuids.instance_uuid
        self.volume_id = uuids.volume_id
        self.attached_at = timeutils.utcnow()
        self.detached_at = None
        self.attach_mode = 'rw'
        self.connection_info = {'driver_volume_type': 'fake_type',
                                'target_lun': '1',
                                'foo': 'bar',
                                'attachment_id': uuids.attachment_id}
        self.att = {'id': self.id,
                    'status': self.status,
                    'instance': self.instance,
                    'volume_id': self.volume_id,
                    'attached_at': self.attached_at,
                    'detached_at': self.detached_at,
                    'attach_mode': self.attach_mode,
                    'connection_info': self.connection_info}

    def get(self, key, default=None):
        return self.att.get(key, default)

    def __setitem__(self, key, value):
        self.att[key] = value

    def __getitem__(self, key):
        return self.att[key]

    def to_dict(self):
        return self.att


class CinderApiTestCase(test.NoDBTestCase):
    def setUp(self):
        super(CinderApiTestCase, self).setUp()

        self.api = cinder.API()
        self.ctx = context.get_admin_context()

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_get(self, mock_cinderclient):
        volume_id = 'volume_id1'
        mock_volumes = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(volumes=mock_volumes)

        self.api.get(self.ctx, volume_id)

        mock_cinderclient.assert_called_once_with(self.ctx, microversion=None)
        mock_volumes.get.assert_called_once_with(volume_id)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_get_failed_notfound(self, mock_cinderclient):
        mock_cinderclient.return_value.volumes.get.side_effect = (
            cinder_exception.NotFound(404, '404'))

        self.assertRaises(exception.VolumeNotFound,
                  self.api.get, self.ctx, 'id1')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_get_failed_badrequest(self, mock_cinderclient):
        mock_cinderclient.return_value.volumes.get.side_effect = (
            cinder_exception.BadRequest(400, '400'))

        self.assertRaises(exception.InvalidInput,
                  self.api.get, self.ctx, 'id1')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_get_failed_connection_failed(self, mock_cinderclient):
        mock_cinderclient.return_value.volumes.get.side_effect = (
            cinder_exception.ConnectionError(''))

        self.assertRaises(exception.CinderConnectionFailed,
                  self.api.get, self.ctx, 'id1')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_get_with_shared_targets(self, mock_cinderclient):
        """Tests getting a volume at microversion 3.48 which includes the
        shared_targets and service_uuid parameters in the volume response body.
        """
        mock_volume = mock.MagicMock(
            shared_targets=False, service_uuid=uuids.service_uuid)
        mock_volumes = mock.MagicMock()
        mock_volumes.get.return_value = mock_volume
        mock_cinderclient.return_value = mock.MagicMock(volumes=mock_volumes)
        vol = self.api.get(self.ctx, uuids.volume_id, microversion='3.48')
        mock_cinderclient.assert_called_once_with(
            self.ctx, microversion='3.48')
        mock_volumes.get.assert_called_once_with(uuids.volume_id)
        self.assertIn('shared_targets', vol)
        self.assertFalse(vol['shared_targets'])
        self.assertEqual(uuids.service_uuid, vol['service_uuid'])

    @mock.patch('nova.volume.cinder.cinderclient',
                side_effect=exception.CinderAPIVersionNotAvailable(
                    version='3.48'))
    def test_get_microversion_not_supported(self, mock_cinderclient):
        """Tests getting a volume at microversion 3.48 but that version
        is not available.
        """
        self.assertRaises(exception.CinderAPIVersionNotAvailable,
                          self.api.get, self.ctx, uuids.volume_id,
                          microversion='3.48')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_create(self, mock_cinderclient):
        volume = FakeVolume('id1')
        mock_volumes = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(volumes=mock_volumes)
        mock_volumes.create.return_value = volume

        created_volume = self.api.create(self.ctx, 1, '', '')
        self.assertEqual('id1', created_volume['id'])
        self.assertEqual(1, created_volume['size'])

        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volumes.create.assert_called_once_with(1, availability_zone=None,
                                                    description='',
                                                    imageRef=None,
                                                    metadata=None, name='',
                                                    snapshot_id=None,
                                                    volume_type=None)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_create_failed(self, mock_cinderclient):
        mock_cinderclient.return_value.volumes.create.side_effect = (
            cinder_exception.BadRequest(400, '400'))

        self.assertRaises(exception.InvalidInput,
                          self.api.create, self.ctx, 1, '', '')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_create_failed_not_found(self, mock_cinderclient):
        mock_cinderclient.return_value.volumes.create.side_effect = (
            cinder_exception.NotFound(404, 'Volume type can not be found.'))

        ex = self.assertRaises(exception.NotFound,
                               self.api.create, self.ctx, 1, '', '')
        self.assertEqual('Volume type can not be found.', str(ex))

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_create_over_quota_failed(self, mock_cinderclient):
        mock_cinderclient.return_value.volumes.create.side_effect = (
            cinder_exception.OverLimit(413))
        self.assertRaises(exception.OverQuota, self.api.create, self.ctx,
                          1, '', '')
        mock_cinderclient.return_value.volumes.create.assert_called_once_with(
            1, imageRef=None, availability_zone=None,
            volume_type=None, description='', snapshot_id=None, name='',
            metadata=None)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_get_all(self, mock_cinderclient):
        volume1 = FakeVolume('id1')
        volume2 = FakeVolume('id2')

        volume_list = [volume1, volume2]
        mock_volumes = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(volumes=mock_volumes)
        mock_volumes.list.return_value = volume_list

        volumes = self.api.get_all(self.ctx)
        self.assertEqual(2, len(volumes))
        self.assertEqual(['id1', 'id2'], [vol['id'] for vol in volumes])

        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volumes.list.assert_called_once_with(detailed=True,
                                                  search_opts={})

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_get_all_with_search(self, mock_cinderclient):
        volume1 = FakeVolume('id1')

        mock_volumes = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(volumes=mock_volumes)
        mock_volumes.list.return_value = [volume1]

        volumes = self.api.get_all(self.ctx, search_opts={'id': 'id1'})
        self.assertEqual(1, len(volumes))
        self.assertEqual('id1', volumes[0]['id'])

        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volumes.list.assert_called_once_with(detailed=True,
                                                  search_opts={'id': 'id1'})

    @mock.patch.object(cinder.az, 'get_instance_availability_zone',
                       return_value='zone1')
    def test_check_availability_zone_differs(self, mock_get_instance_az):
        self.flags(cross_az_attach=False, group='cinder')
        volume = {'id': uuids.volume_id,
                  'status': 'available',
                  'attach_status': 'detached',
                  'availability_zone': 'zone2'}
        instance = fake_instance_obj(self.ctx)
        # Simulate _provision_instances in the compute API; the instance is not
        # created in the API so the instance will not have an id attribute set.
        delattr(instance, 'id')

        self.assertRaises(exception.InvalidVolume,
                          self.api.check_availability_zone,
                          self.ctx, volume, instance)
        mock_get_instance_az.assert_called_once_with(self.ctx, instance)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_reserve_volume(self, mock_cinderclient):
        mock_volumes = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(volumes=mock_volumes)

        self.api.reserve_volume(self.ctx, 'id1')

        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volumes.reserve.assert_called_once_with('id1')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_unreserve_volume(self, mock_cinderclient):
        mock_volumes = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(volumes=mock_volumes)

        self.api.unreserve_volume(self.ctx, 'id1')

        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volumes.unreserve.assert_called_once_with('id1')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_begin_detaching(self, mock_cinderclient):
        mock_volumes = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(volumes=mock_volumes)

        self.api.begin_detaching(self.ctx, 'id1')

        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volumes.begin_detaching.assert_called_once_with('id1')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_roll_detaching(self, mock_cinderclient):
        mock_volumes = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(volumes=mock_volumes)

        self.api.roll_detaching(self.ctx, 'id1')

        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volumes.roll_detaching.assert_called_once_with('id1')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attach(self, mock_cinderclient):
        mock_volumes = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(volumes=mock_volumes)

        self.api.attach(self.ctx, 'id1', 'uuid', 'point')

        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volumes.attach.assert_called_once_with('id1', 'uuid', 'point',
                                                    mode='rw')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attach_with_mode(self, mock_cinderclient):
        mock_volumes = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(volumes=mock_volumes)

        self.api.attach(self.ctx, 'id1', 'uuid', 'point', mode='ro')

        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volumes.attach.assert_called_once_with('id1', 'uuid', 'point',
                                                    mode='ro')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_create(self, mock_cinderclient):
        """Tests the happy path for creating a volume attachment without a
        mountpoint.
        """
        attachment_ref = {'id': uuids.attachment_id,
                          'connection_info': {}}
        expected_attachment_ref = {'id': uuids.attachment_id,
                                   'connection_info': {}}
        mock_cinderclient.return_value.attachments.create.return_value = (
            attachment_ref)
        result = self.api.attachment_create(
            self.ctx, uuids.volume_id, uuids.instance_id)
        self.assertEqual(expected_attachment_ref, result)
        mock_cinderclient.return_value.attachments.create.\
            assert_called_once_with(uuids.volume_id, None, uuids.instance_id)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_create_with_mountpoint(self, mock_cinderclient):
        """Tests the happy path for creating a volume attachment with a
        mountpoint.
        """
        attachment_ref = {'id': uuids.attachment_id,
                          'connection_info': {}}
        expected_attachment_ref = {'id': uuids.attachment_id,
                                   'connection_info': {}}
        mock_cinderclient.return_value.attachments.create.return_value = (
            attachment_ref)
        original_connector = {'host': 'fake-host'}
        updated_connector = dict(original_connector, mountpoint='/dev/vdb')
        result = self.api.attachment_create(
            self.ctx, uuids.volume_id, uuids.instance_id,
            connector=original_connector, mountpoint='/dev/vdb')
        self.assertEqual(expected_attachment_ref, result)
        # Make sure the original connector wasn't modified.
        self.assertNotIn('mountpoint', original_connector)
        # Make sure the mountpoint was passed through via the connector.
        mock_cinderclient.return_value.attachments.create.\
            assert_called_once_with(uuids.volume_id, updated_connector,
                                    uuids.instance_id)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_create_volume_not_found(self, mock_cinderclient):
        """Tests that the translate_volume_exception decorator is used."""
        # fake out the volume not found error
        mock_cinderclient.return_value.attachments.create.side_effect = (
            cinder_exception.NotFound(404))
        self.assertRaises(exception.VolumeNotFound, self.api.attachment_create,
                          self.ctx, uuids.volume_id, uuids.instance_id)

    @mock.patch('nova.volume.cinder.cinderclient',
                side_effect=exception.CinderAPIVersionNotAvailable(
                    version='3.44'))
    def test_attachment_create_unsupported_api_version(self,
                                                       mock_cinderclient):
        """Tests that CinderAPIVersionNotAvailable is passed back through
        if 3.44 isn't available.
        """
        self.assertRaises(exception.CinderAPIVersionNotAvailable,
                          self.api.attachment_create,
                          self.ctx, uuids.volume_id, uuids.instance_id)
        mock_cinderclient.assert_called_once_with(self.ctx, '3.44')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_update(self, mock_cinderclient):
        """Tests the happy path for updating a volume attachment without
        a mountpoint.
        """
        fake_attachment = FakeAttachment()
        connector = {'host': 'fake-host'}
        expected_attachment_ref = {
             'id': uuids.attachment_id,
             'volume_id': fake_attachment.volume_id,
             'attach_mode': 'rw',
             'connection_info': {
                 'attached_at': fake_attachment.attached_at,
                 'data': {'foo': 'bar', 'target_lun': '1'},
                 'detached_at': None,
                 'driver_volume_type': 'fake_type',
                 'instance': fake_attachment.instance,
                 'status': 'attaching',
                 'volume_id': fake_attachment.volume_id}}
        mock_cinderclient.return_value.attachments.update.return_value = (
            fake_attachment)
        result = self.api.attachment_update(
            self.ctx, uuids.attachment_id, connector=connector)
        self.assertEqual(expected_attachment_ref, result)
        # Make sure the connector wasn't modified.
        self.assertNotIn('mountpoint', connector)
        mock_cinderclient.return_value.attachments.update.\
            assert_called_once_with(uuids.attachment_id, connector)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_update_with_mountpoint(self, mock_cinderclient):
        """Tests the happy path for updating a volume attachment with
        a mountpoint.
        """
        fake_attachment = FakeAttachment()
        original_connector = {'host': 'fake-host'}
        updated_connector = dict(original_connector, mountpoint='/dev/vdb')
        expected_attachment_ref = {
             'id': uuids.attachment_id,
             'volume_id': fake_attachment.volume_id,
             'attach_mode': 'rw',
             'connection_info': {
                 'attached_at': fake_attachment.attached_at,
                 'data': {'foo': 'bar', 'target_lun': '1'},
                 'detached_at': None,
                 'driver_volume_type': 'fake_type',
                 'instance': fake_attachment.instance,
                 'status': 'attaching',
                 'volume_id': fake_attachment.volume_id}}
        mock_cinderclient.return_value.attachments.update.return_value = (
            fake_attachment)
        result = self.api.attachment_update(
            self.ctx, uuids.attachment_id, connector=original_connector,
            mountpoint='/dev/vdb')
        self.assertEqual(expected_attachment_ref, result)
        # Make sure the original connector wasn't modified.
        self.assertNotIn('mountpoint', original_connector)
        # Make sure the mountpoint was passed through via the connector.
        mock_cinderclient.return_value.attachments.update.\
            assert_called_once_with(uuids.attachment_id, updated_connector)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_update_attachment_not_found(self, mock_cinderclient):
        """Tests that the translate_attachment_exception decorator is used."""
        # fake out the volume not found error
        mock_cinderclient.return_value.attachments.update.side_effect = (
            cinder_exception.NotFound(404))
        self.assertRaises(exception.VolumeAttachmentNotFound,
                          self.api.attachment_update,
                          self.ctx, uuids.attachment_id,
                          connector={'host': 'fake-host'})

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_update_attachment_no_connector(self,
                                                       mock_cinderclient):
        """Tests that the translate_cinder_exception decorator is used."""
        # fake out the volume bad request error
        mock_cinderclient.return_value.attachments.update.side_effect = (
            cinder_exception.BadRequest(400))
        self.assertRaises(exception.InvalidInput,
                          self.api.attachment_update,
                          self.ctx, uuids.attachment_id, connector=None)

    @mock.patch('nova.volume.cinder.cinderclient',
                side_effect=exception.CinderAPIVersionNotAvailable(
                    version='3.44'))
    def test_attachment_update_unsupported_api_version(self,
                                                       mock_cinderclient):
        """Tests that CinderAPIVersionNotAvailable is passed back through
        if 3.44 isn't available.
        """
        self.assertRaises(exception.CinderAPIVersionNotAvailable,
                          self.api.attachment_update,
                          self.ctx, uuids.attachment_id, connector={})
        mock_cinderclient.assert_called_once_with(self.ctx, '3.44',
                                                  skip_version_check=True)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_delete(self, mock_cinderclient):
        mock_attachments = mock.MagicMock()
        mock_cinderclient.return_value = \
            mock.MagicMock(attachments=mock_attachments)

        attachment_id = uuids.attachment
        self.api.attachment_delete(self.ctx, attachment_id)

        mock_cinderclient.assert_called_once_with(self.ctx, '3.44',
                                                  skip_version_check=True)
        mock_attachments.delete.assert_called_once_with(attachment_id)

    @mock.patch('nova.volume.cinder.LOG')
    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_delete_failed(self, mock_cinderclient, mock_log):
        mock_cinderclient.return_value.attachments.delete.side_effect = (
                cinder_exception.BadRequest(400, '400'))

        attachment_id = uuids.attachment
        ex = self.assertRaises(exception.InvalidInput,
                               self.api.attachment_delete,
                               self.ctx,
                               attachment_id)

        self.assertEqual(400, ex.code)

    @mock.patch('nova.volume.cinder.cinderclient',
                side_effect=exception.CinderAPIVersionNotAvailable(
                    version='3.44'))
    def test_attachment_delete_unsupported_api_version(self,
                                                       mock_cinderclient):
        """Tests that CinderAPIVersionNotAvailable is passed back through
        if 3.44 isn't available.
        """
        self.assertRaises(exception.CinderAPIVersionNotAvailable,
                          self.api.attachment_delete,
                          self.ctx, uuids.attachment_id)
        mock_cinderclient.assert_called_once_with(self.ctx, '3.44',
                                                  skip_version_check=True)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_delete_not_found(self, mock_cinderclient):
        mock_cinderclient.return_value.attachments.delete.side_effect = (
            cinder_exception.ClientException(404))

        attachment_id = uuids.attachment
        self.api.attachment_delete(self.ctx, attachment_id)

        self.assertEqual(1, mock_cinderclient.call_count)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_delete_internal_server_error(self, mock_cinderclient):
        mock_cinderclient.return_value.attachments.delete.side_effect = (
            cinder_exception.ClientException(500))

        self.assertRaises(cinder_exception.ClientException,
                          self.api.attachment_delete,
                          self.ctx, uuids.attachment_id)

        self.assertEqual(5, mock_cinderclient.call_count)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_delete_internal_server_error_do_not_raise(
                                                      self, mock_cinderclient):
        # generate exception, and then have a normal return on the next retry
        mock_cinderclient.return_value.attachments.delete.side_effect = [
            cinder_exception.ClientException(500), None]

        attachment_id = uuids.attachment
        self.api.attachment_delete(self.ctx, attachment_id)

        self.assertEqual(2, mock_cinderclient.call_count)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_delete_gateway_timeout(self, mock_cinderclient):
        mock_cinderclient.return_value.attachments.delete.side_effect = (
            cinder_exception.ClientException(504))

        self.assertRaises(cinder_exception.ClientException,
                          self.api.attachment_delete,
                          self.ctx, uuids.attachment_id)

        self.assertEqual(5, mock_cinderclient.call_count)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_delete_gateway_timeout_do_not_raise(
                                                      self, mock_cinderclient):
        # generate exception, and then have a normal return on the next retry
        mock_cinderclient.return_value.attachments.delete.side_effect = [
            cinder_exception.ClientException(504), None]

        attachment_id = uuids.attachment
        self.api.attachment_delete(self.ctx, attachment_id)

        self.assertEqual(2, mock_cinderclient.call_count)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_delete_bad_request_exception(self, mock_cinderclient):
        mock_cinderclient.return_value.attachments.delete.side_effect = (
            cinder_exception.BadRequest(400))

        self.assertRaises(exception.InvalidInput,
                          self.api.attachment_delete,
                          self.ctx, uuids.attachment_id)

        self.assertEqual(1, mock_cinderclient.call_count)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_complete(self, mock_cinderclient):
        mock_attachments = mock.MagicMock()
        mock_cinderclient.return_value = \
            mock.MagicMock(attachments=mock_attachments)

        attachment_id = uuids.attachment
        self.api.attachment_complete(self.ctx, attachment_id)

        mock_cinderclient.assert_called_once_with(self.ctx, '3.44',
                                                  skip_version_check=True)
        mock_attachments.complete.assert_called_once_with(attachment_id)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_complete_failed(self, mock_cinderclient):
        mock_cinderclient.return_value.attachments.complete.side_effect = (
            cinder_exception.NotFound(404))

        attachment_id = uuids.attachment
        ex = self.assertRaises(exception.VolumeAttachmentNotFound,
                               self.api.attachment_complete,
                               self.ctx,
                               attachment_id)

        self.assertEqual(404, ex.code)
        self.assertIn(attachment_id, str(ex))

    @mock.patch('nova.volume.cinder.cinderclient',
                side_effect=exception.CinderAPIVersionNotAvailable(
                    version='3.44'))
    def test_attachment_complete_unsupported_api_version(self,
                                                         mock_cinderclient):
        """Tests that CinderAPIVersionNotAvailable is passed back.

        If microversion 3.44 isn't available that should result in a
        CinderAPIVersionNotAvailable exception.
        """
        self.assertRaises(exception.CinderAPIVersionNotAvailable,
                          self.api.attachment_complete,
                          self.ctx, uuids.attachment_id)
        mock_cinderclient.assert_called_once_with(self.ctx, '3.44',
                                                  skip_version_check=True)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_detach(self, mock_cinderclient):
        mock_volumes = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(version='2',
                                                        volumes=mock_volumes)

        self.api.detach(self.ctx, 'id1', instance_uuid='fake_uuid',
                        attachment_id='fakeid')

        mock_cinderclient.assert_called_with(self.ctx)
        mock_volumes.detach.assert_called_once_with('id1', 'fakeid')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_detach_no_attachment_id(self, mock_cinderclient):
        attachment = {'server_id': 'fake_uuid',
                      'attachment_id': 'fakeid'
                     }

        mock_volumes = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(version='2',
                                                        volumes=mock_volumes)
        mock_cinderclient.return_value.volumes.get.return_value = \
            FakeVolume('id1', attachments=[attachment])

        self.api.detach(self.ctx, 'id1', instance_uuid='fake_uuid')

        mock_cinderclient.assert_called_with(self.ctx, microversion=None)
        mock_volumes.detach.assert_called_once_with('id1', None)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_detach_no_attachment_id_multiattach(self, mock_cinderclient):
        attachment = {'server_id': 'fake_uuid',
                      'attachment_id': 'fakeid'
                     }

        mock_volumes = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(version='2',
                                                        volumes=mock_volumes)
        mock_cinderclient.return_value.volumes.get.return_value = \
            FakeVolume('id1', attachments=[attachment], multiattach=True)

        self.api.detach(self.ctx, 'id1', instance_uuid='fake_uuid')

        mock_cinderclient.assert_called_with(self.ctx, microversion=None)
        mock_volumes.detach.assert_called_once_with('id1', 'fakeid')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_detach_internal_server_error(self, mock_cinderclient):
        mock_cinderclient.return_value.volumes.detach.side_effect = (
            cinder_exception.ClientException(500))

        self.assertRaises(cinder_exception.ClientException,
                          self.api.detach,
                          self.ctx, 'id1', instance_uuid='fake_uuid')

        self.assertEqual(
            5, mock_cinderclient.return_value.volumes.detach.call_count)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_detach_internal_server_error_do_not_raise(
                                               self, mock_cinderclient):
        # generate exception, and then have a normal return on the next retry
        mock_cinderclient.return_value.volumes.detach.side_effect = [
            cinder_exception.ClientException(500), None]

        self.api.detach(self.ctx, 'id1', instance_uuid='fake_uuid',
                        attachment_id='fakeid')

        self.assertEqual(
            2, mock_cinderclient.return_value.volumes.detach.call_count)

    @mock.patch('nova.volume.cinder.cinderclient',
                side_effect=cinder_exception.BadRequest(code=400))
    def test_detach_bad_request_exception(self, mock_cinderclient):

        self.assertRaises(exception.InvalidInput,
                          self.api.detach,
                          self.ctx, 'id1', instance_uuid='fake_uuid')

        self.assertEqual(1, mock_cinderclient.call_count)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_get(self, mock_cinderclient):
        mock_attachment = mock.MagicMock()
        mock_cinderclient.return_value = \
            mock.MagicMock(attachments=mock_attachment)

        attachment_id = uuids.attachment
        self.api.attachment_get(self.ctx, attachment_id)

        mock_cinderclient.assert_called_once_with(self.ctx, '3.44',
                                                  skip_version_check=True)
        mock_attachment.show.assert_called_once_with(attachment_id)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_attachment_get_failed(self, mock_cinderclient):
        mock_cinderclient.return_value.attachments.show.side_effect = (
                cinder_exception.NotFound(404, '404'))

        attachment_id = uuids.attachment
        ex = self.assertRaises(exception.VolumeAttachmentNotFound,
                               self.api.attachment_get,
                               self.ctx,
                               attachment_id)

        self.assertEqual(404, ex.code)
        self.assertIn(attachment_id, str(ex))

    @mock.patch('nova.volume.cinder.cinderclient',
                side_effect=exception.CinderAPIVersionNotAvailable(
                    version='3.44'))
    def test_attachment_get_unsupported_api_version(self, mock_cinderclient):
        """Tests that CinderAPIVersionNotAvailable is passed back.

        If microversion 3.44 isn't available that should result in a
        CinderAPIVersionNotAvailable exception.
        """
        self.assertRaises(exception.CinderAPIVersionNotAvailable,
                          self.api.attachment_get,
                          self.ctx, uuids.attachment_id)
        mock_cinderclient.assert_called_once_with(self.ctx, '3.44',
                                                  skip_version_check=True)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_initialize_connection(self, mock_cinderclient):
        connection_info = {'foo': 'bar'}
        mock_cinderclient.return_value.volumes. \
            initialize_connection.return_value = connection_info

        volume_id = 'fake_vid'
        connector = {'host': 'fakehost1'}
        actual = self.api.initialize_connection(self.ctx, volume_id, connector)

        expected = connection_info
        expected['connector'] = connector
        self.assertEqual(expected, actual)

        mock_cinderclient.return_value.volumes. \
            initialize_connection.assert_called_once_with(volume_id, connector)

    @mock.patch('nova.volume.cinder.LOG')
    @mock.patch('nova.volume.cinder.cinderclient')
    def test_initialize_connection_exception_no_code(
                                self, mock_cinderclient, mock_log):
        mock_cinderclient.return_value.volumes. \
            initialize_connection.side_effect = (
                cinder_exception.ClientException(500, "500"))
        mock_cinderclient.return_value.volumes. \
            terminate_connection.side_effect = (
                test.TestingException)

        connector = {'host': 'fakehost1'}
        self.assertRaises(cinder_exception.ClientException,
                          self.api.initialize_connection,
                          self.ctx,
                          'id1',
                          connector)
        self.assertIsNone(mock_log.error.call_args_list[1][0][1]['code'])

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_initialize_connection_rollback(self, mock_cinderclient):
        mock_cinderclient.return_value.volumes.\
            initialize_connection.side_effect = (
                cinder_exception.ClientException(500, "500"))

        connector = {'host': 'host1'}
        ex = self.assertRaises(cinder_exception.ClientException,
                               self.api.initialize_connection,
                               self.ctx,
                               'id1',
                               connector)
        self.assertEqual(500, ex.code)
        mock_cinderclient.return_value.volumes.\
            terminate_connection.assert_called_once_with('id1', connector)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_initialize_connection_no_rollback(self, mock_cinderclient):
        mock_cinderclient.return_value.volumes.\
            initialize_connection.side_effect = test.TestingException

        connector = {'host': 'host1'}
        self.assertRaises(test.TestingException,
                          self.api.initialize_connection,
                          self.ctx,
                          'id1',
                          connector)
        self.assertFalse(mock_cinderclient.return_value.volumes.
            terminate_connection.called)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_terminate_connection(self, mock_cinderclient):
        mock_volumes = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(volumes=mock_volumes)

        self.api.terminate_connection(self.ctx, 'id1', 'connector')

        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volumes.terminate_connection.assert_called_once_with('id1',
                                                                  'connector')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_terminate_connection_internal_server_error(
                                                    self, mock_cinderclient):
        mock_cinderclient.return_value.volumes.terminate_connection.\
            side_effect = cinder_exception.ClientException(500)

        self.assertRaises(cinder_exception.ClientException,
                          self.api.terminate_connection,
                          self.ctx, 'id1', 'connector')

        self.assertEqual(5, mock_cinderclient.call_count)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_terminate_connection_internal_server_error_do_not_raise(
                                                    self, mock_cinderclient):
        # generate exception, and then have a normal return on the next retry
        mock_cinderclient.return_value.volumes.terminate_connection.\
            side_effect = [cinder_exception.ClientException(500),
                           None]

        self.api.terminate_connection(self.ctx, 'id1', 'connector')

        self.assertEqual(2, mock_cinderclient.call_count)

    @mock.patch('nova.volume.cinder.cinderclient',
                side_effect=cinder_exception.BadRequest(code=400))
    def test_terminate_connection_bad_request_exception(
                                                    self, mock_cinderclient):
        self.assertRaises(exception.InvalidInput,
                          self.api.terminate_connection,
                          self.ctx, 'id1', 'connector')

        self.assertEqual(1, mock_cinderclient.call_count)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_delete(self, mock_cinderclient):
        mock_volumes = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(volumes=mock_volumes)

        self.api.delete(self.ctx, 'id1')

        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volumes.delete.assert_called_once_with('id1')

    def test_update(self):
        self.assertRaises(NotImplementedError,
                          self.api.update, self.ctx, '', '')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_get_absolute_limits_forbidden(self, cinderclient):
        """Tests to make sure we gracefully handle a Forbidden error raised
        from python-cinderclient when getting limits.
        """
        cinderclient.return_value.limits.get.side_effect = (
            cinder_exception.Forbidden(403))
        self.assertRaises(
            exception.Forbidden, self.api.get_absolute_limits, self.ctx)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_get_absolute_limits(self, cinderclient):
        """Tests the happy path of getting the absolute limits."""
        expected_limits = {
            "totalSnapshotsUsed": 0,
            "maxTotalBackups": 10,
            "maxTotalVolumeGigabytes": 1000,
            "maxTotalSnapshots": 10,
            "maxTotalBackupGigabytes": 1000,
            "totalBackupGigabytesUsed": 0,
            "maxTotalVolumes": 10,
            "totalVolumesUsed": 0,
            "totalBackupsUsed": 0,
            "totalGigabytesUsed": 0
        }
        limits_obj = cinder_limits.Limits(None, {'absolute': expected_limits})
        cinderclient.return_value.limits.get.return_value = limits_obj
        actual_limits = self.api.get_absolute_limits(self.ctx)
        self.assertDictEqual(expected_limits, actual_limits)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_get_snapshot(self, mock_cinderclient):
        snapshot_id = 'snapshot_id'
        mock_volume_snapshots = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(
            volume_snapshots=mock_volume_snapshots)

        self.api.get_snapshot(self.ctx, snapshot_id)

        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volume_snapshots.get.assert_called_once_with(snapshot_id)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_get_snapshot_failed_notfound(self, mock_cinderclient):
        mock_cinderclient.return_value.volume_snapshots.get.side_effect = (
            cinder_exception.NotFound(404, '404'))

        self.assertRaises(exception.SnapshotNotFound,
                          self.api.get_snapshot, self.ctx, 'snapshot_id')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_get_snapshot_connection_failed(self, mock_cinderclient):
        mock_cinderclient.return_value.volume_snapshots.get.side_effect = (
            cinder_exception.ConnectionError(''))

        self.assertRaises(exception.CinderConnectionFailed,
                          self.api.get_snapshot, self.ctx, 'snapshot_id')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_get_all_snapshots(self, mock_cinderclient):
        snapshot1 = FakeSnapshot('snapshot_id1', 'id1')
        snapshot2 = FakeSnapshot('snapshot_id2', 'id2')

        snapshot_list = [snapshot1, snapshot2]
        mock_volume_snapshots = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(
            volume_snapshots=mock_volume_snapshots)
        mock_volume_snapshots.list.return_value = snapshot_list

        snapshots = self.api.get_all_snapshots(self.ctx)
        self.assertEqual(2, len(snapshots))
        self.assertEqual(['snapshot_id1', 'snapshot_id2'],
                         [snap['id'] for snap in snapshots])
        self.assertEqual(['id1', 'id2'],
                         [snap['volume_id'] for snap in snapshots])

        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volume_snapshots.list.assert_called_once_with(detailed=True)

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_create_snapshot(self, mock_cinderclient):
        snapshot = FakeSnapshot('snapshot_id1', 'id1')
        mock_volume_snapshots = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(
            volume_snapshots=mock_volume_snapshots)
        mock_volume_snapshots.create.return_value = snapshot

        created_snapshot = self.api.create_snapshot(self.ctx,
                                                    'id1',
                                                    'name',
                                                    'description')

        self.assertEqual('snapshot_id1', created_snapshot['id'])
        self.assertEqual('id1', created_snapshot['volume_id'])
        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volume_snapshots.create.assert_called_once_with('id1', False,
                                                             'name',
                                                             'description')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_create_force(self, mock_cinderclient):
        snapshot = FakeSnapshot('snapshot_id1', 'id1')
        mock_volume_snapshots = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(
            volume_snapshots=mock_volume_snapshots)
        mock_volume_snapshots.create.return_value = snapshot

        created_snapshot = self.api.create_snapshot_force(self.ctx,
                                                          'id1',
                                                          'name',
                                                          'description')

        self.assertEqual('snapshot_id1', created_snapshot['id'])
        self.assertEqual('id1', created_snapshot['volume_id'])
        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volume_snapshots.create.assert_called_once_with('id1', True,
                                                             'name',
                                                             'description')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_delete_snapshot(self, mock_cinderclient):
        mock_volume_snapshots = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(
            volume_snapshots=mock_volume_snapshots)

        self.api.delete_snapshot(self.ctx, 'snapshot_id')

        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volume_snapshots.delete.assert_called_once_with('snapshot_id')

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_update_snapshot_status(self, mock_cinderclient):
        mock_volume_snapshots = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(
            volume_snapshots=mock_volume_snapshots)

        self.api.update_snapshot_status(self.ctx, 'snapshot_id', 'error')

        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volume_snapshots.update_snapshot_status.assert_called_once_with(
            'snapshot_id', {'status': 'error', 'progress': '90%'})

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_get_all_volume_types(self, mock_cinderclient):
        volume_type1 = FakeVolumeType('lvm_1', 'volume_type_id1')
        volume_type2 = FakeVolumeType('lvm_2', 'volume_type_id2')
        volume_type_list = [volume_type1, volume_type2]

        mock_volume_types = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(
            volume_types=mock_volume_types)
        mock_volume_types.list.return_value = volume_type_list

        volume_types = self.api.get_all_volume_types(self.ctx)
        self.assertEqual(2, len(volume_types))
        self.assertEqual(['volume_type_id1', 'volume_type_id2'],
                         [vol_type['id'] for vol_type in volume_types])
        self.assertEqual(['lvm_1', 'lvm_2'],
                         [vol_type['name'] for vol_type in volume_types])

        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volume_types.list.assert_called_once_with()

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_get_volume_encryption_metadata(self, mock_cinderclient):
        mock_volumes = mock.MagicMock()
        mock_cinderclient.return_value = mock.MagicMock(volumes=mock_volumes)

        self.api.get_volume_encryption_metadata(self.ctx,
                                                {'encryption_key_id':
                                                 'fake_key'})

        mock_cinderclient.assert_called_once_with(self.ctx)
        mock_volumes.get_encryption_metadata.assert_called_once_with(
            {'encryption_key_id': 'fake_key'})

    @mock.patch('nova.volume.cinder.cinderclient')
    def test_volume_reimage(self, mock_cinderclient):
        mock_reimage = mock.MagicMock()
        mock_volumes = mock.MagicMock(reimage=mock_reimage)
        mock_cinderclient.return_value = mock.MagicMock(volumes=mock_volumes)
        self.api.reimage_volume(
            self.ctx, uuids.volume_id, uuids.image_id,
            reimage_reserved=True)
        mock_cinderclient.assert_called_once_with(self.ctx, '3.68')
        mock_reimage.assert_called_with(uuids.volume_id, uuids.image_id, True)

    def test_translate_cinder_exception_no_error(self):
        my_func = mock.Mock()
        my_func.__name__ = 'my_func'
        my_func.return_value = 'foo'

        res = cinder.translate_cinder_exception(my_func)('fizzbuzz',
                                                         'bar', 'baz')

        self.assertEqual('foo', res)
        my_func.assert_called_once_with('fizzbuzz', 'bar', 'baz')

    def test_translate_cinder_exception_cinder_connection_error(self):
        self._do_translate_cinder_exception_test(
            cinder_exception.ConnectionError,
            exception.CinderConnectionFailed)

    def test_translate_cinder_exception_keystone_connection_error(self):
        self._do_translate_cinder_exception_test(
            keystone_exception.ConnectionError,
            exception.CinderConnectionFailed)

    def test_translate_cinder_exception_cinder_bad_request(self):
        self._do_translate_cinder_exception_test(
            cinder_exception.BadRequest(400, '400'),
            exception.InvalidInput)

    def test_translate_cinder_exception_keystone_bad_request(self):
        self._do_translate_cinder_exception_test(
            keystone_exception.BadRequest,
            exception.InvalidInput)

    def test_translate_cinder_exception_cinder_forbidden(self):
        self._do_translate_cinder_exception_test(
            cinder_exception.Forbidden(403, '403'),
            exception.Forbidden)

    def test_translate_cinder_exception_keystone_forbidden(self):
        self._do_translate_cinder_exception_test(
            keystone_exception.Forbidden,
            exception.Forbidden)

    def test_translate_mixed_exception_over_limit(self):
        self._do_translate_mixed_exception_test(
            cinder_exception.OverLimit(''),
            exception.OverQuota)

    def test_translate_mixed_exception_volume_not_found(self):
        self._do_translate_mixed_exception_test(
            cinder_exception.NotFound(''),
            exception.VolumeNotFound)

    def test_translate_mixed_exception_keystone_not_found(self):
        self._do_translate_mixed_exception_test(
            keystone_exception.NotFound,
            exception.VolumeNotFound)

    def test_translate_create_exception_keystone_not_found(self):
        self._do_translate_create_exception_test(
            keystone_exception.NotFound,
            exception.NotFound)

    def test_translate_create_exception_volume_not_found(self):
        self._do_translate_create_exception_test(
            cinder_exception.NotFound('Volume type could not be found'),
            exception.NotFound)

    def _do_translate_cinder_exception_test(self, raised_exc, expected_exc):
        self._do_translate_exception_test(raised_exc, expected_exc,
                                          cinder.translate_cinder_exception)

    def _do_translate_mixed_exception_test(self, raised_exc, expected_exc):
        self._do_translate_exception_test(raised_exc, expected_exc,
                                          cinder.translate_mixed_exceptions)

    def _do_translate_create_exception_test(self, raised_exc, expected_exc):
        self._do_translate_exception_test(raised_exc, expected_exc,
                                          cinder.translate_create_exception)

    def _do_translate_exception_test(self, raised_exc, expected_exc, wrapper):
        my_func = mock.Mock()
        my_func.__name__ = 'my_func'
        my_func.side_effect = raised_exc

        self.assertRaises(expected_exc, wrapper(my_func), 'foo', 'bar', 'baz')


class CinderClientTestCase(test.NoDBTestCase):
    """Used to test constructing a cinder client object at various versions."""

    def setUp(self):
        super(CinderClientTestCase, self).setUp()
        cinder.reset_globals()
        self.ctxt = context.RequestContext('fake-user', 'fake-project')
        # Mock out the keystoneauth stuff.
        self.mock_session = mock.Mock(autospec=session.Session)
        patcher = mock.patch('keystoneauth1.loading.'
                                  'load_session_from_conf_options',
                                  return_value=self.mock_session)
        patcher.start()
        self.addCleanup(patcher.stop)

    @mock.patch('cinderclient.client.get_volume_api_from_url',
                return_value='3')
    def test_create_v3_client_no_microversion(self, get_volume_api):
        """Tests that creating a v3 client, which is the default, and without
        specifying a microversion will default to 3.0 as the version to use.
        """
        client = cinder.cinderclient(self.ctxt)
        self.assertEqual(cinder_api_versions.APIVersion('3.0'),
                         client.api_version)
        get_volume_api.assert_called_once_with(
            self.mock_session.get_endpoint.return_value)

    @mock.patch('nova.volume.cinder._get_highest_client_server_version',
                # Fake the case that cinder is really old.
                return_value=cinder_api_versions.APIVersion('2.0'))
    @mock.patch('cinderclient.client.get_volume_api_from_url',
                return_value='3')
    def test_create_v3_client_with_microversion_too_new(self,
                                                        get_volume_api,
                                                        get_highest_version):
        """Tests that creating a v3 client and requesting a microversion that
        is either too new for the server (or client) to support raises an
        exception.
        """
        self.assertRaises(exception.CinderAPIVersionNotAvailable,
                          cinder.cinderclient, self.ctxt, microversion='3.44')
        get_volume_api.assert_called_once_with(
            self.mock_session.get_endpoint.return_value)
        get_highest_version.assert_called_once_with(
            self.ctxt, self.mock_session.get_endpoint.return_value)

    @mock.patch('nova.volume.cinder._get_highest_client_server_version',
                return_value=cinder_api_versions.APIVersion(
                    cinder_api_versions.MAX_VERSION))
    @mock.patch('cinderclient.client.get_volume_api_from_url',
                return_value='3')
    def test_create_v3_client_with_microversion_available(self,
                                                          get_volume_api,
                                                          get_highest_version):
        """Tests that creating a v3 client and requesting a microversion that
        is available in the server and supported by the client will result in
        creating a Client object with the requested microversion.
        """
        client = cinder.cinderclient(self.ctxt, microversion='3.44')
        self.assertEqual(cinder_api_versions.APIVersion('3.44'),
                         client.api_version)
        get_volume_api.assert_called_once_with(
            self.mock_session.get_endpoint.return_value)
        get_highest_version.assert_called_once_with(
            self.ctxt, self.mock_session.get_endpoint.return_value)

    @mock.patch('nova.volume.cinder._get_highest_client_server_version',
                new_callable=mock.NonCallableMock)  # asserts not called
    @mock.patch('cinderclient.client.get_volume_api_from_url',
                return_value='3')
    def test_create_v3_client_with_microversion_skip_version_check(
            self, get_volume_api, get_highest_version):
        """Tests that creating a v3 client and requesting a microversion
        but asking to skip the version discovery check is honored.
        """
        client = cinder.cinderclient(self.ctxt, microversion='3.44',
                                     skip_version_check=True)
        self.assertEqual(cinder_api_versions.APIVersion('3.44'),
                         client.api_version)
        get_volume_api.assert_called_once_with(
            self.mock_session.get_endpoint.return_value)

    @mock.patch('nova.volume.cinder.LOG.error')
    @mock.patch.object(ks_loading, 'load_auth_from_conf_options')
    def test_load_auth_plugin_failed(self, mock_load_from_conf, mock_log_err):
        mock_load_from_conf.return_value = None
        self.assertRaises(cinder_exception.Unauthorized,
                          cinder._load_auth_plugin, CONF)
        mock_log_err.assert_called()
        self.assertIn('The [cinder] section of your nova configuration file',
                      mock_log_err.call_args[0][0])

    @mock.patch('nova.volume.cinder._ADMIN_AUTH')
    def test_admin_context_without_token(self,
                                         mock_admin_auth):

        mock_admin_auth.return_value = '_FAKE_ADMIN_AUTH'
        admin_ctx = context.get_admin_context()
        params = cinder._get_cinderclient_parameters(admin_ctx)
        self.assertEqual(params[0], mock_admin_auth)