Removes the vestigial tests.

This gets rid of the misleading tests in this repo which have not been
relied on for most of this project's life (for historical reasons, tests
are currently stored in the reddwarf_lite-integration repo).

Change-Id: Ic452396ac50ea252bbd34d41638c2f337da3ed2a
This commit is contained in:
Tim Simpson 2012-11-02 16:19:04 -05:00
parent bdbb0a64a6
commit 11a3e531f7
15 changed files with 1 additions and 1039 deletions

View File

@ -1,16 +0,0 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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.

View File

@ -1,40 +0,0 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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 factory
from reddwarf.common import context
from reddwarf.common import utils
from reddwarf.instance import models
class DBInstance(factory.Factory):
FACTORY_FOR = models.DBInstance
context = context.ReddwarfContext()
uuid = utils.generate_uuid()
class Instance(factory.Factory):
FACTORY_FOR = models.Instance
context = context.ReddwarfContext()
uuid = utils.generate_uuid()
def factory_create(model_to_create, **kwargs):
return model_to_create(**kwargs)
factory.Factory.set_creation_function(factory_create)

View File

@ -1,65 +0,0 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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 os
import subprocess
from reddwarf import tests
from reddwarf.common import config
from reddwarf.db import db_api
def setup():
options = dict(config_file=tests.test_config_file())
conf = config.Config.load_paste_config("reddwarf", options, None)
db_api.db_reset(conf)
def execute(cmd, raise_error=True):
"""Executes a command in a subprocess.
Returns a tuple of (exitcode, out, err), where out is the string output
from stdout and err is the string output from stderr when
executing the command.
:param cmd: Command string to execute
:param raise_error: If returncode is not 0 (success), then
raise a RuntimeError? Default: True)
"""
env = os.environ.copy()
# Make sure that we use the programs in the
# current source directory's bin/ directory.
env['PATH'] = tests.reddwarf_bin_path() + ':' + env['PATH']
process = subprocess.Popen(cmd,
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env)
result = process.communicate()
(out, err) = result
exitcode = process.returncode
if process.returncode != 0 and raise_error:
msg = "Command %(cmd)s did not succeed. Returned an exit "\
"code of %(exitcode)d."\
"\n\nSTDOUT: %(out)s"\
"\n\nSTDERR: %(err)s" % locals()
raise RuntimeError(msg)
return exitcode, out, err

View File

@ -1,44 +0,0 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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 datetime
import reddwarf
from reddwarf import tests
from reddwarf.common import config
from reddwarf.tests import functional
def run_reddwarf_manage(command):
reddwarf_manage = tests.reddwarf_bin_path('reddwarf-manage')
config_file = tests.test_config_file()
return functional.execute("%(reddwarf_manage)s %(command)s "
"--config-file=%(config_file)s" % locals())
class TestDBSyncCLI(tests.BaseTest):
def test_db_sync_executes(self):
exitcode, out, err = run_reddwarf_manage("db_sync")
self.assertEqual(exitcode, 0)
class TestDBUpgradeCLI(tests.BaseTest):
def test_db_upgrade_executes(self):
exitcode, out, err = run_reddwarf_manage("db_upgrade")
self.assertEqual(exitcode, 0)

View File

@ -1,49 +0,0 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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 json
import webtest
from reddwarf import tests
from reddwarf.common import config
from reddwarf.common import utils
from reddwarf.common import wsgi
from reddwarf.db import db_api
# TODO(hub-cap): we will probably use this later
# def sanitize(data):
# serializer = wsgi.JSONDictSerializer()
# return json.loads(serializer.serialize(data))
class TestApp(webtest.TestApp):
def post_json(self, url, body=None, **kwargs):
kwargs['content_type'] = "application/json"
return self.post(url, json.dumps(body), **kwargs)
def put_json(self, url, body=None, **kwargs):
kwargs['content_type'] = "application/json"
return self.put(url, json.dumps(body), **kwargs)
def setup():
options = {"config_file": tests.test_config_file()}
conf = config.Config.load_paste_config("reddwarfapp", options, None)
db_api.db_reset(conf)

View File

@ -1,47 +0,0 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC.
# 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 unittest
from reddwarf.common.auth import TenantBasedAuth
class TenantRegexTest(unittest.TestCase):
def check(self, path, no_match=False, expected_tenant_id=None,
expected_version_id=None):
print("Path=%s" % path)
match = TenantBasedAuth.tenant_scoped_url.match(path)
if no_match:
self.assertIsNone(match, "Somehow path %s was a match!" % path)
else:
self.assertIsNotNone(match)
if expected_tenant_id:
actual = match.group('tenant_id')
self.assertEqual(expected_tenant_id, actual)
else:
self.assertRaises(IndexError, match.group('tenant_id'))
def test_no_match(self):
self.check("blah", no_match=True)
def test_has_tenant_id1(self):
self.check("/mgmt/instances/None", expected_tenant_id="mgmt")
def test_has_tenant_id2(self):
self.check(
"/9bbf90bc162d4d1ea458af6214a625e6/mgmt/instances/None",
expected_tenant_id="9bbf90bc162d4d1ea458af6214a625e6")

View File

@ -1,57 +0,0 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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 logging
import unittest
from reddwarf.common import context
AUTH_TOK = "auth-token"
LOG = logging.getLogger(__name__)
TENANT = "tenant"
USER = "user"
class ContextTest(unittest.TestCase):
def test_get_context_as_dict(self):
ctx = context.ReddwarfContext(user=USER, tenant=TENANT,
is_admin=True, show_deleted=True,
read_only=True, auth_tok=AUTH_TOK)
ctx_dict = ctx.to_dict()
self.assertEqual(ctx_dict['user'], USER)
self.assertEqual(ctx_dict['tenant'], TENANT)
self.assertEqual(ctx_dict['is_admin'], True)
self.assertEqual(ctx_dict['show_deleted'], True)
self.assertEqual(ctx_dict['read_only'], True)
self.assertEqual(ctx_dict['auth_tok'], AUTH_TOK)
def test_creating_context(self):
tmp_ctx_dict = {
'user': USER,
'tenant': TENANT,
'is_admin': True,
'show_deleted': True,
'read_only': True,
'auth_tok': AUTH_TOK,
}
tmp_ctx = context.ReddwarfContext.from_dict(tmp_ctx_dict)
self.assertEqual(tmp_ctx.user, USER)
self.assertEqual(tmp_ctx.tenant, TENANT)
self.assertEqual(tmp_ctx.is_admin, True)
self.assertEqual(tmp_ctx.show_deleted, True)
self.assertEqual(tmp_ctx.read_only, True)
self.assertEqual(tmp_ctx.auth_tok, AUTH_TOK)

View File

@ -1,99 +0,0 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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 mox
import novaclient
from reddwarf import tests
from reddwarf.common import utils
from reddwarf.common import exception
from reddwarf.instance import models
from reddwarf.instance.tasks import InstanceTasks
from reddwarf.tests.factories import models as factory_models
class TestInstance(tests.BaseTest):
FAKE_SERVER = None
def setUp(self):
super(TestInstance, self).setUp()
self.expected_name = 'my_name'
self.expected_id = utils.generate_uuid()
def mock_out_client(self):
"""Stubs out a fake server returned from novaclient.
This is akin to calling Client.servers.get(uuid)
and getting the server object back."""
self.FAKE_SERVER = self.mock.CreateMock(object)
self.FAKE_SERVER.name = self.expected_name
self.FAKE_SERVER.status = 'ACTIVE'
self.FAKE_SERVER.updated = utils.utcnow()
self.FAKE_SERVER.created = utils.utcnow()
self.FAKE_SERVER.id = self.expected_id
self.FAKE_SERVER.flavor = ('http://localhost/1234/flavors/',
'52415800-8b69-11e0-9b19-734f1195ff37')
self.FAKE_SERVER.links = [
{
"href": "http://localhost/1234/instances/123",
"rel": "self",
},
{
"href": "http://localhost/1234/instances/123",
"rel": "bookmark",
},
]
self.FAKE_SERVER.addresses = {
"private": [
{
"addr": "10.0.0.4",
"version": 4
},
],
}
client = self.mock.CreateMock(novaclient.v1_1.Client)
servers = self.mock.CreateMock(novaclient.v1_1.servers.ServerManager)
servers.get(mox.IgnoreArg()).AndReturn(self.FAKE_SERVER)
client.servers = servers
self.mock.StubOutWithMock(models.NovaRemoteModelBase, 'get_client')
models.NovaRemoteModelBase.get_client(mox.IgnoreArg()). \
AndReturn(client)
self.mock.ReplayAll()
def test_create_dbinstance_data(self):
"""This ensures the data() call in a new
DBInstance object returns the proper mapped data
to a dict from attr's"""
# Creates the instance via __init__
from reddwarf.instance import tasks
instance = factory_models.DBInstance(
task_status=InstanceTasks.BUILDING,
name=self.expected_name,
compute_instance_id=self.expected_id,
task_start_time=None).data()
self.assertEqual(instance['name'], self.expected_name)
self.assertEqual(instance['compute_instance_id'], self.expected_id)
self.assertEqual(instance['task_id'], InstanceTasks.BUILDING.code)
self.assertEqual(instance['task_description'],
InstanceTasks.BUILDING.db_text)
def test_create_instance_data_without_flavorref(self):
#todo(cp16net) fix this to work with the factory
self.mock_out_client()
self.FAKE_SERVER.flavor = None
self.assertRaises(exception.BadRequest, factory_models.Instance())

View File

@ -1,165 +0,0 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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 mox
import logging
from nose import SkipTest
import novaclient
from reddwarf import tests
from reddwarf.common import config
from reddwarf.common import utils
from reddwarf.instance import models
from reddwarf.tests import unit
LOG = logging.getLogger(__name__)
class ControllerTestBase(tests.BaseTest):
def setUp(self):
super(ControllerTestBase, self).setUp()
conf, reddwarf_app = config.Config.load_paste_app(
'reddwarfapp',
{"config_file": tests.test_config_file()},
None)
self.app = unit.TestApp(reddwarf_app)
class TestInstanceController(ControllerTestBase):
DUMMY_INSTANCE_ID = "123"
DUMMY_INSTANCE = {
"id": DUMMY_INSTANCE_ID,
"name": "DUMMY_NAME",
"status": "BUILD",
"created": "createtime",
"updated": "updatedtime",
"flavor": {},
"links": [],
"addresses": {},
}
def setUp(self):
self.instances_path = "/tenant/instances"
super(TestInstanceController, self).setUp()
# TODO(hub-cap): Start testing the failure cases
def test_show_broken(self):
raise SkipTest()
response = self.app.get("%s/%s" % (self.instances_path,
self.DUMMY_INSTANCE_ID),
headers={'X-Auth-Token': '123'})
self.assertEqual(response.status_int, 404)
def test_show(self):
raise SkipTest()
self.mock.StubOutWithMock(models.Instance, 'data')
models.Instance.data().AndReturn(self.DUMMY_INSTANCE)
self.mock.StubOutWithMock(models.Instance, '__init__')
models.Instance.__init__(context=mox.IgnoreArg(), uuid=mox.IgnoreArg())
self.mock.ReplayAll()
response = self.app.get("%s/%s" % (self.instances_path,
self.DUMMY_INSTANCE_ID),
headers={'X-Auth-Token': '123'})
self.assertEqual(response.status_int, 201)
def test_index(self):
raise SkipTest()
self.mock.StubOutWithMock(models.Instances, 'data')
models.Instances.data().AndReturn([self.DUMMY_INSTANCE])
self.mock.StubOutWithMock(models.Instances, '__init__')
models.Instances.__init__(mox.IgnoreArg())
self.mock.ReplayAll()
response = self.app.get("%s" % (self.instances_path),
headers={'X-Auth-Token': '123'})
self.assertEqual(response.status_int, 201)
def mock_out_client_create(self):
"""Stubs out a fake server returned from novaclient.
This is akin to calling Client.servers.get(uuid)
and getting the server object back."""
self.FAKE_SERVER = self.mock.CreateMock(object)
self.FAKE_SERVER.name = 'my_name'
self.FAKE_SERVER.status = 'ACTIVE'
self.FAKE_SERVER.updated = utils.utcnow()
self.FAKE_SERVER.created = utils.utcnow()
self.FAKE_SERVER.id = utils.generate_uuid()
self.FAKE_SERVER.flavor = 'http://localhost/1234/flavors/1234'
self.FAKE_SERVER.links = [
{
"href": "http://localhost/1234/instances/123",
"rel": "self",
},
{
"href": "http://localhost/1234/instances/123",
"rel": "bookmark",
}
]
self.FAKE_SERVER.addresses = {
"private": [
{
"addr": "10.0.0.4",
"version": 4,
},
],
}
client = self.mock.CreateMock(novaclient.v1_1.Client)
servers = self.mock.CreateMock(novaclient.v1_1.servers.ServerManager)
servers.create(mox.IgnoreArg(),
mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn(self.FAKE_SERVER)
client.servers = servers
self.mock.StubOutWithMock(models.NovaRemoteModelBase, 'get_client')
models.NovaRemoteModelBase.get_client(mox.IgnoreArg()). \
AndReturn(client)
def test_create(self):
raise SkipTest()
self.mock.StubOutWithMock(models.Instance, 'data')
models.Instance.data().AndReturn(self.DUMMY_INSTANCE)
self.mock.StubOutWithMock(models.ServiceImage, 'find_by')
models.ServiceImage.find_by(
service_name=mox.IgnoreArg()).AndReturn({'image_id': 1234})
self.mock_out_client_create()
self.mock.ReplayAll()
body = {
"instance": {
"databases": [
{
"character_set": "utf8",
"collate": "utf8_general_ci",
"name": "sampledb"
},
{
"name": "nextround"
}
],
"flavorRef": "http://localhost/v1.0/tenant/flavors/1",
"name": "json_rack_instance",
}
}
response = self.app.post_json("%s" % (self.instances_path), body=body,
headers={'X-Auth-Token': '123'})
print(response)
self.assertEqual(response.status_int, 201)

View File

@ -1,36 +0,0 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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 logging
import unittest
from reddwarf.common import exception
LOG = logging.getLogger(__name__)
class ExceptionTest(unittest.TestCase):
def test_exception_with_message_no_args(self):
test_message = "test message no args"
exc = exception.ReddwarfError(test_message)
self.assertEqual(str(exc), test_message)
def test_exception_with_message_args(self):
test_message = "test message %(one)s %(two)s"
test_args = {'one': 1, 'two': 2}
exc = exception.ReddwarfError(test_message, one=1, two=2)
self.assertEqual(str(exc), test_message % test_args)

View File

@ -1,99 +0,0 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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 logging
import time
import unittest
from reddwarf.common import utils
LOG = logging.getLogger(__name__)
class TestMethodInspector(unittest.TestCase):
def test_method_without_optional_args(self):
def foo(bar):
"""This is a method"""
method = utils.MethodInspector(foo)
self.assertEqual(method.required_args, ['bar'])
self.assertEqual(method.optional_args, [])
def test_method_with_optional_args(self):
def foo(bar, baz=1):
"""This is a method"""
method = utils.MethodInspector(foo)
self.assertEqual(method.required_args, ['bar'])
self.assertEqual(method.optional_args, [('baz', 1)])
def test_instance_method_with_optional_args(self):
class Foo():
def bar(self, baz, qux=2):
"""This is a method"""
method = utils.MethodInspector(Foo().bar)
self.assertEqual(method.required_args, ['baz'])
self.assertEqual(method.optional_args, [('qux', 2)])
def test_method_without_args(self):
def foo():
"""This is a method"""
method = utils.MethodInspector(foo)
self.assertEqual(method.required_args, [])
self.assertEqual(method.optional_args, [])
def test_instance_method_without_args(self):
class Foo():
def bar(self):
"""This is a method"""
method = utils.MethodInspector(Foo().bar)
self.assertEqual(method.required_args, [])
self.assertEqual(method.optional_args, [])
def test_method_str(self):
class Foo():
def bar(self, baz, qux=None):
"""This is a method"""
method = utils.MethodInspector(Foo().bar)
self.assertEqual(str(method), "bar baz=<baz> [qux=<qux>]")
class StringifyExcludeTest(unittest.TestCase):
def test_empty_stringify_keys(self):
self.assertEqual(utils.stringify_keys(None), None)
def test_empty_exclude(self):
self.assertEqual(utils.exclude(None), None)
def test_exclude_keys(self):
exclude_keys = ['one']
key_values = {'one': 1, 'two': 2}
new_keys = utils.exclude(key_values, *exclude_keys)
self.assertEqual(len(new_keys), 1)
self.assertEqual(new_keys, {'two': 2})

View File

@ -1,320 +0,0 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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.
""" Taken from melange. """
import routes
import webob
import webob.exc
import webtest
from reddwarf.common import wsgi
from reddwarf import tests
class StubApp(object):
def __init__(self):
self.called = False
def __call__(self, environ, start_response):
self.environ = environ
self.start_response = start_response
self.called = True
class StubUrlMap(StubApp, dict):
def __init__(self, dictionary):
self.update(dictionary)
super(StubUrlMap, self).__init__()
class VersionedURLMapTest(tests.BaseTest):
def setUp(self):
self.v1_app = StubApp()
self.v2_app = StubApp()
self.root_app = StubApp()
self.urlmap = StubUrlMap({'/v2.0': self.v2_app,
'/v1.0': self.v1_app,
'/': self.root_app})
self.versioned_urlmap = wsgi.VersionedURLMap(self.urlmap)
super(VersionedURLMapTest, self).setUp()
def test_chooses_app_based_on_accept_version(self):
environ = {'HTTP_ACCEPT': "application/vnd.openstack.reddwarf+xml;"
"version=1.0",
'PATH_INFO': "/resource"}
self.versioned_urlmap(environ=environ, start_response=None)
self.assertTrue(self.v1_app.called)
def test_delegates_to_urlmapper_when_accept_header_is_absent(self):
self.versioned_urlmap(environ={'PATH_INFO': "/resource"},
start_response=None)
self.assertTrue(self.urlmap.called)
def test_delegates_to_urlmapper_for_std_accept_headers_with_version(self):
environ = {
'HTTP_ACCEPT': "application/json;version=1.0",
'PATH_INFO': "/resource",
}
self.versioned_urlmap(environ=environ, start_response=None)
self.assertTrue(self.urlmap.called)
def test_delegates_to_urlmapper_for_nonexistant_version_of_app(self):
environ = {
'HTTP_ACCEPT': "application/vnd.openstack.reddwarf+xml;"
"version=9.0", 'REQUEST_METHOD': "GET",
'PATH_INFO': "/resource.xml",
}
def assert_status(status, *args):
self.assertEqual(status, "406 Not Acceptable")
self.versioned_urlmap(environ=environ, start_response=assert_status)
def test_delegates_to_urlmapper_when_url_versioned(self):
environ = {
'HTTP_ACCEPT': "application/vnd.openstack.reddwarf+xml;"
"version=2.0",
'PATH_INFO': "/v1.0/resource",
}
self.versioned_urlmap(environ=environ, start_response=None)
self.assertTrue(self.urlmap.called)
class RequestTest(tests.BaseTest):
def test_content_type_from_accept_header(self):
request = wsgi.Request.blank('/tests/123')
request.headers["Accept"] = "application/xml"
result = request.best_match_content_type()
self.assertEqual(result, "application/xml")
request = wsgi.Request.blank('/tests/123')
request.headers["Accept"] = "application/json"
result = request.best_match_content_type()
self.assertEqual(result, "application/json")
request = wsgi.Request.blank('/tests/123')
request.headers["Accept"] = "application/xml, application/json"
result = request.best_match_content_type()
self.assertEqual(result, "application/json")
request = wsgi.Request.blank('/tests/123')
request.headers["Accept"] = \
"application/json; q=0.3, application/xml; q=0.9"
result = request.best_match_content_type()
self.assertEqual(result, "application/xml")
def test_content_type_from_accept_header_with_versioned_mimetype(self):
request = wsgi.Request.blank('/tests/123')
request.headers["Accept"] = \
"application/vnd.openstack.reddwarf+xml;version=66.0"
result = request.best_match_content_type()
self.assertEqual(result, "application/xml")
request = wsgi.Request.blank('/tests/123')
request.headers["Accept"] = \
"application/vnd.openstack.reddwarf+json;version=96.0"
result = request.best_match_content_type()
self.assertEqual(result, "application/json")
def test_content_type_from_query_extension(self):
request = wsgi.Request.blank('/tests/123.xml')
result = request.best_match_content_type()
self.assertEqual(result, "application/xml")
request = wsgi.Request.blank('/tests/123.json')
result = request.best_match_content_type()
self.assertEqual(result, "application/json")
request = wsgi.Request.blank('/tests/123.invalid')
result = request.best_match_content_type()
self.assertEqual(result, "application/json")
def test_content_type_accept_and_query_extension(self):
request = wsgi.Request.blank('/tests/123.xml')
request.headers["Accept"] = "application/json"
result = request.best_match_content_type()
self.assertEqual(result, "application/xml")
def test_content_type_accept_default(self):
request = wsgi.Request.blank('/tests/123.unsupported')
request.headers["Accept"] = "application/unsupported1"
result = request.best_match_content_type()
self.assertEqual(result, "application/json")
def test_accept_version_for_custom_mime_type(self):
environ = {'HTTP_ACCEPT': "application/vnd.openstack.reddwarf+xml;"
"version=1.0"}
request = wsgi.Request(environ=environ)
self.assertEqual(request.accept_version, "1.0")
def test_accept_version_from_first_custom_mime_type(self):
environ = {'HTTP_ACCEPT': "application/json;version=2.0, "
"application/vnd.openstack.reddwarf+xml;version=1.0, "
"application/vnd.openstack.reddwarf+json;version=4.0"}
request = wsgi.Request(environ=environ)
self.assertEqual(request.accept_version, "1.0")
def test_accept_version_is_none_for_standard_mime_type(self):
environ = {'HTTP_ACCEPT': "application/json;"
"version=1.0"}
request = wsgi.Request(environ=environ)
self.assertIsNone(request.accept_version)
def test_accept_version_is_none_for_invalid_mime_type(self):
environ = {'HTTP_ACCEPT': "glibberish;"
"version=1.0"}
request = wsgi.Request(environ=environ)
self.assertIsNone(request.accept_version)
def test_accept_version_none_when_mime_type_doesnt_specify_version(self):
environ = {'HTTP_ACCEPT': "application/vnd.openstack.reddwarf+xml"}
request = wsgi.Request(environ=environ)
self.assertIsNone(request.accept_version)
def test_accept_version_is_none_when_accept_header_is_absent(self):
request = wsgi.Request(environ={})
self.assertIsNone(request.accept_version)
def test_accept_version_is_none_for_mime_type_with_invalid_version(self):
environ = {'HTTP_ACCEPT': "application/vnd.openstack.reddwarf+xml;"
"version=foo.bar"}
request = wsgi.Request(environ=environ)
self.assertIsNone(request.accept_version)
def test_url_version_for_versioned_url(self):
request = wsgi.Request.blank("/v1.0/resource")
self.assertEqual(request.url_version, "1.0")
def test_url_version_for_non_versioned_url_is_none(self):
request = wsgi.Request.blank("/resource")
self.assertIsNone(request.url_version)
def test_request_params_returns_non_unicode_strings(self):
request = wsgi.Request.blank("/resource?x=y&a=b")
for key in request.params:
self.assertEqual(type(key), str)
class DummyApp(wsgi.Router):
def __init__(self):
mapper = routes.Mapper()
controller = StubController()
mapper.resource("resource", "/resources",
controller=controller.create_resource())
super(DummyApp, self).__init__(mapper)
class StubController(wsgi.Controller):
def index(self, request, format=None):
return {'fort': 'knox'}
class TestController(tests.BaseTest):
def test_response_content_type_matches_accept_header(self):
app = webtest.TestApp(DummyApp())
response = app.get("/resources", headers={'Accept': "application/xml"})
self.assertEqual(response.content_type, "application/xml")
self.assertEqual(response.xml.tag, "fort")
self.assertEqual(response.xml.text.strip(), "knox")
def test_response_content_type_matches_url_format_over_accept_header(self):
app = webtest.TestApp(DummyApp())
response = app.get("/resources.json",
headers={'Accept': "application/xml"})
self.assertEqual(response.content_type, "application/json")
self.assertEqual(response.json, {'fort': 'knox'})
def test_returns_404_if_action_not_implemented(self):
app = webtest.TestApp(DummyApp())
response = app.get("/resources/new", status='*')
self.assertEqual(response.status_int, 404)
class TestFault(tests.BaseTest):
def test_fault_wraps_webob_exception(self):
app = webtest.TestApp(wsgi.Fault(webob.exc.HTTPNotFound("some error")))
response = app.get("/", status="*")
self.assertEqual(response.status_int, 404)
self.assertEqual(response.content_type, "application/json")
self.assertEqual(response.json['NotFound'],
dict(code=404,
message="The resource could not be found.",
detail="some error"))
def test_fault_gives_back_xml(self):
app = webtest.TestApp(wsgi.Fault(
webob.exc.HTTPBadRequest("some error")))
response = app.get("/x.xml", status="*")
self.assertEqual(response.content_type, "application/xml")
self.assertEqual(response.xml.tag, 'BadRequest')
self.assertEqual(response.xml.attrib['code'], '400')
self.assertEqual(response.xml.find('detail').text.strip(),
'some error')
class TestResult(tests.BaseTest):
class TestData(object):
def data_for_json(self):
return {'foo': "bar", 'foo2': "bar2"}
def data_for_xml(self):
return {'foos': [{'foo': "bar"}, {'foo2': "bar2"}]}
def test_data_returns_back_input_data(self):
self.assertEqual(wsgi.Result("blah").data("application/json"), "blah")
self.assertEqual(wsgi.Result({'x': "blah"}).data("application/json"),
{'x': "blah"})
self.assertEqual(wsgi.Result(["x", "blah"]).data("application/xml"),
["x", "blah"])
def test_data_returns_json_specific_input_data(self):
self.assertEqual(wsgi.Result(self.TestData()).data("application/json"),
{'foo': "bar", 'foo2': "bar2"})
def test_data_returns_xml_specific_input_data(self):
self.assertEqual(wsgi.Result(self.TestData()).data("application/xml"),
{'foos': [{'foo': "bar"}, {'foo2': "bar2"}]})

View File

@ -6,6 +6,6 @@ mox
nose
nosexcover
openstack.nose_plugin
pep8=1.3.3
pep8==1.3.3
pylint
webtest

View File

@ -12,7 +12,6 @@ setenv = VIRTUAL_ENV={envdir}
deps = -r{toxinidir}/tools/pip-requires
-r{toxinidir}/tools/test-requires
setuptools_git>=0.4
commands = nosetests {posargs}
[tox:jenkins]
sitepackages = True