~ubuntu-branches/ubuntu/raring/nova/raring-proposed

« back to all changes in this revision

Viewing changes to nova/tests/integrated/test_api_samples.py

  • Committer: Package Import Robot
  • Author(s): Chuck Short, Adam Gandelman, Chuck Short
  • Date: 2012-11-23 09:04:58 UTC
  • mfrom: (1.1.66)
  • Revision ID: package-import@ubuntu.com-20121123090458-91565o7aev1i1h71
Tags: 2013.1~g1-0ubuntu1
[ Adam Gandelman ]
* debian/control: Ensure novaclient is upgraded with nova,
  require python-keystoneclient >= 1:2.9.0. (LP: #1073289)
* debian/patches/{ubuntu/*, rbd-security.patch}: Dropped, applied
  upstream.
* debian/control: Add python-testtools to Build-Depends.

[ Chuck Short ]
* New upstream version.
* Refreshed debian/patches/avoid_setuptools_git_dependency.patch.
* debian/rules: FTBFS if missing binaries.
* debian/nova-scheudler.install: Add missing rabbit-queues and
  nova-rpc-zmq-receiver.
* Remove nova-volume since it doesnt exist anymore, transition to cinder-*.
* debian/rules: install apport hook in the right place.
* debian/patches/ubuntu-show-tests.patch: Display test failures.
* debian/control: Add depends on genisoimage
* debian/control: Suggest guestmount.
* debian/control: Suggest websockify. (LP: #1076442)
* debian/nova.conf: Disable nova-volume service.
* debian/control: Depend on xen-system-* rather than the hypervisor.
* debian/control, debian/mans/nova-conductor.8, debian/nova-conductor.init,
  debian/nova-conductor.install, debian/nova-conductor.logrotate
  debian/nova-conductor.manpages, debian/nova-conductor.postrm
  debian/nova-conductor.upstart.in: Add nova-conductor service.
* debian/control: Add python-fixtures as a build deps.

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
#    under the License.
15
15
 
16
16
import base64
 
17
import datetime
17
18
import os
18
19
import re
 
20
import urllib
19
21
import uuid
20
22
 
21
23
from lxml import etree
22
24
 
 
25
from nova.cloudpipe.pipelib import CloudPipe
 
26
from nova.compute import api
23
27
from nova import context
24
 
from nova import flags
 
28
from nova import db
 
29
from nova.network.manager import NetworkManager
 
30
from nova.openstack.common import cfg
25
31
from nova.openstack.common import importutils
26
32
from nova.openstack.common import jsonutils
27
33
from nova.openstack.common.log import logging
 
34
from nova.openstack.common import timeutils
 
35
from nova.scheduler import driver
28
36
from nova import test
29
37
from nova.tests import fake_network
30
38
from nova.tests.image import fake
31
39
from nova.tests.integrated import integrated_helpers
32
40
 
33
 
FLAGS = flags.FLAGS
 
41
CONF = cfg.CONF
 
42
CONF.import_opt('allow_resize_to_same_host', 'nova.config')
 
43
CONF.import_opt('osapi_compute_extension', 'nova.config')
 
44
CONF.import_opt('vpn_image_id', 'nova.config')
34
45
LOG = logging.getLogger(__name__)
35
46
 
36
47
 
69
80
        if not data:
70
81
            return {}
71
82
        if self.ctype == 'json':
 
83
            # NOTE(vish): allow non-quoted replacements to survive json
 
84
            data = re.sub(r'([^"])%\((.+)\)s([^"])', r'\1"%(int:\2)s"\3', data)
72
85
            return jsonutils.loads(data)
73
86
        else:
74
87
            def to_dict(node):
140
153
            if not isinstance(result, list):
141
154
                raise NoMatch(
142
155
                        _('Result: %(result)s is not a list.') % locals())
143
 
            # NOTE(maurosr): sort the list of dicts by their __tag__ element
144
 
            # when using xml. This will avoid some fails in keypairs api sample
145
 
            # which order in different way when using a private key itself or
146
 
            # its regular expression, and after all doesn't interfere with
147
 
            # other tests.
148
 
            # Should we define a criteria when ordering json? Doesn't seems
149
 
            # necessary so far.
150
 
            for ex_obj, res_obj in zip(sorted(expected, key=lambda k:
151
 
                                                        k.get('__tag__', k)),
152
 
                                       sorted(result, key=lambda k:
153
 
                                                        k.get('__tag__', k))):
154
 
                res = self._compare_result(subs, ex_obj, res_obj)
 
156
            if len(expected) != len(result):
 
157
                raise NoMatch(
 
158
                        _('Length mismatch: %(result)s\n%(expected)s.')
 
159
                        % locals())
 
160
            for res_obj in result:
 
161
                for ex_obj in expected:
 
162
                    try:
 
163
                        res = self._compare_result(subs, ex_obj, res_obj)
 
164
                        break
 
165
                    except NoMatch:
 
166
                        pass
 
167
                else:
 
168
                    raise NoMatch(
 
169
                            _('Result: %(res_obj)s not in %(expected)s.')
 
170
                            % locals())
155
171
                matched_value = res or matched_value
156
172
 
157
173
        elif isinstance(expected, basestring) and '%' in expected:
 
174
            # NOTE(vish): escape stuff for regex
 
175
            for char in '[]<>?':
 
176
                expected = expected.replace(char, '\\%s' % char)
 
177
            # NOTE(vish): special handling of subs that are not quoted. We are
 
178
            #             expecting an int but we had to pass in a string
 
179
            #             so the json would parse properly.
 
180
            if expected.startswith("%(int:"):
 
181
                result = str(result)
 
182
                expected = expected.replace('int:', '')
 
183
            expected = expected % subs
 
184
            expected = '^%s$' % expected
 
185
            match = re.match(expected, result)
 
186
            if not match:
 
187
                raise NoMatch(_('Values do not match:\n'
 
188
                        '%(expected)s\n%(result)s') % locals())
158
189
            try:
159
 
                # NOTE(vish): escape stuff for regex
160
 
                for char in ['[', ']', '<', '>', '?']:
161
 
                    expected = expected.replace(char, '\%s' % char)
162
 
                expected = expected % subs
163
 
                match = re.match(expected, result)
164
 
            except Exception as exc:
165
 
                raise NoMatch(_('Values do not match:\n'
166
 
                        '%(expected)s\n%(result)s') % locals())
167
 
            if not match:
168
 
                raise NoMatch(_('Values do not match:\n'
169
 
                        '%(expected)s\n%(result)s') % locals())
170
 
            if match.groups():
171
 
                matched_value = match.groups()[0]
 
190
                matched_value = match.group('id')
 
191
            except IndexError:
 
192
                if match.groups():
 
193
                    matched_value = match.groups()[0]
172
194
        else:
173
195
            if isinstance(expected, basestring):
174
196
                # NOTE(danms): Ignore whitespace in this comparison
200
222
        else:
201
223
            text = r'[^<]*'
202
224
        return {
203
 
            'timestamp': '[0-9]{4}-[0,1][0-9]-[0-3][0-9]T'
204
 
                         '[0-9]{2}:[0-9]{2}:[0-9]{2}'
205
 
                         '(Z|(\+|-)[0-9]{2}:[0-9]{2})',
 
225
            # NOTE(treinish): Could result in a false positive, but it
 
226
            # shouldn't be an issue for this case.
 
227
            'timestamp': '\d{4}-[0,1]\d-[0-3]\d[ ,T]'
 
228
                         '\d{2}:\d{2}:\d{2}'
 
229
                         '(Z|(\+|-)\d{2}:\d{2}|\.\d{6})',
206
230
            'password': '[0-9a-zA-Z]{1,12}',
207
231
            'ip': '[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}',
208
 
            'ip6': '([0-9a-zA-Z]{1,4}:){1,7}:?[0-9a-zA-Z]',
209
 
            'id': '([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}'
 
232
            'ip6': '([0-9a-zA-Z]{1,4}:){1,7}:?[0-9a-zA-Z]{1,4}',
 
233
            'id': '(?P<id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}'
210
234
                  '-[0-9a-f]{4}-[0-9a-f]{12})',
211
235
            'uuid': '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}'
212
236
                    '-[0-9a-f]{4}-[0-9a-f]{12}',
 
237
            'reservation_id': 'r-[0-9a-zA-Z]{8}',
213
238
            'private_key': '-----BEGIN RSA PRIVATE KEY-----'
214
239
                           '[a-zA-Z0-9\n/+=]*'
215
240
                           '-----END RSA PRIVATE KEY-----',
221
246
#                           '[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:'
222
247
#                           '[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}',
223
248
            'host': self._get_host(),
 
249
            'host_name': '[0-9a-z]{32}',
224
250
            'glance_host': self._get_glance_host(),
225
251
            'compute_host': self.compute.host,
226
252
            'text': text,
282
308
        subs = self._get_regexes()
283
309
        subs['hostid'] = '[a-f0-9]+'
284
310
        subs['id'] = uuid
 
311
        subs['hypervisor_hostname'] = r'[\w\.\-]+'
285
312
        return self._verify_response('server-get-resp', subs, response)
286
313
 
287
314
    def test_servers_list(self):
299
326
        subs = self._get_regexes()
300
327
        subs['hostid'] = '[a-f0-9]+'
301
328
        subs['id'] = uuid
 
329
        subs['hypervisor_hostname'] = r'[\w\.\-]+'
302
330
        return self._verify_response('servers-details-resp', subs, response)
303
331
 
304
332
 
381
409
    ctype = 'xml'
382
410
 
383
411
 
 
412
class ServersIpsJsonTest(ServersSampleBase):
 
413
    def test_get(self):
 
414
        """Test getting a server's IP information"""
 
415
        uuid = self._post_server()
 
416
        response = self._do_get('servers/%s/ips' % uuid)
 
417
        subs = self._get_regexes()
 
418
        return self._verify_response('server-ips-resp', subs, response)
 
419
 
 
420
    def test_get_by_network(self):
 
421
        """Test getting a server's IP information by network id"""
 
422
        uuid = self._post_server()
 
423
        response = self._do_get('servers/%s/ips/private' % uuid)
 
424
        subs = self._get_regexes()
 
425
        return self._verify_response('server-ips-network-resp', subs, response)
 
426
 
 
427
 
 
428
class ServersIpsXmlTest(ServersIpsJsonTest):
 
429
    ctype = 'xml'
 
430
 
 
431
 
384
432
class ExtensionsSampleJsonTest(ApiSampleTestBase):
385
433
    all_extensions = True
386
434
 
411
459
    ctype = 'xml'
412
460
 
413
461
 
 
462
class HostsSampleJsonTest(ApiSampleTestBase):
 
463
    extension_name = "nova.api.openstack.compute.contrib.hosts.Hosts"
 
464
 
 
465
    def test_host_get(self):
 
466
        response = self._do_get('os-hosts/%s' % self.compute.host)
 
467
        subs = self._get_regexes()
 
468
        return self._verify_response('host-get-resp', subs, response)
 
469
 
 
470
    def test_hosts_list(self):
 
471
        response = self._do_get('os-hosts')
 
472
        subs = self._get_regexes()
 
473
        return self._verify_response('hosts-list-resp', subs, response)
 
474
 
 
475
 
 
476
class HostsSampleXmlTest(HostsSampleJsonTest):
 
477
    ctype = 'xml'
 
478
 
 
479
 
414
480
class FlavorsSampleAllExtensionJsonTest(FlavorsSampleJsonTest):
415
481
    all_extensions = True
416
482
 
507
573
 
508
574
 
509
575
class ServersActionsJsonTest(ServersSampleBase):
510
 
    def setUp(self):
511
 
        super(ServersActionsJsonTest, self).setUp()
512
 
 
513
576
    def _test_server_action(self, uuid, action,
514
577
                            subs={}, resp_tpl=None, code=202):
515
578
        subs.update({'action': action})
550
613
                                 'server-action-rebuild-resp')
551
614
 
552
615
    def test_server_resize(self):
553
 
        FLAGS.allow_resize_to_same_host = True
 
616
        CONF.allow_resize_to_same_host = True
554
617
        uuid = self._post_server()
555
618
        self._test_server_action(uuid, "resize",
556
619
                                 {"id": 2,
577
640
    ctype = 'xml'
578
641
 
579
642
 
 
643
class ServersActionsAllJsonTest(ServersActionsJsonTest):
 
644
    all_extensions = True
 
645
 
 
646
 
 
647
class ServersActionsAllXmlTest(ServersActionsXmlTest):
 
648
    all_extensions = True
 
649
 
 
650
 
580
651
class ServerStartStopJsonTest(ServersSampleBase):
581
652
    extension_name = "nova.api.openstack.compute.contrib" + \
582
653
        ".server_start_stop.Server_start_stop"
630
701
 
631
702
    def _get_flags(self):
632
703
        f = super(FlavorsExtraDataJsonTest, self)._get_flags()
633
 
        f['osapi_compute_extension'] = FLAGS.osapi_compute_extension[:]
 
704
        f['osapi_compute_extension'] = CONF.osapi_compute_extension[:]
634
705
        # Flavorextradata extension also needs Flavormanage to be loaded.
635
706
        f['osapi_compute_extension'].append(
636
707
            'nova.api.openstack.compute.contrib.flavormanage.Flavormanage')
758
829
        subs['hostid'] = '[a-f0-9]+'
759
830
        subs['id'] = uuid
760
831
        subs['instance_name'] = 'instance-\d{8}'
 
832
        subs['hypervisor_hostname'] = r'[\w\.\-]+'
761
833
        return self._verify_response('extended-server-attrs-get',
762
834
                                     subs, response)
763
835
 
769
841
        subs['hostid'] = '[a-f0-9]+'
770
842
        subs['id'] = uuid
771
843
        subs['instance_name'] = 'instance-\d{8}'
 
844
        subs['hypervisor_hostname'] = r'[\w\.\-]+'
772
845
        return self._verify_response('extended-server-attrs-list',
773
846
                                     subs, response)
774
847
 
783
856
 
784
857
    def setUp(self):
785
858
        super(FloatingIpsJsonTest, self).setUp()
786
 
        pool = FLAGS.default_floating_pool
787
 
        interface = FLAGS.public_interface
 
859
        pool = CONF.default_floating_pool
 
860
        interface = CONF.public_interface
788
861
 
789
862
        self.ip_pool = [
790
863
            {
845
918
    def test_floating_ips_create(self):
846
919
        response = self._do_post('os-floating-ips',
847
920
                                 'floating-ips-create-req',
848
 
                                 {"pool": FLAGS.default_floating_pool})
 
921
                                 {"pool": CONF.default_floating_pool})
849
922
        self.assertEqual(response.status, 200)
850
923
        subs = self._get_regexes()
851
924
        self._verify_response('floating-ips-create-resp',
988
1061
 
989
1062
class VirtualInterfacesXmlTest(VirtualInterfacesJsonTest):
990
1063
    ctype = 'xml'
 
1064
 
 
1065
 
 
1066
class CloudPipeSampleJsonTest(ApiSampleTestBase):
 
1067
    extension_name = "nova.api.openstack.compute.contrib.cloudpipe.Cloudpipe"
 
1068
 
 
1069
    def setUp(self):
 
1070
        super(CloudPipeSampleJsonTest, self).setUp()
 
1071
 
 
1072
        def get_user_data(self, project_id):
 
1073
            """Stub method to generate user data for cloudpipe tests"""
 
1074
            return "VVNFUiBEQVRB\n"
 
1075
 
 
1076
        def network_api_get(self, context, network_uuid):
 
1077
            """Stub to get a valid network and its information"""
 
1078
            return {'vpn_public_address': '127.0.0.1',
 
1079
                    'vpn_public_port': 22}
 
1080
 
 
1081
        self.stubs.Set(CloudPipe, 'get_encoded_zip', get_user_data)
 
1082
        self.stubs.Set(NetworkManager, "get_network", network_api_get)
 
1083
 
 
1084
    def test_cloud_pipe_create(self):
 
1085
        """Get api samples of cloud pipe extension creation"""
 
1086
        CONF.vpn_image_id = fake.get_valid_image_id()
 
1087
        project = {'project_id': 'cloudpipe-' + str(uuid.uuid4())}
 
1088
        response = self._do_post('os-cloudpipe', 'cloud-pipe-create-req',
 
1089
                                 project)
 
1090
        self.assertEqual(response.status, 200)
 
1091
        subs = self._get_regexes()
 
1092
        subs.update(project)
 
1093
        subs['image_id'] = CONF.vpn_image_id
 
1094
        self._verify_response('cloud-pipe-create-resp', subs, response)
 
1095
        return project
 
1096
 
 
1097
    def test_cloud_pipe_list(self):
 
1098
        """Get api samples of cloud pipe extension get request"""
 
1099
        project = self.test_cloud_pipe_create()
 
1100
        response = self._do_get('os-cloudpipe')
 
1101
        self.assertEqual(response.status, 200)
 
1102
        subs = self._get_regexes()
 
1103
        subs.update(project)
 
1104
        subs['image_id'] = CONF.vpn_image_id
 
1105
        return self._verify_response('cloud-pipe-get-resp', subs, response)
 
1106
 
 
1107
 
 
1108
class CloudPipeSampleXmlTest(CloudPipeSampleJsonTest):
 
1109
    ctype = "xml"
 
1110
 
 
1111
 
 
1112
class AggregatesSampleJsonTest(ServersSampleBase):
 
1113
    extension_name = "nova.api.openstack.compute.contrib" + \
 
1114
                                     ".aggregates.Aggregates"
 
1115
 
 
1116
    def test_aggregate_create(self):
 
1117
        subs = {
 
1118
            "aggregate_id": '(?P<id>\d+)'
 
1119
        }
 
1120
        response = self._do_post('os-aggregates', 'aggregate-post-req', subs)
 
1121
        self.assertEqual(response.status, 200)
 
1122
        subs.update(self._get_regexes())
 
1123
        return self._verify_response('aggregate-post-resp', subs, response)
 
1124
 
 
1125
    def test_list_aggregates(self):
 
1126
        self.test_aggregate_create()
 
1127
        response = self._do_get('os-aggregates')
 
1128
        subs = self._get_regexes()
 
1129
        return self._verify_response('aggregates-list-get-resp',
 
1130
                                      subs, response)
 
1131
 
 
1132
    def test_aggregate_get(self):
 
1133
        agg_id = self.test_aggregate_create()
 
1134
        response = self._do_get('os-aggregates/%s' % agg_id)
 
1135
        subs = self._get_regexes()
 
1136
        return self._verify_response('aggregates-get-resp', subs, response)
 
1137
 
 
1138
    def test_add_metadata(self):
 
1139
        agg_id = self.test_aggregate_create()
 
1140
        response = self._do_post('os-aggregates/%s/action' % agg_id,
 
1141
                                 'aggregate-metadata-post-req',
 
1142
                                 {'action': 'set_metadata'})
 
1143
        subs = self._get_regexes()
 
1144
        return self._verify_response('aggregates-metadata-post-resp',
 
1145
                                      subs, response)
 
1146
 
 
1147
    def test_add_host(self):
 
1148
        aggregate_id = self.test_aggregate_create()
 
1149
        subs = {
 
1150
            "host_name": self.compute.host,
 
1151
        }
 
1152
        response = self._do_post('os-aggregates/%s/action' % aggregate_id,
 
1153
                                 'aggregate-add-host-post-req', subs)
 
1154
        subs.update(self._get_regexes())
 
1155
        return self._verify_response('aggregates-add-host-post-resp',
 
1156
                                      subs, response)
 
1157
 
 
1158
    def test_remove_host(self):
 
1159
        self.test_add_host()
 
1160
        subs = {
 
1161
            "host_name": self.compute.host,
 
1162
        }
 
1163
        response = self._do_post('os-aggregates/1/action',
 
1164
                                 'aggregate-remove-host-post-req', subs)
 
1165
        subs.update(self._get_regexes())
 
1166
        return self._verify_response('aggregates-remove-host-post-resp',
 
1167
                                      subs, response)
 
1168
 
 
1169
    def test_update_aggregate(self):
 
1170
        aggregate_id = self.test_aggregate_create()
 
1171
        response = self._do_put('os-aggregates/%s' % aggregate_id,
 
1172
                                  'aggregate-update-post-req', {})
 
1173
        subs = self._get_regexes()
 
1174
        return self._verify_response('aggregate-update-post-resp',
 
1175
                                      subs, response)
 
1176
 
 
1177
 
 
1178
class AggregatesSampleXmlTest(AggregatesSampleJsonTest):
 
1179
    ctype = 'xml'
 
1180
 
 
1181
 
 
1182
class CertificatesSamplesJsonTest(ApiSampleTestBase):
 
1183
    extension_name = ("nova.api.openstack.compute.contrib.certificates."
 
1184
                      "Certificates")
 
1185
 
 
1186
    def setUp(self):
 
1187
        super(CertificatesSamplesJsonTest, self).setUp()
 
1188
 
 
1189
    def test_create_certificates(self):
 
1190
        response = self._do_post('os-certificates',
 
1191
                                 'certificate-create-req', {})
 
1192
        self.assertEqual(response.status, 200)
 
1193
        subs = self._get_regexes()
 
1194
        return self._verify_response('certificate-create-resp', subs, response)
 
1195
 
 
1196
    def test_get_root_certificate(self):
 
1197
        response = self._do_get('os-certificates/root')
 
1198
        self.assertEqual(response.status, 200)
 
1199
        subs = self._get_regexes()
 
1200
        return self._verify_response('certificate-get-root-resp', subs,
 
1201
                                     response)
 
1202
 
 
1203
 
 
1204
class CertificatesSamplesXmlTest(CertificatesSamplesJsonTest):
 
1205
    ctype = 'xml'
 
1206
 
 
1207
 
 
1208
class UsedLimitsSamplesJsonTest(ApiSampleTestBase):
 
1209
    extension_name = ("nova.api.openstack.compute.contrib.used_limits."
 
1210
                      "Used_limits")
 
1211
 
 
1212
    def test_get_used_limits(self):
 
1213
        """Get api sample to used limits"""
 
1214
        response = self._do_get('limits')
 
1215
        self.assertEqual(response.status, 200)
 
1216
        subs = self._get_regexes()
 
1217
        return self._verify_response('usedlimits-get-resp', subs, response)
 
1218
 
 
1219
 
 
1220
class UsedLimitsSamplesXmlTest(UsedLimitsSamplesJsonTest):
 
1221
    ctype = "xml"
 
1222
 
 
1223
 
 
1224
class MultipleCreateJsonTest(ServersSampleBase):
 
1225
    extension_name = ("nova.api.openstack.compute.contrib.multiple_create."
 
1226
                      "Multiple_create")
 
1227
 
 
1228
    def test_multiple_create(self):
 
1229
        subs = {
 
1230
            'image_id': fake.get_valid_image_id(),
 
1231
            'host': self._get_host(),
 
1232
            'min_count': "2",
 
1233
            'max_count': "3"
 
1234
        }
 
1235
        response = self._do_post('servers', 'multiple-create-post-req', subs)
 
1236
        self.assertEqual(response.status, 202)
 
1237
        subs.update(self._get_regexes())
 
1238
        return self._verify_response('multiple-create-post-resp',
 
1239
                                      subs, response)
 
1240
 
 
1241
    def test_multiple_create_without_reservation_id(self):
 
1242
        subs = {
 
1243
            'image_id': fake.get_valid_image_id(),
 
1244
            'host': self._get_host(),
 
1245
            'min_count': "2",
 
1246
            'max_count': "3"
 
1247
        }
 
1248
        response = self._do_post('servers', 'multiple-create-no-resv-post-req',
 
1249
                                  subs)
 
1250
        self.assertEqual(response.status, 202)
 
1251
        subs.update(self._get_regexes())
 
1252
        return self._verify_response('multiple-create-no-resv-post-resp',
 
1253
                                      subs, response)
 
1254
 
 
1255
 
 
1256
class MultipleCreateXmlTest(MultipleCreateJsonTest):
 
1257
    ctype = 'xml'
 
1258
 
 
1259
 
 
1260
class SimpleTenantUsageSampleJsonTest(ServersSampleBase):
 
1261
    extension_name = ("nova.api.openstack.compute.contrib.simple_tenant_usage."
 
1262
                      "Simple_tenant_usage")
 
1263
 
 
1264
    def setUp(self):
 
1265
        """setUp method for simple tenant usage"""
 
1266
        super(SimpleTenantUsageSampleJsonTest, self).setUp()
 
1267
        self._post_server()
 
1268
        timeutils.set_time_override(timeutils.utcnow() +
 
1269
                                    datetime.timedelta(hours=1))
 
1270
        self.query = {
 
1271
            'start': str(timeutils.utcnow() - datetime.timedelta(hours=1)),
 
1272
            'end': str(timeutils.utcnow())
 
1273
        }
 
1274
 
 
1275
    def tearDown(self):
 
1276
        """tearDown method for simple tenant usage"""
 
1277
        super(SimpleTenantUsageSampleJsonTest, self).tearDown()
 
1278
        timeutils.clear_time_override()
 
1279
 
 
1280
    def test_get_tenants_usage(self):
 
1281
        """Get api sample to get all tenants usage request"""
 
1282
        response = self._do_get('os-simple-tenant-usage?%s' % (
 
1283
                                                urllib.urlencode(self.query)))
 
1284
        self.assertEqual(response.status, 200)
 
1285
        subs = self._get_regexes()
 
1286
        self._verify_response('simple-tenant-usage-get', subs, response)
 
1287
 
 
1288
    def test_get_tenant_usage_details(self):
 
1289
        """Get api sample to get specific tenant usage request"""
 
1290
        tenant_id = 'openstack'
 
1291
        response = self._do_get('os-simple-tenant-usage/%s?%s' % (tenant_id,
 
1292
                                                urllib.urlencode(self.query)))
 
1293
        self.assertEqual(response.status, 200)
 
1294
        subs = self._get_regexes()
 
1295
        self._verify_response('simple-tenant-usage-get-specific', subs,
 
1296
                              response)
 
1297
 
 
1298
 
 
1299
class SimpleTenantUsageSampleXmlTest(SimpleTenantUsageSampleJsonTest):
 
1300
    ctype = "xml"
 
1301
 
 
1302
 
 
1303
class ServerDiagnosticsSamplesJsonTest(ServersSampleBase):
 
1304
    extension_name = ("nova.api.openstack.compute.contrib.server_diagnostics."
 
1305
                      "Server_diagnostics")
 
1306
 
 
1307
    def test_server_diagnostics_get(self):
 
1308
        uuid = self._post_server()
 
1309
        response = self._do_get('servers/%s/diagnostics' % uuid)
 
1310
        self.assertEqual(response.status, 200)
 
1311
        subs = self._get_regexes()
 
1312
        return self._verify_response('server-diagnostics-get-resp', subs,
 
1313
                                     response)
 
1314
 
 
1315
 
 
1316
class ServerDiagnosticsSamplesXmlTest(ServerDiagnosticsSamplesJsonTest):
 
1317
    ctype = "xml"
 
1318
 
 
1319
 
 
1320
class AvailabilityZoneJsonTest(ServersSampleBase):
 
1321
    extension_name = ("nova.api.openstack.compute.contrib.availability_zone."
 
1322
                      "Availability_zone")
 
1323
 
 
1324
    def test_create_availability_zone(self):
 
1325
        subs = {
 
1326
            'image_id': fake.get_valid_image_id(),
 
1327
            'host': self._get_host(),
 
1328
            "availability_zone": "nova"
 
1329
        }
 
1330
        response = self._do_post('servers', 'availability-zone-post-req', subs)
 
1331
        self.assertEqual(response.status, 202)
 
1332
        subs.update(self._get_regexes())
 
1333
        return self._verify_response('availability-zone-post-resp',
 
1334
                                      subs, response)
 
1335
 
 
1336
 
 
1337
class AvailabilityZoneXmlTest(AvailabilityZoneJsonTest):
 
1338
    ctype = "xml"
 
1339
 
 
1340
 
 
1341
class AdminActionsSamplesJsonTest(ServersSampleBase):
 
1342
    extension_name = ("nova.api.openstack.compute.contrib.admin_actions."
 
1343
                      "Admin_actions")
 
1344
 
 
1345
    def setUp(self):
 
1346
        """setUp Method for AdminActions api samples extension
 
1347
        This method creates the server that will be used in each tests"""
 
1348
        super(AdminActionsSamplesJsonTest, self).setUp()
 
1349
        self.uuid = self._post_server()
 
1350
 
 
1351
    def test_post_pause(self):
 
1352
        """Get api samples to pause server request"""
 
1353
        response = self._do_post('servers/%s/action' % self.uuid,
 
1354
                                 'admin-actions-pause', {})
 
1355
        self.assertEqual(response.status, 202)
 
1356
 
 
1357
    def test_post_unpause(self):
 
1358
        """Get api samples to unpause server request"""
 
1359
        self.test_post_pause()
 
1360
        response = self._do_post('servers/%s/action' % self.uuid,
 
1361
                                 'admin-actions-unpause', {})
 
1362
        self.assertEqual(response.status, 202)
 
1363
 
 
1364
    def test_post_suspend(self):
 
1365
        """Get api samples to suspend server request"""
 
1366
        response = self._do_post('servers/%s/action' % self.uuid,
 
1367
                                 'admin-actions-suspend', {})
 
1368
        self.assertEqual(response.status, 202)
 
1369
 
 
1370
    def test_post_resume(self):
 
1371
        """Get api samples to server resume request"""
 
1372
        self.test_post_suspend()
 
1373
        response = self._do_post('servers/%s/action' % self.uuid,
 
1374
                                 'admin-actions-resume', {})
 
1375
        self.assertEqual(response.status, 202)
 
1376
 
 
1377
    def test_post_migrate(self):
 
1378
        """Get api samples to migrate server request"""
 
1379
        response = self._do_post('servers/%s/action' % self.uuid,
 
1380
                                 'admin-actions-migrate', {})
 
1381
        self.assertEqual(response.status, 202)
 
1382
 
 
1383
    def test_post_reset_network(self):
 
1384
        """Get api samples to reset server network request"""
 
1385
        response = self._do_post('servers/%s/action' % self.uuid,
 
1386
                                 'admin-actions-reset-network', {})
 
1387
        self.assertEqual(response.status, 202)
 
1388
 
 
1389
    def test_post_inject_network_info(self):
 
1390
        """Get api samples to inject network info request"""
 
1391
        response = self._do_post('servers/%s/action' % self.uuid,
 
1392
                                 'admin-actions-inject-network-info', {})
 
1393
        self.assertEqual(response.status, 202)
 
1394
 
 
1395
    def test_post_lock_server(self):
 
1396
        """Get api samples to lock server request"""
 
1397
        response = self._do_post('servers/%s/action' % self.uuid,
 
1398
                                 'admin-actions-lock-server', {})
 
1399
        self.assertEqual(response.status, 202)
 
1400
 
 
1401
    def test_post_unlock_server(self):
 
1402
        """Get api samples to unlock server request"""
 
1403
        self.test_post_lock_server()
 
1404
        response = self._do_post('servers/%s/action' % self.uuid,
 
1405
                                 'admin-actions-unlock-server', {})
 
1406
        self.assertEqual(response.status, 202)
 
1407
 
 
1408
    def test_post_backup_server(self):
 
1409
        """Get api samples to backup server request"""
 
1410
        def image_details(self, context, **kwargs):
 
1411
            """This stub is specifically used on the backup action."""
 
1412
            # NOTE(maurosr): I've added this simple stub cause backup action
 
1413
            # was trapped in infinite loop during fetch image phase since the
 
1414
            # fake Image Service always returns the same set of images
 
1415
            return None
 
1416
 
 
1417
        self.stubs.Set(fake._FakeImageService, 'detail', image_details)
 
1418
 
 
1419
        response = self._do_post('servers/%s/action' % self.uuid,
 
1420
                                 'admin-actions-backup-server', {})
 
1421
        self.assertEqual(response.status, 202)
 
1422
 
 
1423
    def test_post_live_migrate_server(self):
 
1424
        """Get api samples to server live migrate request"""
 
1425
        def fake_live_migration_src_check(self, context, instance_ref):
 
1426
            """Skip live migration scheduler checks"""
 
1427
            return
 
1428
 
 
1429
        def fake_live_migration_dest_check(self, context, instance_ref, dest):
 
1430
            """Skip live migration scheduler checks"""
 
1431
            return
 
1432
 
 
1433
        def fake_live_migration_common(self, context, instance_ref, dest):
 
1434
            """Skip live migration scheduler checks"""
 
1435
            return
 
1436
        self.stubs.Set(driver.Scheduler, '_live_migration_src_check',
 
1437
                       fake_live_migration_src_check)
 
1438
        self.stubs.Set(driver.Scheduler, '_live_migration_dest_check',
 
1439
                       fake_live_migration_dest_check)
 
1440
        self.stubs.Set(driver.Scheduler, '_live_migration_common_check',
 
1441
                       fake_live_migration_common)
 
1442
 
 
1443
        def fake_get_compute(context, host):
 
1444
            service = dict(host=host,
 
1445
                           binary='nova-compute',
 
1446
                           topic='compute',
 
1447
                           report_count=1,
 
1448
                           updated_at='foo',
 
1449
                           hypervisor_type='bar',
 
1450
                           hypervisor_version='1',
 
1451
                           disabled=False)
 
1452
            return [{'compute_node': [service]}]
 
1453
        self.stubs.Set(db, "service_get_all_compute_by_host", fake_get_compute)
 
1454
 
 
1455
        response = self._do_post('servers/%s/action' % self.uuid,
 
1456
                                 'admin-actions-live-migrate',
 
1457
                                 {'hostname': self.compute.host})
 
1458
        self.assertEqual(response.status, 202)
 
1459
 
 
1460
    def test_post_reset_state(self):
 
1461
        """get api samples to server reset state request"""
 
1462
        response = self._do_post('servers/%s/action' % self.uuid,
 
1463
                                 'admin-actions-reset-server-state', {})
 
1464
        self.assertEqual(response.status, 202)
 
1465
 
 
1466
 
 
1467
class AdminActionsSamplesXmlTest(AdminActionsSamplesJsonTest):
 
1468
    ctype = 'xml'
 
1469
 
 
1470
 
 
1471
class ConsolesSampleJsonTests(ServersSampleBase):
 
1472
    extension_name = ("nova.api.openstack.compute.contrib"
 
1473
                                     ".consoles.Consoles")
 
1474
 
 
1475
    def test_get_vnc_console(self):
 
1476
        uuid = self._post_server()
 
1477
        response = self._do_post('servers/%s/action' % uuid,
 
1478
                                 'get-vnc-console-post-req',
 
1479
                                {'action': 'os-getVNCConsole'})
 
1480
        self.assertEqual(response.status, 200)
 
1481
        subs = self._get_regexes()
 
1482
        subs["url"] = \
 
1483
            "((https?):((//)|(\\\\))+([\w\d:#@%/;$()~_?\+-=\\\.&](#!)?)*)"
 
1484
        return self._verify_response('get-vnc-console-post-resp',
 
1485
                                       subs, response)
 
1486
 
 
1487
 
 
1488
class ConsoleOutputSampleXmlTests(ConsoleOutputSampleJsonTest):
 
1489
        ctype = 'xml'