summaryrefslogtreecommitdiff
path: root/nova/tests/unit/api/openstack/compute/test_hypervisors.py
blob: facc5389be3195fe8ea6fd825a1135e6a9a2b5ea (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
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
# Copyright (c) 2012 OpenStack Foundation
# All Rights Reserved.
#
#    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 mock
import netaddr
from oslo_serialization import jsonutils
from oslo_utils.fixture import uuidsentinel as uuids
from webob import exc

from nova.api.openstack.compute import hypervisors as hypervisors_v21
from nova import exception
from nova import objects
from nova import test
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import fake_instance


CPU_INFO = """
{"arch": "x86_64",
"vendor": "fake",
"topology": {"cores": 1, "threads": 1, "sockets": 1},
"features": [],
"model": ""}"""

TEST_HYPERS = [
    dict(id=1,
         uuid=uuids.hyper1,
         service_id=1,
         host="compute1",
         vcpus=4,
         memory_mb=10 * 1024,
         local_gb=250,
         vcpus_used=2,
         memory_mb_used=5 * 1024,
         local_gb_used=125,
         hypervisor_type="xen",
         hypervisor_version=3,
         hypervisor_hostname="hyper1",
         free_ram_mb=5 * 1024,
         free_disk_gb=125,
         current_workload=2,
         running_vms=2,
         cpu_info=CPU_INFO,
         disk_available_least=100,
         host_ip=netaddr.IPAddress('1.1.1.1')),
    dict(id=2,
         uuid=uuids.hyper2,
         service_id=2,
         host="compute2",
         vcpus=4,
         memory_mb=10 * 1024,
         local_gb=250,
         vcpus_used=2,
         memory_mb_used=5 * 1024,
         local_gb_used=125,
         hypervisor_type="xen",
         hypervisor_version=3,
         hypervisor_hostname="hyper2",
         free_ram_mb=5 * 1024,
         free_disk_gb=125,
         current_workload=2,
         running_vms=2,
         cpu_info=CPU_INFO,
         disk_available_least=100,
         host_ip=netaddr.IPAddress('2.2.2.2'))]


TEST_SERVICES = [
    objects.Service(id=1,
                    uuid=uuids.service1,
                    host="compute1",
                    binary="nova-compute",
                    topic="compute_topic",
                    report_count=5,
                    disabled=False,
                    disabled_reason=None,
                    availability_zone="nova"),
    objects.Service(id=2,
                    uuid=uuids.service2,
                    host="compute2",
                    binary="nova-compute",
                    topic="compute_topic",
                    report_count=5,
                    disabled=False,
                    disabled_reason=None,
                    availability_zone="nova"),
]

TEST_HYPERS_OBJ = [objects.ComputeNode(**hyper_dct)
                   for hyper_dct in TEST_HYPERS]

TEST_HYPERS[0].update({'service': TEST_SERVICES[0]})
TEST_HYPERS[1].update({'service': TEST_SERVICES[1]})

TEST_SERVERS = [dict(name="inst1", uuid=uuids.instance_1, host="compute1"),
                dict(name="inst2", uuid=uuids.instance_2, host="compute2"),
                dict(name="inst3", uuid=uuids.instance_3, host="compute1"),
                dict(name="inst4", uuid=uuids.instance_4, host="compute2")]


def fake_compute_node_get_all(context, limit=None, marker=None):
    if marker in ['99999', uuids.invalid_marker]:
        raise exception.MarkerNotFound(marker)
    marker_found = True if marker is None else False
    output = []
    for hyper in TEST_HYPERS_OBJ:
        # Starting with the 2.53 microversion, the marker is a uuid.
        if not marker_found and marker in (str(hyper.id), hyper.uuid):
            marker_found = True
        elif marker_found:
            if limit is None or len(output) < int(limit):
                output.append(hyper)
    return output


def fake_compute_node_search_by_hypervisor(context, hypervisor_re):
    return TEST_HYPERS_OBJ


def fake_compute_node_get(context, compute_id):
    for hyper in TEST_HYPERS_OBJ:
        if hyper.uuid == compute_id:
            return hyper

        if (
            (isinstance(compute_id, int) or compute_id.isdigit()) and
            hyper.id == int(compute_id)
        ):
            return hyper
    raise exception.ComputeHostNotFound(host=compute_id)


def fake_service_get_by_compute_host(context, host):
    for service in TEST_SERVICES:
        if service.host == host:
            return service


def fake_compute_node_statistics(context):
    result = dict(
        count=0,
        vcpus=0,
        memory_mb=0,
        local_gb=0,
        vcpus_used=0,
        memory_mb_used=0,
        local_gb_used=0,
        free_ram_mb=0,
        free_disk_gb=0,
        current_workload=0,
        running_vms=0,
        disk_available_least=0,
        )

    for hyper in TEST_HYPERS_OBJ:
        for key in result:
            if key == 'count':
                result[key] += 1
            else:
                result[key] += getattr(hyper, key)

    return result


def fake_instance_get_all_by_host(context, host):
    results = []
    for inst in TEST_SERVERS:
        if inst['host'] == host:
            inst_obj = fake_instance.fake_instance_obj(context, **inst)
            results.append(inst_obj)
    return results


class HypervisorsTestV21(test.NoDBTestCase):
    api_version = '2.1'
    # Allow subclasses to override if the id value in the response is the
    # compute node primary key integer id or the uuid.
    expect_uuid_for_id = False

    # TODO(stephenfin): These should just be defined here
    TEST_HYPERS_OBJ = copy.deepcopy(TEST_HYPERS_OBJ)
    TEST_SERVICES = copy.deepcopy(TEST_SERVICES)
    TEST_SERVERS = copy.deepcopy(TEST_SERVERS)

    DETAIL_HYPERS_DICTS = copy.deepcopy(TEST_HYPERS)
    del DETAIL_HYPERS_DICTS[0]['service_id']
    del DETAIL_HYPERS_DICTS[1]['service_id']
    del DETAIL_HYPERS_DICTS[0]['host']
    del DETAIL_HYPERS_DICTS[1]['host']
    del DETAIL_HYPERS_DICTS[0]['uuid']
    del DETAIL_HYPERS_DICTS[1]['uuid']
    DETAIL_HYPERS_DICTS[0].update({'state': 'up',
                           'status': 'enabled',
                           'service': dict(id=1, host='compute1',
                                        disabled_reason=None)})
    DETAIL_HYPERS_DICTS[1].update({'state': 'up',
                           'status': 'enabled',
                           'service': dict(id=2, host='compute2',
                                        disabled_reason=None)})
    INDEX_HYPER_DICTS = [
        dict(id=1, hypervisor_hostname="hyper1",
             state='up', status='enabled'),
        dict(id=2, hypervisor_hostname="hyper2",
             state='up', status='enabled')]
    DETAIL_NULL_CPUINFO_DICT = {'': '', None: None}

    def _get_request(self, use_admin_context, url='', version=None):
        return fakes.HTTPRequest.blank(
            url,
            use_admin_context=use_admin_context,
            version=version or self.api_version)

    def _get_hyper_id(self):
        """Helper function to get the proper hypervisor id for a request

        :returns: The first hypervisor's uuid for microversions that expect a
            uuid for the id, otherwise the hypervisor's id primary key
        """
        return (self.TEST_HYPERS_OBJ[0].uuid if self.expect_uuid_for_id
                else self.TEST_HYPERS_OBJ[0].id)

    def setUp(self):
        super(HypervisorsTestV21, self).setUp()

        self.controller = hypervisors_v21.HypervisorsController()
        self.controller.servicegroup_api.service_is_up = mock.MagicMock(
            return_value=True)

        host_api = self.controller.host_api
        host_api.compute_node_get_all = mock.MagicMock(
            side_effect=fake_compute_node_get_all)
        host_api.service_get_by_compute_host = mock.MagicMock(
            side_effect=fake_service_get_by_compute_host)
        host_api.compute_node_search_by_hypervisor = mock.MagicMock(
            side_effect=fake_compute_node_search_by_hypervisor)
        host_api.compute_node_get = mock.MagicMock(
            side_effect=fake_compute_node_get)

        self.stub_out('nova.db.main.api.compute_node_statistics',
                      fake_compute_node_statistics)

    def test_view_hypervisor_nodetail_noservers(self):
        req = self._get_request(True)
        result = self.controller._view_hypervisor(
            self.TEST_HYPERS_OBJ[0], self.TEST_SERVICES[0], False, req)

        self.assertEqual(self.INDEX_HYPER_DICTS[0], result)

    def test_view_hypervisor_detail_noservers(self):
        req = self._get_request(True)
        result = self.controller._view_hypervisor(
            self.TEST_HYPERS_OBJ[0], self.TEST_SERVICES[0], True, req)

        self.assertEqual(self.DETAIL_HYPERS_DICTS[0], result)

    def test_view_hypervisor_nodetail_service_down(self):
        self.controller.servicegroup_api.service_is_up.return_value = False

        expected_dict = copy.deepcopy(self.INDEX_HYPER_DICTS[0])
        expected_dict['state'] = 'down'

        req = self._get_request(True)
        result = self.controller._view_hypervisor(
            self.TEST_HYPERS_OBJ[0], self.TEST_SERVICES[0], False, req)

        self.assertEqual(expected_dict, result)

    def test_view_hypervisor_detail_service_down(self):
        self.controller.servicegroup_api.service_is_up.return_value = False

        expected_dict = copy.deepcopy(self.DETAIL_HYPERS_DICTS[0])
        expected_dict['state'] = 'down'

        req = self._get_request(True)
        result = self.controller._view_hypervisor(
            self.TEST_HYPERS_OBJ[0], self.TEST_SERVICES[0], True, req)

        self.assertEqual(expected_dict, result)

    def test_view_hypervisor_nodetail_service_disabled(self):
        service = copy.deepcopy(TEST_SERVICES[0])
        service.disabled = True

        req = self._get_request(True)
        result = self.controller._view_hypervisor(
            self.TEST_HYPERS_OBJ[0], service, False, req)

        self.assertEqual('disabled', result['status'])

    def test_view_hypervisor_detail_service_disabled(self):
        service = copy.deepcopy(TEST_SERVICES[0])
        service.disabled = True

        req = self._get_request(True)
        result = self.controller._view_hypervisor(
            self.TEST_HYPERS_OBJ[0], service, True, req)

        self.assertEqual('disabled', result['status'])

    def test_view_hypervisor_servers(self):
        req = self._get_request(True)
        result = self.controller._view_hypervisor(self.TEST_HYPERS_OBJ[0],
                                                  self.TEST_SERVICES[0],
                                                  False, req,
                                                  self.TEST_SERVERS)
        expected_dict = copy.deepcopy(self.INDEX_HYPER_DICTS[0])
        expected_dict.update({'servers': [
                                  dict(name="inst1", uuid=uuids.instance_1),
                                  dict(name="inst2", uuid=uuids.instance_2),
                                  dict(name="inst3", uuid=uuids.instance_3),
                                  dict(name="inst4", uuid=uuids.instance_4)]})

        self.assertEqual(expected_dict, result)

    def _test_view_hypervisor_detail_cpuinfo_null(self, cpu_info):
        req = self._get_request(True)

        test_hypervisor_obj = copy.deepcopy(self.TEST_HYPERS_OBJ[0])
        test_hypervisor_obj.cpu_info = cpu_info
        result = self.controller._view_hypervisor(test_hypervisor_obj,
                                                  self.TEST_SERVICES[0],
                                                  True, req)

        expected_dict = copy.deepcopy(self.DETAIL_HYPERS_DICTS[0])
        expected_dict.update({'cpu_info':
                              self.DETAIL_NULL_CPUINFO_DICT[cpu_info]})
        self.assertEqual(result, expected_dict)

    def test_view_hypervisor_detail_cpuinfo_empty_string(self):
        self._test_view_hypervisor_detail_cpuinfo_null('')

    def test_view_hypervisor_detail_cpuinfo_none(self):
        self._test_view_hypervisor_detail_cpuinfo_null(None)

    def test_index(self):
        req = self._get_request(True)
        result = self.controller.index(req)

        self.assertEqual(dict(hypervisors=self.INDEX_HYPER_DICTS), result)

    def test_index_compute_host_not_found(self):
        """Tests that if a service is deleted but the compute node is not we
        don't fail when listing hypervisors.
        """

        # two computes, a matching service only exists for the first one
        compute_nodes = objects.ComputeNodeList(objects=[
            objects.ComputeNode(**TEST_HYPERS[0]),
            objects.ComputeNode(**TEST_HYPERS[1])
        ])

        def fake_service_get_by_compute_host(context, host):
            if host == TEST_HYPERS[0]['host']:
                return TEST_SERVICES[0]
            raise exception.ComputeHostNotFound(host=host)

        @mock.patch.object(self.controller.host_api, 'compute_node_get_all',
                           return_value=compute_nodes)
        @mock.patch.object(self.controller.host_api,
                           'service_get_by_compute_host',
                           fake_service_get_by_compute_host)
        def _test(self, compute_node_get_all):
            req = self._get_request(True)
            result = self.controller.index(req)
            self.assertEqual(1, len(result['hypervisors']))
            expected = {
                'id': compute_nodes[0].uuid if self.expect_uuid_for_id
                                            else compute_nodes[0].id,
                'hypervisor_hostname': compute_nodes[0].hypervisor_hostname,
                'state': 'up',
                'status': 'enabled',
            }
            self.assertDictEqual(expected, result['hypervisors'][0])

        _test(self)

    def test_index_compute_host_not_mapped(self):
        """Tests that we don't fail index if a host is not mapped."""

        # two computes, a matching service only exists for the first one
        compute_nodes = objects.ComputeNodeList(objects=[
            objects.ComputeNode(**TEST_HYPERS[0]),
            objects.ComputeNode(**TEST_HYPERS[1])
        ])

        def fake_service_get_by_compute_host(context, host):
            if host == TEST_HYPERS[0]['host']:
                return TEST_SERVICES[0]
            raise exception.HostMappingNotFound(name=host)

        @mock.patch.object(self.controller.host_api, 'compute_node_get_all',
                           return_value=compute_nodes)
        @mock.patch.object(self.controller.host_api,
                           'service_get_by_compute_host',
                           fake_service_get_by_compute_host)
        def _test(self, compute_node_get_all):
            req = self._get_request(True)
            result = self.controller.index(req)
            self.assertEqual(1, len(result['hypervisors']))
            expected = {
                'id': compute_nodes[0].uuid if self.expect_uuid_for_id
                                            else compute_nodes[0].id,
                'hypervisor_hostname': compute_nodes[0].hypervisor_hostname,
                'state': 'up',
                'status': 'enabled',
            }
            self.assertDictEqual(expected, result['hypervisors'][0])

        _test(self)

    def test_detail(self):
        req = self._get_request(True)
        result = self.controller.detail(req)

        self.assertEqual(dict(hypervisors=self.DETAIL_HYPERS_DICTS), result)

    def test_detail_compute_host_not_found(self):
        """Tests that if a service is deleted but the compute node is not we
        don't fail when listing hypervisors.
        """

        # two computes, a matching service only exists for the first one
        compute_nodes = objects.ComputeNodeList(objects=[
            objects.ComputeNode(**TEST_HYPERS[0]),
            objects.ComputeNode(**TEST_HYPERS[1])
        ])

        def fake_service_get_by_compute_host(context, host):
            if host == TEST_HYPERS[0]['host']:
                return TEST_SERVICES[0]
            raise exception.ComputeHostNotFound(host=host)

        @mock.patch.object(self.controller.host_api, 'compute_node_get_all',
                           return_value=compute_nodes)
        @mock.patch.object(self.controller.host_api,
                           'service_get_by_compute_host',
                           fake_service_get_by_compute_host)
        def _test(self, compute_node_get_all):
            req = self._get_request(True)
            result = self.controller.detail(req)
            self.assertEqual(1, len(result['hypervisors']))
            expected = {
                'id': compute_nodes[0].id,
                'hypervisor_hostname': compute_nodes[0].hypervisor_hostname,
                'state': 'up',
                'status': 'enabled',
            }
            # we don't care about all of the details, just make sure we get
            # the subset we care about and there are more keys than what index
            # would return
            hypervisor = result['hypervisors'][0]
            self.assertTrue(
                set(expected.keys()).issubset(set(hypervisor.keys())))
            self.assertGreater(len(hypervisor.keys()), len(expected.keys()))
            self.assertEqual(compute_nodes[0].hypervisor_hostname,
                             hypervisor['hypervisor_hostname'])

        _test(self)

    def test_detail_compute_host_not_mapped(self):
        """Tests that if a service is deleted but the compute node is not we
        don't fail when listing hypervisors.
        """

        # two computes, a matching service only exists for the first one
        compute_nodes = objects.ComputeNodeList(objects=[
            objects.ComputeNode(**TEST_HYPERS[0]),
            objects.ComputeNode(**TEST_HYPERS[1])
        ])

        def fake_service_get_by_compute_host(context, host):
            if host == TEST_HYPERS[0]['host']:
                return TEST_SERVICES[0]
            raise exception.HostMappingNotFound(name=host)

        @mock.patch.object(self.controller.host_api, 'compute_node_get_all',
                           return_value=compute_nodes)
        @mock.patch.object(self.controller.host_api,
                           'service_get_by_compute_host',
                           fake_service_get_by_compute_host)
        def _test(self, compute_node_get_all):
            req = self._get_request(True)
            result = self.controller.detail(req)
            self.assertEqual(1, len(result['hypervisors']))
            expected = {
                'id': compute_nodes[0].id,
                'hypervisor_hostname': compute_nodes[0].hypervisor_hostname,
                'state': 'up',
                'status': 'enabled',
            }
            # we don't care about all of the details, just make sure we get
            # the subset we care about and there are more keys than what index
            # would return
            hypervisor = result['hypervisors'][0]
            self.assertTrue(
                set(expected.keys()).issubset(set(hypervisor.keys())))
            self.assertGreater(len(hypervisor.keys()), len(expected.keys()))
            self.assertEqual(compute_nodes[0].hypervisor_hostname,
                             hypervisor['hypervisor_hostname'])

        _test(self)

    def test_show(self):
        req = self._get_request(True)
        hyper_id = self._get_hyper_id()
        result = self.controller.show(req, hyper_id)

        self.assertEqual({'hypervisor': self.DETAIL_HYPERS_DICTS[0]}, result)

    def test_show_compute_host_not_mapped(self):
        """Tests that if a service is deleted but the compute node is not we
        don't fail when listing hypervisors.
        """

        @mock.patch.object(self.controller.host_api, 'compute_node_get',
                           return_value=self.TEST_HYPERS_OBJ[0])
        @mock.patch.object(self.controller.host_api,
                           'service_get_by_compute_host')
        def _test(self, mock_service, mock_compute_node_get):
            req = self._get_request(True)
            mock_service.side_effect = exception.HostMappingNotFound(
                name='foo')
            hyper_id = self._get_hyper_id()
            self.assertRaises(exc.HTTPNotFound, self.controller.show,
                              req, hyper_id)
            self.assertTrue(mock_service.called)
            mock_compute_node_get.assert_called_once_with(mock.ANY, hyper_id)
        _test(self)

    def test_show_noid(self):
        req = self._get_request(True)
        hyperid = uuids.hyper3 if self.expect_uuid_for_id else '3'
        self.assertRaises(exc.HTTPNotFound, self.controller.show, req, hyperid)

    def test_show_non_integer_id(self):
        req = self._get_request(True)
        self.assertRaises(exc.HTTPNotFound, self.controller.show, req, 'abc')

    def test_uptime(self):
        with mock.patch.object(
            self.controller.host_api, 'get_host_uptime',
            return_value='fake uptime',
        ) as mock_get_uptime:
            req = self._get_request(True)
            hyper_id = self._get_hyper_id()

            result = self.controller.uptime(req, hyper_id)

            expected_dict = copy.deepcopy(self.INDEX_HYPER_DICTS[0])
            expected_dict.update({'uptime': "fake uptime"})
            self.assertEqual(dict(hypervisor=expected_dict), result)
            self.assertEqual(1, mock_get_uptime.call_count)

    def test_uptime_noid(self):
        req = self._get_request(True)
        hyper_id = uuids.hyper3 if self.expect_uuid_for_id else '3'
        self.assertRaises(exc.HTTPNotFound, self.controller.uptime, req,
                          hyper_id)

    def test_uptime_not_implemented(self):
        with mock.patch.object(
            self.controller.host_api, 'get_host_uptime',
            side_effect=NotImplementedError,
        ) as mock_get_uptime:
            req = self._get_request(True)
            hyper_id = self._get_hyper_id()
            self.assertRaises(
                exc.HTTPNotImplemented,
                self.controller.uptime, req, hyper_id)
            self.assertEqual(1, mock_get_uptime.call_count)

    def test_uptime_host_not_found(self):
        with mock.patch.object(
            self.controller.host_api, 'get_host_uptime',
            side_effect=exception.HostNotFound('foo'),
        ) as mock_get_uptime:
            req = self._get_request(True)
            hyper_id = self._get_hyper_id()
            self.assertRaises(
                exc.HTTPBadRequest,
                self.controller.uptime, req, hyper_id)
            self.assertEqual(1, mock_get_uptime.call_count)

    def test_uptime_non_integer_id(self):
        req = self._get_request(True)
        self.assertRaises(exc.HTTPNotFound, self.controller.uptime, req, 'abc')

    def test_uptime_hypervisor_down(self):
        with mock.patch.object(self.controller.host_api, 'get_host_uptime',
                side_effect=exception.ComputeServiceUnavailable(host='dummy')
                ) as mock_get_uptime:
            req = self._get_request(True)
            hyper_id = self._get_hyper_id()
            self.assertRaises(exc.HTTPBadRequest,
                              self.controller.uptime, req, hyper_id)
            mock_get_uptime.assert_called_once_with(
                mock.ANY, self.TEST_HYPERS_OBJ[0].host)

    def test_uptime_hypervisor_not_mapped_service_get(self):
        @mock.patch.object(self.controller.host_api, 'compute_node_get')
        @mock.patch.object(self.controller.host_api, 'get_host_uptime')
        @mock.patch.object(self.controller.host_api,
                           'service_get_by_compute_host',
                           side_effect=exception.HostMappingNotFound(
                               name='dummy'))
        def _test(mock_get, _, __):
            req = self._get_request(True)
            hyper_id = self._get_hyper_id()
            self.assertRaises(exc.HTTPNotFound,
                              self.controller.uptime, req, hyper_id)
            self.assertTrue(mock_get.called)

        _test()

    def test_uptime_hypervisor_not_mapped(self):
        with mock.patch.object(self.controller.host_api, 'get_host_uptime',
                side_effect=exception.HostMappingNotFound(name='dummy')
                ) as mock_get_uptime:
            req = self._get_request(True)
            hyper_id = self._get_hyper_id()
            self.assertRaises(exc.HTTPNotFound,
                              self.controller.uptime, req, hyper_id)
            mock_get_uptime.assert_called_once_with(
                mock.ANY, self.TEST_HYPERS_OBJ[0].host)

    def test_search(self):
        req = self._get_request(True)
        result = self.controller.search(req, 'hyper')

        self.assertEqual(dict(hypervisors=self.INDEX_HYPER_DICTS), result)

    def test_search_non_exist(self):
        with mock.patch.object(self.controller.host_api,
                               'compute_node_search_by_hypervisor',
                               return_value=[]) as mock_node_search:
            req = self._get_request(True)
            self.assertRaises(exc.HTTPNotFound, self.controller.search,
                              req, 'a')
            self.assertEqual(1, mock_node_search.call_count)

    def test_search_unmapped(self):

        @mock.patch.object(self.controller.host_api,
                           'compute_node_search_by_hypervisor')
        @mock.patch.object(self.controller.host_api,
                           'service_get_by_compute_host')
        def _test(mock_service, mock_search):
            mock_search.return_value = [mock.MagicMock()]
            mock_service.side_effect = exception.HostMappingNotFound(
                name='foo')
            req = self._get_request(True)
            self.assertRaises(exc.HTTPNotFound, self.controller.search,
                              req, 'a')
            self.assertTrue(mock_service.called)

        _test()

    @mock.patch.object(objects.InstanceList, 'get_by_host',
                       side_effect=fake_instance_get_all_by_host)
    def test_servers(self, mock_get):
        req = self._get_request(True)
        result = self.controller.servers(req, 'hyper')

        expected_dict = copy.deepcopy(self.INDEX_HYPER_DICTS)
        expected_dict[0].update({'servers': [
                                     dict(uuid=uuids.instance_1),
                                     dict(uuid=uuids.instance_3)]})
        expected_dict[1].update({'servers': [
                                     dict(uuid=uuids.instance_2),
                                     dict(uuid=uuids.instance_4)]})

        for output in result['hypervisors']:
            servers = output['servers']
            for server in servers:
                del server['name']
        self.assertEqual(dict(hypervisors=expected_dict), result)

    def test_servers_not_mapped(self):
        req = self._get_request(True)
        with mock.patch.object(
            self.controller.host_api, 'instance_get_all_by_host',
            side_effect=exception.HostMappingNotFound(name='something'),
        ):
            self.assertRaises(
                exc.HTTPNotFound,
                self.controller.servers, req, 'hyper')

    def test_servers_compute_host_not_found(self):
        req = self._get_request(True)

        with test.nested(
            mock.patch.object(
                self.controller.host_api, 'instance_get_all_by_host',
                side_effect=fake_instance_get_all_by_host,
            ),
            mock.patch.object(
                self.controller.host_api, 'service_get_by_compute_host',
                side_effect=exception.ComputeHostNotFound(host='foo'),
            ),
        ):
            # The result should be empty since every attempt to fetch the
            # service for a hypervisor "failed"
            result = self.controller.servers(req, 'hyper')
            self.assertEqual({'hypervisors': []}, result)

    def test_servers_non_id(self):
        with mock.patch.object(self.controller.host_api,
                               'compute_node_search_by_hypervisor',
                               return_value=[]) as mock_node_search:
            req = self._get_request(True)
            self.assertRaises(exc.HTTPNotFound,
                              self.controller.servers,
                              req, '115')
            self.assertEqual(1, mock_node_search.call_count)

    def test_servers_with_non_integer_hypervisor_id(self):
        with mock.patch.object(self.controller.host_api,
                               'compute_node_search_by_hypervisor',
                               return_value=[]) as mock_node_search:

            req = self._get_request(True)
            self.assertRaises(exc.HTTPNotFound,
                              self.controller.servers, req, 'abc')
            self.assertEqual(1, mock_node_search.call_count)

    def test_servers_with_no_servers(self):
        with mock.patch.object(self.controller.host_api,
                               'instance_get_all_by_host',
                               return_value=[]) as mock_inst_get_all:
            req = self._get_request(True)
            result = self.controller.servers(req, self.TEST_HYPERS_OBJ[0].id)
            self.assertEqual(dict(hypervisors=self.INDEX_HYPER_DICTS), result)
            self.assertTrue(mock_inst_get_all.called)

    def test_statistics(self):
        req = self._get_request(True)
        result = self.controller.statistics(req)

        self.assertEqual(dict(hypervisor_statistics=dict(
                    count=2,
                    vcpus=8,
                    memory_mb=20 * 1024,
                    local_gb=500,
                    vcpus_used=4,
                    memory_mb_used=10 * 1024,
                    local_gb_used=250,
                    free_ram_mb=10 * 1024,
                    free_disk_gb=250,
                    current_workload=4,
                    running_vms=4,
                    disk_available_least=200)), result)


class HypervisorsTestV228(HypervisorsTestV21):
    api_version = '2.28'

    DETAIL_HYPERS_DICTS = copy.deepcopy(HypervisorsTestV21.DETAIL_HYPERS_DICTS)
    DETAIL_HYPERS_DICTS[0]['cpu_info'] = jsonutils.loads(CPU_INFO)
    DETAIL_HYPERS_DICTS[1]['cpu_info'] = jsonutils.loads(CPU_INFO)
    DETAIL_NULL_CPUINFO_DICT = {'': {}, None: {}}


class HypervisorsTestV233(HypervisorsTestV228):
    api_version = '2.33'

    def test_index_pagination(self):
        req = self._get_request(True,
                                '/v2/1234/os-hypervisors?limit=1&marker=1')
        result = self.controller.index(req)
        expected = {
            'hypervisors': [
                {'hypervisor_hostname': 'hyper2',
                 'id': 2,
                 'state': 'up',
                 'status': 'enabled'}
            ],
            'hypervisors_links': [
                {'href': 'http://localhost/v2/os-hypervisors?limit=1&marker=2',
                 'rel': 'next'}
            ]
        }

        self.assertEqual(expected, result)

    def test_index_pagination_with_invalid_marker(self):
        req = self._get_request(True,
                                '/v2/1234/os-hypervisors?marker=99999')
        self.assertRaises(exc.HTTPBadRequest,
                          self.controller.index, req)

    def test_index_pagination_with_invalid_non_int_limit(self):
        req = self._get_request(True,
                                '/v2/1234/os-hypervisors?limit=-9')
        self.assertRaises(exception.ValidationError,
                          self.controller.index, req)

    def test_index_pagination_with_invalid_string_limit(self):
        req = self._get_request(True,
                                '/v2/1234/os-hypervisors?limit=abc')
        self.assertRaises(exception.ValidationError,
                          self.controller.index, req)

    def test_index_duplicate_query_parameters_with_invalid_string_limit(self):
        req = self._get_request(
            True,
            '/v2/1234/os-hypervisors/?limit=1&limit=abc')
        self.assertRaises(exception.ValidationError,
                          self.controller.index, req)

    def test_index_duplicate_query_parameters_validation(self):
        expected = [{
           'hypervisor_hostname': 'hyper2',
           'id': 2,
           'state': 'up',
           'status': 'enabled'}
        ]
        params = {
            'limit': 1,
            'marker': 1,
        }

        for param, value in params.items():
            req = self._get_request(
                use_admin_context=True,
                url='/os-hypervisors?marker=1&%s=%s&%s=%s' %
                    (param, value, param, value))
            result = self.controller.index(req)
            self.assertEqual(expected, result['hypervisors'])

    def test_index_pagination_with_additional_filter(self):
        expected = {
            'hypervisors': [
                {'hypervisor_hostname': 'hyper2',
                 'id': 2,
                 'state': 'up',
                 'status': 'enabled'}
            ],
            'hypervisors_links': [
                {'href': 'http://localhost/v2/os-hypervisors?limit=1&marker=2',
                 'rel': 'next'}
            ]
        }
        req = self._get_request(
            True, '/v2/1234/os-hypervisors?limit=1&marker=1&additional=3')
        result = self.controller.index(req)
        self.assertEqual(expected, result)

    def test_detail_pagination(self):
        req = self._get_request(
            True, '/v2/1234/os-hypervisors/detail?limit=1&marker=1')
        result = self.controller.detail(req)
        link = 'http://localhost/v2/os-hypervisors/detail?limit=1&marker=2'
        expected = {
            'hypervisors': [
                {'cpu_info': {'arch': 'x86_64',
                              'features': [],
                              'model': '',
                              'topology': {'cores': 1,
                                           'sockets': 1,
                                           'threads': 1},
                              'vendor': 'fake'},
                'current_workload': 2,
                'disk_available_least': 100,
                'free_disk_gb': 125,
                'free_ram_mb': 5120,
                'host_ip': netaddr.IPAddress('2.2.2.2'),
                'hypervisor_hostname': 'hyper2',
                'hypervisor_type': 'xen',
                'hypervisor_version': 3,
                'id': 2,
                'local_gb': 250,
                'local_gb_used': 125,
                'memory_mb': 10240,
                'memory_mb_used': 5120,
                'running_vms': 2,
                'service': {'disabled_reason': None,
                            'host': 'compute2',
                            'id': 2},
                'state': 'up',
                'status': 'enabled',
                'vcpus': 4,
                'vcpus_used': 2}
            ],
            'hypervisors_links': [{'href': link, 'rel': 'next'}]
        }

        self.assertEqual(expected, result)

    def test_detail_pagination_with_invalid_marker(self):
        req = self._get_request(True,
                                '/v2/1234/os-hypervisors/detail?marker=99999')
        self.assertRaises(exc.HTTPBadRequest,
                          self.controller.detail, req)

    def test_detail_pagination_with_invalid_string_limit(self):
        req = self._get_request(True,
                                '/v2/1234/os-hypervisors/detail?limit=abc')
        self.assertRaises(exception.ValidationError,
                          self.controller.detail, req)

    def test_detail_duplicate_query_parameters_with_invalid_string_limit(self):
        req = self._get_request(
            True,
            '/v2/1234/os-hypervisors/detail?limit=1&limit=abc')
        self.assertRaises(exception.ValidationError,
                          self.controller.detail, req)

    def test_detail_duplicate_query_parameters_validation(self):
        expected = [
                {'cpu_info': {'arch': 'x86_64',
                              'features': [],
                              'model': '',
                              'topology': {'cores': 1,
                                           'sockets': 1,
                                           'threads': 1},
                              'vendor': 'fake'},
                'current_workload': 2,
                'disk_available_least': 100,
                'free_disk_gb': 125,
                'free_ram_mb': 5120,
                'host_ip': netaddr.IPAddress('2.2.2.2'),
                'hypervisor_hostname': 'hyper2',
                'hypervisor_type': 'xen',
                'hypervisor_version': 3,
                'id': 2,
                'local_gb': 250,
                'local_gb_used': 125,
                'memory_mb': 10240,
                'memory_mb_used': 5120,
                'running_vms': 2,
                'service': {'disabled_reason': None,
                            'host': 'compute2',
                            'id': 2},
                'state': 'up',
                'status': 'enabled',
                'vcpus': 4,
                'vcpus_used': 2}
        ]

        params = {
            'limit': 1,
            'marker': 1,
        }

        for param, value in params.items():
            req = self._get_request(
                use_admin_context=True,
                url='/os-hypervisors/detail?marker=1&%s=%s&%s=%s' %
                    (param, value, param, value))
            result = self.controller.detail(req)
            self.assertEqual(expected, result['hypervisors'])

    def test_detail_pagination_with_additional_filter(self):
        link = 'http://localhost/v2/os-hypervisors/detail?limit=1&marker=2'
        expected = {
            'hypervisors': [
                {'cpu_info': {'arch': 'x86_64',
                              'features': [],
                              'model': '',
                              'topology': {'cores': 1,
                                           'sockets': 1,
                                           'threads': 1},
                              'vendor': 'fake'},
                'current_workload': 2,
                'disk_available_least': 100,
                'free_disk_gb': 125,
                'free_ram_mb': 5120,
                'host_ip': netaddr.IPAddress('2.2.2.2'),
                'hypervisor_hostname': 'hyper2',
                'hypervisor_type': 'xen',
                'hypervisor_version': 3,
                'id': 2,
                'local_gb': 250,
                'local_gb_used': 125,
                'memory_mb': 10240,
                'memory_mb_used': 5120,
                'running_vms': 2,
                'service': {'disabled_reason': None,
                            'host': 'compute2',
                            'id': 2},
                'state': 'up',
                'status': 'enabled',
                'vcpus': 4,
                'vcpus_used': 2}
            ],
            'hypervisors_links': [{
                'href': link,
                'rel': 'next'}]
        }
        req = self._get_request(
            True, '/v2/1234/os-hypervisors/detail?limit=1&marker=1&unknown=2')
        result = self.controller.detail(req)
        self.assertEqual(expected, result)


class HypervisorsTestV252(HypervisorsTestV233):
    """This is a boundary test to make sure 2.52 works like 2.33."""
    api_version = '2.52'


class HypervisorsTestV253(HypervisorsTestV252):
    api_version = hypervisors_v21.UUID_FOR_ID_MIN_VERSION
    expect_uuid_for_id = True

    # This is an expected response for index().
    INDEX_HYPER_DICTS = [
        dict(id=uuids.hyper1, hypervisor_hostname="hyper1",
             state='up', status='enabled'),
        dict(id=uuids.hyper2, hypervisor_hostname="hyper2",
             state='up', status='enabled')]

    def setUp(self):
        super(HypervisorsTestV253, self).setUp()
        # This is an expected response for detail().
        for index, detail_hyper_dict in enumerate(self.DETAIL_HYPERS_DICTS):
            detail_hyper_dict['id'] = TEST_HYPERS[index]['uuid']
            detail_hyper_dict['service']['id'] = TEST_SERVICES[index].uuid

    def test_servers(self):
        """Asserts that calling the servers route after 2.52 fails."""
        self.assertRaises(exception.VersionNotFoundForAPIMethod,
                          self.controller.servers,
                          self._get_request(True), 'hyper')

    def test_servers_not_mapped(self):
        # the separate 'servers' API has been removed, so skip this test
        pass

    def test_servers_compute_host_not_found(self):
        # the separate 'servers' API has been removed, so skip this test
        pass

    def test_servers_non_id(self):
        # the separate 'servers' API has been removed, so skip this test
        pass

    def test_servers_with_non_integer_hypervisor_id(self):
        # the separate 'servers' API has been removed, so skip this test
        pass

    def test_servers_with_no_servers(self):
        # the separate 'servers' API has been removed, so skip this test
        pass

    def test_index_with_no_servers(self):
        """Tests GET /os-hypervisors?with_servers=1 when there are no
        instances on the given host.
        """
        with mock.patch.object(self.controller.host_api,
                               'instance_get_all_by_host',
                               return_value=[]) as mock_inst_get_all:
            req = self._get_request(use_admin_context=True,
                                    url='/os-hypervisors?with_servers=1')
            result = self.controller.index(req)
        self.assertEqual(dict(hypervisors=self.INDEX_HYPER_DICTS), result)
        # instance_get_all_by_host is called for each hypervisor
        self.assertEqual(2, mock_inst_get_all.call_count)
        mock_inst_get_all.assert_has_calls((
            mock.call(req.environ['nova.context'], TEST_HYPERS_OBJ[0].host),
            mock.call(req.environ['nova.context'], TEST_HYPERS_OBJ[1].host)))

    def test_index_with_servers_not_mapped(self):
        """Tests that instance_get_all_by_host fails with HostMappingNotFound.
        """
        req = self._get_request(use_admin_context=True,
                                url='/os-hypervisors?with_servers=1')
        with mock.patch.object(
                self.controller.host_api, 'instance_get_all_by_host',
                side_effect=exception.HostMappingNotFound(name='something')):
            result = self.controller.index(req)
            self.assertEqual(dict(hypervisors=[]), result)

    def test_index_with_servers_compute_host_not_found(self):
        req = self._get_request(
            use_admin_context=True,
            url='/os-hypervisors?with_servers=1')

        with test.nested(
            mock.patch.object(
                self.controller.host_api, 'instance_get_all_by_host',
                side_effect=fake_instance_get_all_by_host,
            ),
            mock.patch.object(
                self.controller.host_api, 'service_get_by_compute_host',
                side_effect=exception.ComputeHostNotFound(host='foo'),
            ),
        ):
            # The result should be empty since every attempt to fetch the
            # service for a hypervisor "failed"
            result = self.controller.index(req)
            self.assertEqual({'hypervisors': []}, result)

    def test_index_with_servers(self):
        """Tests GET /os-hypervisors?with_servers=True"""
        instances = [
            objects.InstanceList(objects=[objects.Instance(
                id=1, uuid=uuids.hyper1_instance1)]),
            objects.InstanceList(objects=[objects.Instance(
                id=2, uuid=uuids.hyper2_instance1)])]
        with mock.patch.object(self.controller.host_api,
                               'instance_get_all_by_host',
                               side_effect=instances) as mock_inst_get_all:
            req = self._get_request(use_admin_context=True,
                                    url='/os-hypervisors?with_servers=True')
            result = self.controller.index(req)
        index_with_servers = copy.deepcopy(self.INDEX_HYPER_DICTS)
        index_with_servers[0]['servers'] = [
            {'name': 'instance-00000001', 'uuid': uuids.hyper1_instance1}]
        index_with_servers[1]['servers'] = [
            {'name': 'instance-00000002', 'uuid': uuids.hyper2_instance1}]
        self.assertEqual(dict(hypervisors=index_with_servers), result)
        # instance_get_all_by_host is called for each hypervisor
        self.assertEqual(2, mock_inst_get_all.call_count)
        mock_inst_get_all.assert_has_calls((
            mock.call(req.environ['nova.context'], TEST_HYPERS_OBJ[0].host),
            mock.call(req.environ['nova.context'], TEST_HYPERS_OBJ[1].host)))

    def test_index_with_servers_invalid_parameter(self):
        """Tests using an invalid with_servers query parameter."""
        req = self._get_request(use_admin_context=True,
                                url='/os-hypervisors?with_servers=invalid')
        self.assertRaises(
            exception.ValidationError, self.controller.index, req)

    def test_index_with_hostname_pattern_and_paging_parameters(self):
        """This is a negative test to validate that trying to list hypervisors
        with a hostname pattern and paging parameters results in a 400 error.
        """
        req = self._get_request(
            use_admin_context=True,
            url='/os-hypervisors?hypervisor_hostname_pattern=foo&'
                'limit=1&marker=%s' % uuids.marker)
        ex = self.assertRaises(exc.HTTPBadRequest, self.controller.index, req)
        self.assertIn('Paging over hypervisors with the '
                      'hypervisor_hostname_pattern query parameter is not '
                      'supported.', str(ex))

    def test_index_with_hostname_pattern_no_match(self):
        """This is a poorly named test, it's really checking the 404 case where
        there is no match for the hostname pattern.
        """
        req = self._get_request(
            use_admin_context=True,
            url='/os-hypervisors?with_servers=yes&'
                'hypervisor_hostname_pattern=shenzhen')
        with mock.patch.object(self.controller.host_api,
                               'compute_node_search_by_hypervisor',
                               return_value=objects.ComputeNodeList()) as s:
            self.assertRaises(exc.HTTPNotFound, self.controller.index, req)
            s.assert_called_once_with(req.environ['nova.context'], 'shenzhen')

    def test_detail_with_hostname_pattern(self):
        """Test listing hypervisors with details and using the
        hypervisor_hostname_pattern query string.
        """
        req = self._get_request(
            use_admin_context=True,
            url='/os-hypervisors?hypervisor_hostname_pattern=shenzhen')
        with mock.patch.object(
            self.controller.host_api,
            'compute_node_search_by_hypervisor',
            return_value=objects.ComputeNodeList(objects=[TEST_HYPERS_OBJ[0]])
        ) as s:
            result = self.controller.detail(req)
            s.assert_called_once_with(req.environ['nova.context'], 'shenzhen')

        expected = {'hypervisors': [self.DETAIL_HYPERS_DICTS[0]]}

        # There are no links when using the hypervisor_hostname_pattern
        # query string since we can't page using a pattern matcher.
        self.assertNotIn('hypervisors_links', result)
        self.assertDictEqual(expected, result)

    def test_detail_invalid_hostname_pattern_parameter(self):
        """Tests passing an invalid hypervisor_hostname_pattern query
        parameter.
        """
        req = self._get_request(
            use_admin_context=True,
            url='/os-hypervisors?hypervisor_hostname_pattern=invalid~host')
        self.assertRaises(
            exception.ValidationError, self.controller.detail, req)

    def test_search(self):
        """Asserts that calling the search route after 2.52 fails."""
        self.assertRaises(exception.VersionNotFoundForAPIMethod,
                          self.controller.search,
                          self._get_request(True), 'hyper')

    def test_search_non_exist(self):
        """This is a duplicate of test_servers_with_non_integer_hypervisor_id.
        """
        pass

    def test_search_unmapped(self):
        """This is already tested with test_index_compute_host_not_mapped."""
        pass

    def test_show_non_integer_id(self):
        """There is no reason to test this for 2.53 since 2.53 requires a
        non-integer id (requires a uuid).
        """
        pass

    def test_show_integer_id(self):
        """Tests that we get a 400 if passed a hypervisor integer id to show().
        """
        req = self._get_request(True)
        ex = self.assertRaises(exc.HTTPBadRequest,
                               self.controller.show, req, '1')
        self.assertIn('Invalid uuid 1', str(ex))

    def test_show_with_servers_invalid_parameter(self):
        """Tests passing an invalid value for the with_servers query parameter
        to the show() method to make sure the query parameter is validated.
        """
        hyper_id = self._get_hyper_id()
        req = self._get_request(
            use_admin_context=True,
            url='/os-hypervisors/%s?with_servers=invalid' % hyper_id)
        ex = self.assertRaises(
            exception.ValidationError, self.controller.show, req, hyper_id)
        self.assertIn('with_servers', str(ex))

    def test_show_with_servers_host_mapping_not_found(self):
        """Tests that a 404 is returned if instance_get_all_by_host raises
        HostMappingNotFound.
        """
        hyper_id = self._get_hyper_id()
        req = self._get_request(
            use_admin_context=True,
            url='/os-hypervisors/%s?with_servers=true' % hyper_id)
        with mock.patch.object(
                self.controller.host_api, 'instance_get_all_by_host',
                side_effect=exception.HostMappingNotFound(name=hyper_id)):
            self.assertRaises(exc.HTTPNotFound, self.controller.show,
                              req, hyper_id)

    def test_show_with_servers(self):
        """Tests the show() result when servers are included in the output."""
        instances = objects.InstanceList(objects=[objects.Instance(
            id=1, uuid=uuids.hyper1_instance1)])
        hyper_id = self._get_hyper_id()
        req = self._get_request(
            use_admin_context=True,
            url='/os-hypervisors/%s?with_servers=on' % hyper_id)
        with mock.patch.object(self.controller.host_api,
                               'instance_get_all_by_host',
                               return_value=instances) as mock_inst_get_all:
            result = self.controller.show(req, hyper_id)
        show_with_servers = copy.deepcopy(self.DETAIL_HYPERS_DICTS[0])
        show_with_servers['servers'] = [
            {'name': 'instance-00000001', 'uuid': uuids.hyper1_instance1}]
        self.assertDictEqual(dict(hypervisor=show_with_servers), result)
        # instance_get_all_by_host is called
        mock_inst_get_all.assert_called_once_with(
            req.environ['nova.context'], TEST_HYPERS_OBJ[0].host)

    def test_show_duplicate_query_parameters_validation(self):
        """Tests that the show query parameter schema enforces only a single
        entry for any query parameter.
        """
        req = self._get_request(
            use_admin_context=True,
            url='/os-hypervisors/%s?with_servers=1&with_servers=1' %
                uuids.hyper1)
        self.assertRaises(exception.ValidationError,
                          self.controller.show, req, uuids.hyper1)

    def test_uptime_non_integer_id(self):
        """There is no reason to test this for 2.53 since 2.53 requires a
        non-integer id (requires a uuid).
        """
        pass

    def test_uptime_integer_id(self):
        """Tests that we get a 400 if passed a hypervisor integer id to
        uptime().
        """
        req = self._get_request(True)
        ex = self.assertRaises(exc.HTTPBadRequest,
                               self.controller.uptime, req, '1')
        self.assertIn('Invalid uuid 1', str(ex))

    def test_detail_pagination(self):
        """Tests details paging with uuid markers."""
        req = self._get_request(
            use_admin_context=True,
            url='/os-hypervisors/detail?limit=1&marker=%s' %
                TEST_HYPERS_OBJ[0].uuid)
        result = self.controller.detail(req)
        link = ('http://localhost/v2/os-hypervisors/detail?limit=1&marker=%s' %
                TEST_HYPERS_OBJ[1].uuid)
        expected = {
            'hypervisors': [self.DETAIL_HYPERS_DICTS[1]],
            'hypervisors_links': [{'href': link, 'rel': 'next'}]
        }
        self.assertEqual(expected, result)

    def test_detail_pagination_with_invalid_marker(self):
        """Tests detail paging with an invalid marker (not found)."""
        req = self._get_request(
            use_admin_context=True,
            url='/os-hypervisors/detail?marker=%s' % uuids.invalid_marker)
        self.assertRaises(exc.HTTPBadRequest,
                          self.controller.detail, req)

    def test_detail_pagination_with_additional_filter(self):
        req = self._get_request(
            True, '/v2/1234/os-hypervisors/detail?limit=1&marker=9&unknown=2')
        self.assertRaises(exception.ValidationError,
                          self.controller.detail, req)

    def test_detail_duplicate_query_parameters_validation(self):
        """Tests that the list Detail query parameter schema enforces only a
        single entry for any query parameter.
        """
        params = {
            'limit': 1,
            'marker': uuids.marker,
            'hypervisor_hostname_pattern': 'foo',
            'with_servers': 'true'
        }
        for param, value in params.items():
            req = self._get_request(
                use_admin_context=True,
                url='/os-hypervisors/detail?%s=%s&%s=%s' %
                    (param, value, param, value))
            self.assertRaises(exception.ValidationError,
                              self.controller.detail, req)

    def test_index_pagination(self):
        """Tests index paging with uuid markers."""
        req = self._get_request(
            use_admin_context=True,
            url='/os-hypervisors?limit=1&marker=%s' %
                TEST_HYPERS_OBJ[0].uuid)
        result = self.controller.index(req)
        link = ('http://localhost/v2/os-hypervisors?limit=1&marker=%s' %
                TEST_HYPERS_OBJ[1].uuid)
        expected = {
            'hypervisors': [{
                'hypervisor_hostname': 'hyper2',
                'id': TEST_HYPERS_OBJ[1].uuid,
                'state': 'up',
                'status': 'enabled'
            }],
            'hypervisors_links': [{'href': link, 'rel': 'next'}]
        }
        self.assertEqual(expected, result)

    def test_index_pagination_with_invalid_marker(self):
        """Tests index paging with an invalid marker (not found)."""
        req = self._get_request(
            use_admin_context=True,
            url='/os-hypervisors?marker=%s' % uuids.invalid_marker)
        self.assertRaises(exc.HTTPBadRequest,
                          self.controller.index, req)

    def test_index_pagination_with_additional_filter(self):
        req = self._get_request(
            True, '/v2/1234/os-hypervisors/?limit=1&marker=9&unknown=2')
        self.assertRaises(exception.ValidationError,
                          self.controller.index, req)

    def test_index_duplicate_query_parameters_validation(self):
        """Tests that the list query parameter schema enforces only a single
        entry for any query parameter.
        """
        params = {
            'limit': 1,
            'marker': uuids.marker,
            'hypervisor_hostname_pattern': 'foo',
            'with_servers': 'true'
        }
        for param, value in params.items():
            req = self._get_request(
                use_admin_context=True,
                url='/os-hypervisors?%s=%s&%s=%s' %
                    (param, value, param, value))
            self.assertRaises(exception.ValidationError,
                              self.controller.index, req)


class HypervisorsTestV275(HypervisorsTestV253):
    api_version = '2.75'

    def _test_servers_with_no_servers(self, func, version=None, **kwargs):
        """Tests GET APIs return 'servers' field in response even
           no servers on hypervisors.
        """
        with mock.patch.object(
            self.controller.host_api,
            'instance_get_all_by_host',
            return_value=[],
        ):
            req = self._get_request(
                url='/os-hypervisors?with_servers=1',
                use_admin_context=True,
                version=version)
            result = func(req, **kwargs)
        return result

    def test_index_with_no_servers(self):
        result = self._test_servers_with_no_servers(self.controller.index)
        for hyper in result['hypervisors']:
            self.assertEqual(0, len(hyper['servers']))

    def test_index_with_no_servers_old_version(self):
        result = self._test_servers_with_no_servers(
            self.controller.index, version='2.74')
        for hyper in result['hypervisors']:
            self.assertNotIn('servers', hyper)

    def test_detail_with_no_servers(self):
        result = self._test_servers_with_no_servers(self.controller.detail)
        for hyper in result['hypervisors']:
            self.assertEqual(0, len(hyper['servers']))

    def test_detail_with_no_servers_old_version(self):
        result = self._test_servers_with_no_servers(
            self.controller.detail, version='2.74')
        for hyper in result['hypervisors']:
            self.assertNotIn('servers', hyper)

    def test_show_with_no_servers(self):
        result = self._test_servers_with_no_servers(
            self.controller.show, id=uuids.hyper1)
        self.assertEqual(0, len(result['hypervisor']['servers']))

    def test_show_with_no_servers_old_version(self):
        result = self._test_servers_with_no_servers(
            self.controller.show, version='2.74', id=uuids.hyper1)
        self.assertNotIn('servers', result['hypervisor'])


class HypervisorsTestV288(HypervisorsTestV275):
    api_version = '2.88'

    DETAIL_HYPERS_DICTS = copy.deepcopy(HypervisorsTestV21.DETAIL_HYPERS_DICTS)
    for hypervisor in DETAIL_HYPERS_DICTS:
        for key in (
            'cpu_info', 'current_workload', 'disk_available_least',
            'free_disk_gb', 'free_ram_mb', 'local_gb', 'local_gb_used',
            'memory_mb', 'memory_mb_used', 'running_vms', 'vcpus',
            'vcpus_used',
        ):
            del hypervisor[key]
        hypervisor['uptime'] = 'fake uptime'

    def setUp(self):
        super().setUp()

        self.controller.host_api.get_host_uptime = mock.MagicMock(
            return_value='fake uptime')

    def test_view_hypervisor_detail_cpuinfo_empty_string(self):
        # cpu_info is no longer included in the response, so skip this test
        pass

    def test_view_hypervisor_detail_cpuinfo_none(self):
        # cpu_info is no longer included in the response, so skip this test
        pass

    def test_uptime(self):
        req = self._get_request(True)
        self.assertRaises(
            exception.VersionNotFoundForAPIMethod,
            self.controller.uptime, req)

    def test_uptime_old_version(self):
        with mock.patch.object(
            self.controller.host_api, 'get_host_uptime',
            return_value='fake uptime',
        ):
            req = self._get_request(use_admin_context=True, version='2.87')
            hyper_id = self._get_hyper_id()

            # no exception == pass
            self.controller.uptime(req, hyper_id)

    def test_uptime_noid(self):
        # the separate 'uptime' API has been removed, so skip this test
        pass

    def test_uptime_not_implemented(self):
        # the separate 'uptime' API has been removed, so skip this test
        pass

    def test_uptime_implemented(self):
        # the separate 'uptime' API has been removed, so skip this test
        pass

    def test_uptime_integer_id(self):
        # the separate 'uptime' API has been removed, so skip this test
        pass

    def test_uptime_host_not_found(self):
        # the separate 'uptime' API has been removed, so skip this test
        pass

    def test_uptime_hypervisor_down(self):
        # the separate 'uptime' API has been removed, so skip this test
        pass

    def test_uptime_hypervisor_not_mapped_service_get(self):
        # the separate 'uptime' API has been removed, so skip this test
        pass

    def test_uptime_hypervisor_not_mapped(self):
        # the separate 'uptime' API has been removed, so skip this test
        pass

    def test_show_with_uptime_notimplemented(self):
        with mock.patch.object(
            self.controller.host_api, 'get_host_uptime',
            side_effect=NotImplementedError,
        ) as mock_get_uptime:
            req = self._get_request(use_admin_context=True)
            hyper_id = self._get_hyper_id()

            result = self.controller.show(req, hyper_id)

            expected_dict = copy.deepcopy(self.DETAIL_HYPERS_DICTS[0])
            expected_dict.update({'uptime': None})
            self.assertEqual({'hypervisor': expected_dict}, result)
            self.assertEqual(1, mock_get_uptime.call_count)

    def test_show_with_uptime_hypervisor_down(self):
        with mock.patch.object(
            self.controller.host_api, 'get_host_uptime',
            side_effect=exception.ComputeServiceUnavailable(host='dummy')
        ) as mock_get_uptime:
            req = self._get_request(use_admin_context=True)
            hyper_id = self._get_hyper_id()

            result = self.controller.show(req, hyper_id)

            expected_dict = copy.deepcopy(self.DETAIL_HYPERS_DICTS[0])
            expected_dict.update({'uptime': None})
            self.assertEqual({'hypervisor': expected_dict}, result)
            self.assertEqual(1, mock_get_uptime.call_count)

    def test_show_old_version(self):
        # ensure things still work as expected here
        req = self._get_request(use_admin_context=True, version='2.87')
        hyper_id = self._get_hyper_id()

        result = self.controller.show(req, hyper_id)

        self.assertNotIn('uptime', result)

    def test_statistics(self):
        req = self._get_request(use_admin_context=True)
        self.assertRaises(
            exception.VersionNotFoundForAPIMethod,
            self.controller.statistics, req)

    def test_statistics_old_version(self):
        req = self._get_request(use_admin_context=True, version='2.87')
        # no exception == pass
        self.controller.statistics(req)