Add unit tests for rest

* add unit tests for rest.types
* add unit tests for rest.controllers.root
* add unit tests for rest.controllers.v1.root

Change-Id: Icb7d243643a6a0a57d2b1f01879774008491ea0a
This commit is contained in:
liyingjun 2014-06-17 01:12:05 +08:00
parent 3ed98ecec0
commit 9e189b9228
7 changed files with 336 additions and 1 deletions

View File

@ -55,7 +55,7 @@ class Version(wtypes.Base):
links=None):
v = Version(id=id, status=status, updated_at=updated_at)
if media_types is None:
mime_type = "application/vnd.openstack.rally.{}+json".format(id)
mime_type = "application/vnd.openstack.rally.%s+json" % id
media_types = [MediaType('application/json', mime_type)]
v.media_types = media_types
if links is None:

0
tests/aas/__init__.py Normal file
View File

View File

232
tests/aas/rest/base.py Normal file
View File

@ -0,0 +1,232 @@
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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.
"""Base classes for API tests."""
# NOTE: Ported from ceilometer/tests/api.py (subsequently moved to
# ceilometer/tests/api/__init__.py).
import pecan
import pecan.testing
from six.moves.urllib import parse as urlparse
from tests import test
PATH_PREFIX = '/v1'
class FunctionalTest(test.TestCase):
"""Used for functional tests of Pecan controllers.
Use this class where you need to test your literal application
and its integration with the framework.
"""
SOURCE_DATA = {'test_source': {'somekey': '666'}}
def setUp(self):
super(FunctionalTest, self).setUp()
self.app = self._make_app()
def reset_pecan():
pecan.set_config({}, overwrite=True)
self.addCleanup(reset_pecan)
def _make_app(self, enable_acl=False):
# Determine where we are so we can set up paths in the config
self.config = {
'app': {
'root': 'rally.aas.rest.controllers.root.RootController',
'modules': ['rally.aas.rest'],
},
}
return pecan.testing.load_test_app(self.config)
def _request_json(self, path, params, expect_errors=False, headers=None,
method="post", extra_environ=None, status=None,
path_prefix=PATH_PREFIX):
"""Simulate an json request.
Sends simulated HTTP request to Pecan test app.
:param path: url path of target service
:param params: content for wsgi.input of request
:param expect_errors: Boolean value; whether an error is expected based
on request
:param headers: a dictionary of headers to send along with the request
:param method: Request method type. Appropriate method function call
should be used rather than passing attribute in.
:param extra_environ: a dictionary of environ variables to send along
with the request
:param status: expected status code of response
:param path_prefix: prefix of the url path
"""
full_path = path_prefix + path
print('%s: %s %s' % (method.upper(), full_path, params))
response = getattr(self.app, "%s_json" % method)(
str(full_path),
params=params,
headers=headers,
status=status,
extra_environ=extra_environ,
expect_errors=expect_errors
)
print('GOT:%s' % response)
return response
def put_json(self, path, params, expect_errors=False, headers=None,
extra_environ=None, status=None):
"""Simulate an put request.
Sends simulated HTTP PUT request to Pecan test app.
:param path: url path of target service
:param params: content for wsgi.input of request
:param expect_errors: Boolean value; whether an error is expected based
on request
:param headers: a dictionary of headers to send along with the request
:param extra_environ: a dictionary of environ variables to send along
with the request
:param status: expected status code of response
"""
return self._request_json(path=path, params=params,
expect_errors=expect_errors,
headers=headers, extra_environ=extra_environ,
status=status, method="put")
def post_json(self, path, params, expect_errors=False, headers=None,
extra_environ=None, status=None):
"""Simulate an post request.
Sends simulated HTTP POST request to Pecan test app.
:param path: url path of target service
:param params: content for wsgi.input of request
:param expect_errors: Boolean value; whether an error is expected based
on request
:param headers: a dictionary of headers to send along with the request
:param extra_environ: a dictionary of environ variables to send along
with the request
:param status: expected status code of response
"""
return self._request_json(path=path, params=params,
expect_errors=expect_errors,
headers=headers, extra_environ=extra_environ,
status=status, method="post")
def patch_json(self, path, params, expect_errors=False, headers=None,
extra_environ=None, status=None):
"""Simulate an patch request.
Sends simulated HTTP PATCH request to Pecan test app.
:param path: url path of target service
:param params: content for wsgi.input of request
:param expect_errors: Boolean value; whether an error is expected based
on request
:param headers: a dictionary of headers to send along with the request
:param extra_environ: a dictionary of environ variables to send along
with the request
:param status: expected status code of response
"""
return self._request_json(path=path, params=params,
expect_errors=expect_errors,
headers=headers, extra_environ=extra_environ,
status=status, method="patch")
def delete(self, path, expect_errors=False, headers=None,
extra_environ=None, status=None, path_prefix=PATH_PREFIX):
"""Simulate a delete request.
Sends simulated HTTP DELETE request to Pecan test app.
:param path: url path of target service
:param expect_errors: Boolean value; whether an error is expected based
on request
:param headers: a dictionary of headers to send along with the request
:param extra_environ: a dictionary of environ variables to send along
with the request
:param status: expected status code of response
:param path_prefix: prefix of the url path
"""
full_path = path_prefix + path
print('DELETE: %s' % (full_path))
response = self.app.delete(full_path,
headers=headers,
status=status,
extra_environ=extra_environ,
expect_errors=expect_errors)
print('GOT:%s' % response)
return response
def get_json(self, path, expect_errors=False, headers=None,
extra_environ=None, q=[], path_prefix=PATH_PREFIX, **params):
"""Simulate a get request.
Sends simulated HTTP GET request to Pecan test app.
:param path: url path of target service
:param expect_errors: Boolean value;whether an error is expected based
on request
:param headers: a dictionary of headers to send along with the request
:param extra_environ: a dictionary of environ variables to send along
with the request
:param q: list of queries consisting of: field, value, op, and type
keys
:param path_prefix: prefix of the url path
:param params: content for wsgi.input of request
"""
full_path = path_prefix + path
query_params = {'q.field': [],
'q.value': [],
'q.op': [],
}
for query in q:
for name in ['field', 'op', 'value']:
query_params['q.%s' % name].append(query.get(name, ''))
all_params = {}
all_params.update(params)
if q:
all_params.update(query_params)
print('GET: %(path)s %(params)r' % {'path': full_path,
'params': all_params})
response = self.app.get(full_path,
params=all_params,
headers=headers,
extra_environ=extra_environ,
expect_errors=expect_errors)
if not expect_errors:
response = response.json
print('GOT:%s' % response)
return response
def validate_link(self, link, bookmark=False):
"""Check if the given link can get correct data."""
# removes the scheme and net location parts of the link
url_parts = list(urlparse.urlparse(link))
url_parts[0] = url_parts[1] = ''
# bookmark link should not have the version in the URL
if bookmark and url_parts[2].startswith(PATH_PREFIX):
return False
full_path = urlparse.urlunparse(url_parts)
try:
self.get_json(full_path, path_prefix='')
return True
except Exception:
return False

View File

View File

@ -0,0 +1,44 @@
# Copyright 2014 Kylin Cloud
# 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.
from __future__ import print_function
from tests.aas.rest import base
class TestRoot(base.FunctionalTest):
def test_get_root(self):
data = self.get_json('/', path_prefix='')
self.assertEqual('v1', data['versions'][0]['id'])
# Check fields are not empty
[self.assertTrue(f) for f in data.keys()]
class TestV1Root(base.FunctionalTest):
def test_get_v1_root(self):
data = self.get_json('/')
self.assertEqual('v1', data['id'])
# Check if all known resources are present and there are no extra ones.
expected_resources = set(['id', 'links', 'media_types', 'status',
'updated_at'])
actual_resources = set(data.keys())
# TODO(lyj): There are still no resources in api, we need to add the
# related resources here when new api resources added.
self.assertEqual(expected_resources, actual_resources)
self.assertIn({'type': 'application/vnd.openstack.rally.v1+json',
'base': 'application/json'}, data['media_types'])

View File

@ -0,0 +1,59 @@
# Copyright 2014 Kylin Cloud
# 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.
"""Test for rest types."""
from __future__ import print_function
from rally.aas.rest import types
from tests import test
class TestLink(test.TestCase):
def test_make_link(self):
url = "http://localhost:8877"
rel = "version"
link = types.Link.make_link(rel, url, "fake")
self.assertEqual("http://localhost:8877/fake", link.href)
self.assertEqual(rel, link.rel)
class TestMediaType(test.TestCase):
def test_init(self):
base = "application/json"
_type = "application/vnd.openstack.rally.v1+json"
mt = types.MediaType(base, _type)
self.assertEqual(base, mt.base)
self.assertEqual(_type, mt.type)
class TestVersion(test.TestCase):
def test_convert(self):
id = "v1"
status = "active"
updated_at = "2014-01-07T00:00:00Z"
link = types.Link.make_link("version", "http://localhost:8877", "fake")
version = types.Version.convert(id, status, updated_at=updated_at,
links=[link])
self.assertEqual(id, version.id)
self.assertEqual(status, version.status)
self.assertEqual(updated_at, version.updated_at)
self.assertEqual("application/json", version.media_types[0].base)
self.assertEqual("application/vnd.openstack.rally.v1+json",
version.media_types[0].type)
self.assertEqual([link], version.links)