Merge "Validate image metadata attributes of Nova APIs"
diff --git a/tempest/api/identity/admin/v3/test_tokens.py b/tempest/api/identity/admin/v3/test_tokens.py
index 9629213..2d75d0a 100644
--- a/tempest/api/identity/admin/v3/test_tokens.py
+++ b/tempest/api/identity/admin/v3/test_tokens.py
@@ -33,15 +33,15 @@
         resp, user = self.client.create_user(
             u_name, description=u_desc, password=u_password,
             email=u_email)
-        self.assertTrue(resp['status'].startswith('2'))
+        self.assertEqual(201, resp.status)
         self.addCleanup(self.client.delete_user, user['id'])
         # Perform Authentication
         resp, body = self.token.auth(user['id'], u_password)
-        self.assertEqual(resp['status'], '201')
+        self.assertEqual(201, resp.status)
         subject_token = resp['x-subject-token']
         # Perform GET Token
         resp, token_details = self.client.get_token(subject_token)
-        self.assertEqual(resp['status'], '200')
+        self.assertEqual(200, resp.status)
         self.assertEqual(resp['x-subject-token'], subject_token)
         self.assertEqual(token_details['user']['id'], user['id'])
         self.assertEqual(token_details['user']['name'], u_name)
@@ -50,6 +50,85 @@
         self.assertRaises(exceptions.NotFound, self.client.get_token,
                           subject_token)
 
+    @attr(type='gate')
+    def test_rescope_token(self):
+        """An unscoped token can be requested, that token can be used to
+           request a scoped token.
+        """
+
+        # Create a user.
+        user_name = data_utils.rand_name(name='user-')
+        user_password = data_utils.rand_name(name='pass-')
+        resp, user = self.client.create_user(user_name, password=user_password)
+        self.assertEqual(201, resp.status)
+        self.addCleanup(self.client.delete_user, user['id'])
+
+        # Create a project.
+        project_name = data_utils.rand_name(name='project-')
+        resp, project = self.client.create_project(project_name)
+        self.assertEqual(201, resp.status)
+        self.addCleanup(self.client.delete_project, project['id'])
+
+        # Create a role
+        role_name = data_utils.rand_name(name='role-')
+        resp, role = self.client.create_role(role_name)
+        self.assertEqual(201, resp.status)
+        self.addCleanup(self.client.delete_role, role['id'])
+
+        # Grant the user the role on the project.
+        resp, _ = self.client.assign_user_role(project['id'], user['id'],
+                                               role['id'])
+        self.assertEqual(204, resp.status)
+
+        # Get an unscoped token.
+        resp, token_auth = self.token.auth(user=user['id'],
+                                           password=user_password)
+        self.assertEqual(201, resp.status)
+
+        token_id = resp['x-subject-token']
+        orig_expires_at = token_auth['token']['expires_at']
+        orig_issued_at = token_auth['token']['issued_at']
+        orig_user = token_auth['token']['user']
+
+        self.assertIsInstance(token_auth['token']['expires_at'], unicode)
+        self.assertIsInstance(token_auth['token']['issued_at'], unicode)
+        self.assertEqual(['password'], token_auth['token']['methods'])
+        self.assertEqual(user['id'], token_auth['token']['user']['id'])
+        self.assertEqual(user['name'], token_auth['token']['user']['name'])
+        self.assertEqual('default',
+                         token_auth['token']['user']['domain']['id'])
+        self.assertEqual('Default',
+                         token_auth['token']['user']['domain']['name'])
+        self.assertNotIn('catalog', token_auth['token'])
+        self.assertNotIn('project', token_auth['token'])
+        self.assertNotIn('roles', token_auth['token'])
+
+        # Use the unscoped token to get a scoped token.
+        resp, token_auth = self.token.auth(token=token_id, tenant=project_name,
+                                           domain='Default')
+        self.assertEqual(201, resp.status)
+
+        self.assertEqual(orig_expires_at, token_auth['token']['expires_at'],
+                         'Expiration time should match original token')
+        self.assertIsInstance(token_auth['token']['issued_at'], unicode)
+        self.assertNotEqual(orig_issued_at, token_auth['token']['issued_at'])
+        self.assertEqual(set(['password', 'token']),
+                         set(token_auth['token']['methods']))
+        self.assertEqual(orig_user, token_auth['token']['user'],
+                         'User should match original token')
+        self.assertIsInstance(token_auth['token']['catalog'], list)
+        self.assertEqual(project['id'],
+                         token_auth['token']['project']['id'])
+        self.assertEqual(project['name'],
+                         token_auth['token']['project']['name'])
+        self.assertEqual('default',
+                         token_auth['token']['project']['domain']['id'])
+        self.assertEqual('Default',
+                         token_auth['token']['project']['domain']['name'])
+        self.assertEqual(1, len(token_auth['token']['roles']))
+        self.assertEqual(role['id'], token_auth['token']['roles'][0]['id'])
+        self.assertEqual(role['name'], token_auth['token']['roles'][0]['name'])
+
 
 class TokensV3TestXML(TokensV3TestJSON):
     _interface = 'xml'
diff --git a/tempest/api/image/v1/test_images.py b/tempest/api/image/v1/test_images.py
index 517123d..8466c7b 100644
--- a/tempest/api/image/v1/test_images.py
+++ b/tempest/api/image/v1/test_images.py
@@ -109,6 +109,7 @@
     """
 
     @classmethod
+    @test.safe_setup
     def setUpClass(cls):
         super(ListImagesTest, cls).setUpClass()
         # We add a few images here to test the listing functionality of
@@ -244,6 +245,7 @@
 
 class ListSnapshotImagesTest(base.BaseV1ImageTest):
     @classmethod
+    @test.safe_setup
     def setUpClass(cls):
         super(ListSnapshotImagesTest, cls).setUpClass()
         if not CONF.compute_feature_enabled.api_v3:
@@ -268,7 +270,7 @@
 
     @classmethod
     def tearDownClass(cls):
-        for server in cls.servers:
+        for server in getattr(cls, "servers", []):
             cls.servers_client.delete_server(server['id'])
         super(ListSnapshotImagesTest, cls).tearDownClass()
 
diff --git a/tempest/api/image/v2/test_images.py b/tempest/api/image/v2/test_images.py
index abde8f7..2592409 100644
--- a/tempest/api/image/v2/test_images.py
+++ b/tempest/api/image/v2/test_images.py
@@ -135,6 +135,7 @@
     """
 
     @classmethod
+    @test.safe_setup
     def setUpClass(cls):
         super(ListImagesTest, cls).setUpClass()
         # We add a few images here to test the listing functionality of
diff --git a/tempest/api/network/admin/test_dhcp_agent_scheduler.py b/tempest/api/network/admin/test_dhcp_agent_scheduler.py
index 0e601d1..13ae1c0 100644
--- a/tempest/api/network/admin/test_dhcp_agent_scheduler.py
+++ b/tempest/api/network/admin/test_dhcp_agent_scheduler.py
@@ -59,17 +59,31 @@
         return network_id in network_ids
 
     @test.attr(type='smoke')
-    def test_remove_network_from_dhcp_agent(self):
+    def test_add_remove_network_from_dhcp_agent(self):
         # The agent is now bound to the network, we can free the port
         self.client.delete_port(self.port['id'])
         self.ports.remove(self.port)
-        resp, body = self.admin_client.list_dhcp_agent_hosting_network(
-            self.network['id'])
+        agent = dict()
+        agent['agent_type'] = None
+        resp, body = self.admin_client.list_agents()
         agents = body['agents']
-        self.assertIsNotNone(agents)
-        # Get an agent.
-        agent = agents[0]
-        network_id = self.network['id']
+        for a in agents:
+            if a['agent_type'] == 'DHCP agent':
+                agent = a
+                break
+        self.assertEqual(agent['agent_type'], 'DHCP agent', 'Could not find '
+                         'DHCP agent in agent list though dhcp_agent_scheduler'
+                         ' is enabled.')
+        network = self.create_network()
+        network_id = network['id']
+        if self._check_network_in_dhcp_agent(network_id, agent):
+            self._remove_network_from_dhcp_agent(network_id, agent)
+            self._add_dhcp_agent_to_network(network_id, agent)
+        else:
+            self._add_dhcp_agent_to_network(network_id, agent)
+            self._remove_network_from_dhcp_agent(network_id, agent)
+
+    def _remove_network_from_dhcp_agent(self, network_id, agent):
         resp, body = self.admin_client.remove_network_from_dhcp_agent(
             agent_id=agent['id'],
             network_id=network_id)
@@ -77,6 +91,13 @@
         self.assertFalse(self._check_network_in_dhcp_agent(
             network_id, agent))
 
+    def _add_dhcp_agent_to_network(self, network_id, agent):
+        resp, body = self.admin_client.add_dhcp_agent_to_network(
+            agent['id'], network_id)
+        self.assertEqual(resp['status'], '201')
+        self.assertTrue(self._check_network_in_dhcp_agent(
+            network_id, agent))
+
 
 class DHCPAgentSchedulersTestXML(DHCPAgentSchedulersTestJSON):
     _interface = 'xml'
diff --git a/tempest/api_schema/compute/hypervisors.py b/tempest/api_schema/compute/hypervisors.py
index 7de5147..630901e 100644
--- a/tempest/api_schema/compute/hypervisors.py
+++ b/tempest/api_schema/compute/hypervisors.py
@@ -12,6 +12,8 @@
 #    License for the specific language governing permissions and limitations
 #    under the License.
 
+import copy
+
 hypervisor_statistics = {
     'status_code': [200],
     'response_body': {
@@ -147,3 +149,49 @@
         'required': ['hypervisor']
     }
 }
+
+common_hypervisors_detail = {
+    'status_code': [200],
+    'response_body': {
+        'type': 'object',
+        'properties': {
+            'hypervisors': {
+                'type': 'array',
+                'items': {
+                    'type': 'object',
+                    'properties': {
+                        'id': {'type': ['integer', 'string']},
+                        'hypervisor_hostname': {'type': 'string'}
+                    },
+                    'required': ['id', 'hypervisor_hostname']
+                }
+            }
+        },
+        'required': ['hypervisors']
+    }
+}
+
+common_hypervisors_info = {
+    'status_code': [200],
+    'response_body': {
+        'type': 'object',
+        'properties': {
+            'hypervisor': {
+                'type': 'object',
+                'properties': {
+                    'id': {'type': ['integer', 'string']},
+                    'hypervisor_hostname': {'type': 'string'},
+                },
+                'required': ['id', 'hypervisor_hostname']
+            }
+        },
+        'required': ['hypervisor']
+    }
+}
+
+
+hypervisor_uptime = copy.deepcopy(common_hypervisors_info)
+hypervisor_uptime['response_body']['properties']['hypervisor'][
+    'properties']['uptime'] = {'type': 'string'}
+hypervisor_uptime['response_body']['properties']['hypervisor'][
+    'required'] = ['id', 'hypervisor_hostname', 'uptime']
diff --git a/tempest/api_schema/compute/keypairs.py b/tempest/api_schema/compute/keypairs.py
index 8973c02..b8f905f 100644
--- a/tempest/api_schema/compute/keypairs.py
+++ b/tempest/api_schema/compute/keypairs.py
@@ -39,3 +39,27 @@
         'required': ['keypairs']
     }
 }
+
+create_keypair = {
+    'type': 'object',
+    'properties': {
+        'keypair': {
+            'type': 'object',
+            'properties': {
+                'fingerprint': {'type': 'string'},
+                'name': {'type': 'string'},
+                'public_key': {'type': 'string'},
+                # NOTE: Now the type of 'user_id' is integer, but here
+                # allows 'string' also because we will be able to change
+                # it to 'uuid' in the future.
+                'user_id': {'type': ['integer', 'string']},
+                'private_key': {'type': 'string'}
+            },
+            # When create keypair API is being called with 'Public key'
+            # (Importing keypair) then, response body does not contain
+            # 'private_key' So it is not defined as 'required'
+            'required': ['fingerprint', 'name', 'public_key', 'user_id']
+        }
+    },
+    'required': ['keypair']
+}
diff --git a/tempest/api_schema/compute/v2/hypervisors.py b/tempest/api_schema/compute/v2/hypervisors.py
new file mode 100644
index 0000000..6bb43a7
--- /dev/null
+++ b/tempest/api_schema/compute/v2/hypervisors.py
@@ -0,0 +1,37 @@
+# Copyright 2014 NEC Corporation.  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
+from tempest.api_schema.compute import hypervisors
+
+hypervisors_servers = copy.deepcopy(hypervisors.common_hypervisors_detail)
+
+# Defining extra attributes for V3 show hypervisor schema
+hypervisors_servers['response_body']['properties']['hypervisors']['items'][
+    'properties']['servers'] = {
+        'type': 'array',
+        'items': {
+            'type': 'object',
+            'properties': {
+                # NOTE: Now the type of 'id' is integer,
+                # but here allows 'string' also because we
+                # will be able to change it to 'uuid' in
+                # the future.
+                'id': {'type': ['integer', 'string']},
+                'name': {'type': 'string'}
+            }
+        }
+    }
+# In V2 API, if there is no servers (VM) on the Hypervisor host then 'servers'
+# attribute will not be present in response body So it is not 'required'.
diff --git a/tempest/api_schema/compute/v2/keypairs.py b/tempest/api_schema/compute/v2/keypairs.py
index 3225b0d..9a025c3 100644
--- a/tempest/api_schema/compute/v2/keypairs.py
+++ b/tempest/api_schema/compute/v2/keypairs.py
@@ -12,6 +12,8 @@
 #    License for the specific language governing permissions and limitations
 #    under the License.
 
+from tempest.api_schema.compute import keypairs
+
 get_keypair = {
     'status_code': [200],
     'response_body': {
@@ -45,3 +47,12 @@
         'required': ['keypair']
     }
 }
+
+create_keypair = {
+    'status_code': [200],
+    'response_body': keypairs.create_keypair
+}
+
+delete_keypair = {
+    'status_code': [202],
+}
diff --git a/tempest/api_schema/compute/v3/hypervisors.py b/tempest/api_schema/compute/v3/hypervisors.py
index 6eb0072..aa31827 100644
--- a/tempest/api_schema/compute/v3/hypervisors.py
+++ b/tempest/api_schema/compute/v3/hypervisors.py
@@ -25,3 +25,26 @@
 # Defining extra attributes for V3 show hypervisor schema
 show_hypervisor['response_body']['properties']['hypervisor']['properties'][
     'os-pci:pci_stats'] = {'type': 'array'}
+
+hypervisors_servers = copy.deepcopy(hypervisors.common_hypervisors_info)
+
+# Defining extra attributes for V3 show hypervisor schema
+hypervisors_servers['response_body']['properties']['hypervisor']['properties'][
+    'servers'] = {
+        'type': 'array',
+        'items': {
+            'type': 'object',
+            'properties': {
+                # NOTE: Now the type of 'id' is integer,
+                # but here allows 'string' also because we
+                # will be able to change it to 'uuid' in
+                # the future.
+                'id': {'type': ['integer', 'string']},
+                'name': {'type': 'string'}
+            }
+        }
+    }
+# V3 API response body always contains the 'servers' attribute even there
+# is no server (VM) are present on Hypervisor host.
+hypervisors_servers['response_body']['properties']['hypervisor'][
+    'required'] = ['id', 'hypervisor_hostname', 'servers']
diff --git a/tempest/api_schema/compute/v3/keypairs.py b/tempest/api_schema/compute/v3/keypairs.py
index 0197c84..de5f4ba 100644
--- a/tempest/api_schema/compute/v3/keypairs.py
+++ b/tempest/api_schema/compute/v3/keypairs.py
@@ -12,6 +12,8 @@
 #    License for the specific language governing permissions and limitations
 #    under the License.
 
+from tempest.api_schema.compute import keypairs
+
 get_keypair = {
     'status_code': [200],
     'response_body': {
@@ -30,3 +32,12 @@
         'required': ['keypair']
     }
 }
+
+create_keypair = {
+    'status_code': [201],
+    'response_body': keypairs.create_keypair
+}
+
+delete_keypair = {
+    'status_code': [204],
+}
diff --git a/tempest/services/compute/json/hypervisor_client.py b/tempest/services/compute/json/hypervisor_client.py
index 89a7961..30228b3 100644
--- a/tempest/services/compute/json/hypervisor_client.py
+++ b/tempest/services/compute/json/hypervisor_client.py
@@ -16,6 +16,7 @@
 import json
 
 from tempest.api_schema.compute import hypervisors as common_schema
+from tempest.api_schema.compute.v2 import hypervisors as v2schema
 from tempest.common import rest_client
 from tempest import config
 
@@ -32,6 +33,8 @@
         """List hypervisors information."""
         resp, body = self.get('os-hypervisors')
         body = json.loads(body)
+        self.validate_response(common_schema.common_hypervisors_detail,
+                               resp, body)
         return resp, body['hypervisors']
 
     def get_hypervisor_list_details(self):
@@ -54,6 +57,7 @@
         """List instances belonging to the specified hypervisor."""
         resp, body = self.get('os-hypervisors/%s/servers' % hyper_name)
         body = json.loads(body)
+        self.validate_response(v2schema.hypervisors_servers, resp, body)
         return resp, body['hypervisors']
 
     def get_hypervisor_stats(self):
@@ -67,10 +71,13 @@
         """Display the uptime of the specified hypervisor."""
         resp, body = self.get('os-hypervisors/%s/uptime' % hyper_id)
         body = json.loads(body)
+        self.validate_response(common_schema.hypervisor_uptime, resp, body)
         return resp, body['hypervisor']
 
     def search_hypervisor(self, hyper_name):
         """Search specified hypervisor."""
         resp, body = self.get('os-hypervisors/%s/search' % hyper_name)
         body = json.loads(body)
+        self.validate_response(common_schema.common_hypervisors_detail,
+                               resp, body)
         return resp, body['hypervisors']
diff --git a/tempest/services/compute/json/keypairs_client.py b/tempest/services/compute/json/keypairs_client.py
index 71f235d..be93789 100644
--- a/tempest/services/compute/json/keypairs_client.py
+++ b/tempest/services/compute/json/keypairs_client.py
@@ -53,7 +53,10 @@
         post_body = json.dumps(post_body)
         resp, body = self.post("os-keypairs", body=post_body)
         body = json.loads(body)
+        self.validate_response(schema.create_keypair, resp, body)
         return resp, body['keypair']
 
     def delete_keypair(self, key_name):
-        return self.delete("os-keypairs/%s" % str(key_name))
+        resp, body = self.delete("os-keypairs/%s" % str(key_name))
+        self.validate_response(schema.delete_keypair, resp, body)
+        return resp, body
diff --git a/tempest/services/compute/v3/json/hypervisor_client.py b/tempest/services/compute/v3/json/hypervisor_client.py
index 0ba6ebf..51468c9 100644
--- a/tempest/services/compute/v3/json/hypervisor_client.py
+++ b/tempest/services/compute/v3/json/hypervisor_client.py
@@ -33,6 +33,8 @@
         """List hypervisors information."""
         resp, body = self.get('os-hypervisors')
         body = json.loads(body)
+        self.validate_response(common_schema.common_hypervisors_detail,
+                               resp, body)
         return resp, body['hypervisors']
 
     def get_hypervisor_list_details(self):
@@ -53,6 +55,7 @@
         """List instances belonging to the specified hypervisor."""
         resp, body = self.get('os-hypervisors/%s/servers' % hyper_name)
         body = json.loads(body)
+        self.validate_response(v3schema.hypervisors_servers, resp, body)
         return resp, body['hypervisor']
 
     def get_hypervisor_stats(self):
@@ -66,10 +69,13 @@
         """Display the uptime of the specified hypervisor."""
         resp, body = self.get('os-hypervisors/%s/uptime' % hyper_id)
         body = json.loads(body)
+        self.validate_response(common_schema.hypervisor_uptime, resp, body)
         return resp, body['hypervisor']
 
     def search_hypervisor(self, hyper_name):
         """Search specified hypervisor."""
         resp, body = self.get('os-hypervisors/search?query=%s' % hyper_name)
         body = json.loads(body)
+        self.validate_response(common_schema.common_hypervisors_detail,
+                               resp, body)
         return resp, body['hypervisors']
diff --git a/tempest/services/compute/v3/json/keypairs_client.py b/tempest/services/compute/v3/json/keypairs_client.py
index d315bc4..f090d7d 100644
--- a/tempest/services/compute/v3/json/keypairs_client.py
+++ b/tempest/services/compute/v3/json/keypairs_client.py
@@ -53,7 +53,10 @@
         post_body = json.dumps(post_body)
         resp, body = self.post("keypairs", body=post_body)
         body = json.loads(body)
+        self.validate_response(schema.create_keypair, resp, body)
         return resp, body['keypair']
 
     def delete_keypair(self, key_name):
-        return self.delete("keypairs/%s" % str(key_name))
+        resp, body = self.delete("keypairs/%s" % str(key_name))
+        self.validate_response(schema.delete_keypair, resp, body)
+        return resp, body
diff --git a/tempest/services/identity/v3/json/identity_client.py b/tempest/services/identity/v3/json/identity_client.py
index 35d8aa0..4b530f1 100644
--- a/tempest/services/identity/v3/json/identity_client.py
+++ b/tempest/services/identity/v3/json/identity_client.py
@@ -459,16 +459,20 @@
 
         self.auth_url = auth_url
 
-    def auth(self, user, password, tenant=None, user_type='id', domain=None):
+    def auth(self, user=None, password=None, tenant=None, user_type='id',
+             domain=None, token=None):
         """
         :param user: user id or name, as specified in user_type
         :param domain: the user and tenant domain
+        :param token: a token to re-scope.
 
         Accepts different combinations of credentials. Restrictions:
         - tenant and domain are only name (no id)
         - user domain and tenant domain are assumed identical
         - domain scope is not supported here
         Sample sample valid combinations:
+        - token
+        - token, tenant, domain
         - user_id, password
         - username, password, domain
         - username, password, tenant, domain
@@ -477,23 +481,32 @@
         creds = {
             'auth': {
                 'identity': {
-                    'methods': ['password'],
-                    'password': {
-                        'user': {
-                            'password': password,
-                        }
-                    }
+                    'methods': [],
                 }
             }
         }
-        if user_type == 'id':
-            creds['auth']['identity']['password']['user']['id'] = user
-        else:
-            creds['auth']['identity']['password']['user']['name'] = user
-        if domain is not None:
-            _domain = dict(name=domain)
-            creds['auth']['identity']['password']['user']['domain'] = _domain
+        id_obj = creds['auth']['identity']
+        if token:
+            id_obj['methods'].append('token')
+            id_obj['token'] = {
+                'id': token
+            }
+        if user and password:
+            id_obj['methods'].append('password')
+            id_obj['password'] = {
+                'user': {
+                    'password': password,
+                }
+            }
+            if user_type == 'id':
+                id_obj['password']['user']['id'] = user
+            else:
+                id_obj['password']['user']['name'] = user
+            if domain is not None:
+                _domain = dict(name=domain)
+                id_obj['password']['user']['domain'] = _domain
         if tenant is not None:
+            _domain = dict(name=domain)
             project = dict(name=tenant, domain=_domain)
             scope = dict(project=project)
             creds['auth']['scope'] = scope
diff --git a/tempest/services/identity/v3/xml/identity_client.py b/tempest/services/identity/v3/xml/identity_client.py
index ffeb979..c49f361 100644
--- a/tempest/services/identity/v3/xml/identity_client.py
+++ b/tempest/services/identity/v3/xml/identity_client.py
@@ -453,43 +453,61 @@
 
         self.auth_url = auth_url
 
-    def auth(self, user, password, tenant=None, user_type='id', domain=None):
+    def auth(self, user=None, password=None, tenant=None, user_type='id',
+             domain=None, token=None):
         """
         :param user: user id or name, as specified in user_type
+        :param domain: the user and tenant domain
+        :param token: a token to re-scope.
 
         Accepts different combinations of credentials. Restrictions:
         - tenant and domain are only name (no id)
         - user domain and tenant domain are assumed identical
+        - domain scope is not supported here
         Sample sample valid combinations:
+        - token
+        - token, tenant, domain
         - user_id, password
         - username, password, domain
         - username, password, tenant, domain
         Validation is left to the server side.
         """
-        if user_type == 'id':
-            _user = common.Element('user', id=user, password=password)
-        else:
-            _user = common.Element('user', name=user, password=password)
-        if domain is not None:
-            _domain = common.Element('domain', name=domain)
-            _user.append(_domain)
 
-        password = common.Element('password')
-        password.append(_user)
-
-        method = common.Element('method')
-        method.append(common.Text('password'))
         methods = common.Element('methods')
-        methods.append(method)
         identity = common.Element('identity')
+
+        if token:
+            method = common.Element('method')
+            method.append(common.Text('token'))
+            methods.append(method)
+
+            token = common.Element('token', id=token)
+            identity.append(token)
+
+        if user and password:
+            if user_type == 'id':
+                _user = common.Element('user', id=user, password=password)
+            else:
+                _user = common.Element('user', name=user, password=password)
+            if domain is not None:
+                _domain = common.Element('domain', name=domain)
+                _user.append(_domain)
+
+            password = common.Element('password')
+            password.append(_user)
+            method = common.Element('method')
+            method.append(common.Text('password'))
+            methods.append(method)
+            identity.append(password)
+
         identity.append(methods)
-        identity.append(password)
 
         auth = common.Element('auth')
         auth.append(identity)
 
         if tenant is not None:
             project = common.Element('project', name=tenant)
+            _domain = common.Element('domain', name=domain)
             project.append(_domain)
             scope = common.Element('scope')
             scope.append(project)
diff --git a/tempest/services/network/json/network_client.py b/tempest/services/network/json/network_client.py
index e5309ff..f9dd8ef 100644
--- a/tempest/services/network/json/network_client.py
+++ b/tempest/services/network/json/network_client.py
@@ -300,3 +300,11 @@
         resp, body = self.get(uri)
         body = json.loads(body)
         return resp, body
+
+    def add_dhcp_agent_to_network(self, agent_id, network_id):
+        post_body = {'network_id': network_id}
+        body = json.dumps(post_body)
+        uri = '%s/agents/%s/dhcp-networks' % (self.uri_prefix, agent_id)
+        resp, body = self.post(uri, body)
+        body = json.loads(body)
+        return resp, body
diff --git a/tempest/services/network/xml/network_client.py b/tempest/services/network/xml/network_client.py
index 26dc672..0945b09 100644
--- a/tempest/services/network/xml/network_client.py
+++ b/tempest/services/network/xml/network_client.py
@@ -250,6 +250,13 @@
         body = _root_tag_fetcher_and_xml_to_json_parse(body)
         return resp, body
 
+    def add_dhcp_agent_to_network(self, agent_id, network_id):
+        uri = '%s/agents/%s/dhcp-networks' % (self.uri_prefix, agent_id)
+        network = common.Element("network_id", network_id)
+        resp, body = self.post(uri, str(common.Document(network)))
+        body = _root_tag_fetcher_and_xml_to_json_parse(body)
+        return resp, body
+
 
 def _root_tag_fetcher_and_xml_to_json_parse(xml_returned_body):
     body = ET.fromstring(xml_returned_body)
diff --git a/tempest/tests/common/test_debug.py b/tempest/tests/common/test_debug.py
new file mode 100644
index 0000000..cd9936c
--- /dev/null
+++ b/tempest/tests/common/test_debug.py
@@ -0,0 +1,122 @@
+# Copyright 2014 NEC Corporation.
+# 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 mock
+
+from tempest.common import debug
+from tempest import config
+from tempest.openstack.common.fixture import mockpatch
+from tempest import test
+from tempest.tests import base
+from tempest.tests import fake_config
+
+
+class TestDebug(base.TestCase):
+
+    def setUp(self):
+        super(TestDebug, self).setUp()
+        self.useFixture(fake_config.ConfigFixture())
+        self.stubs.Set(config, 'TempestConfigPrivate', fake_config.FakePrivate)
+
+        common_pre = 'tempest.common.commands'
+        self.ip_addr_raw_mock = self.patch(common_pre + '.ip_addr_raw')
+        self.ip_route_raw_mock = self.patch(common_pre + '.ip_route_raw')
+        self.iptables_raw_mock = self.patch(common_pre + '.iptables_raw')
+        self.ip_ns_list_mock = self.patch(common_pre + '.ip_ns_list')
+        self.ip_ns_addr_mock = self.patch(common_pre + '.ip_ns_addr')
+        self.ip_ns_route_mock = self.patch(common_pre + '.ip_ns_route')
+        self.iptables_ns_mock = self.patch(common_pre + '.iptables_ns')
+        self.ovs_db_dump_mock = self.patch(common_pre + '.ovs_db_dump')
+
+        self.log_mock = self.patch('tempest.common.debug.LOG')
+
+    def test_log_ip_ns_debug_disabled(self):
+        self.useFixture(mockpatch.PatchObject(test.CONF.debug,
+                                              'enable', False))
+        debug.log_ip_ns()
+        self.assertFalse(self.ip_addr_raw_mock.called)
+        self.assertFalse(self.log_mock.info.called)
+
+    def test_log_ip_ns_debug_enabled(self):
+        self.useFixture(mockpatch.PatchObject(test.CONF.debug,
+                                              'enable', True))
+
+        tables = ['filter', 'nat', 'mangle']
+        self.ip_ns_list_mock.return_value = [1, 2]
+
+        debug.log_ip_ns()
+        self.ip_addr_raw_mock.assert_called_with()
+        self.assertTrue(self.log_mock.info.called)
+        self.ip_route_raw_mock.assert_called_with()
+        self.assertEqual(len(tables), self.iptables_raw_mock.call_count)
+        for table in tables:
+            self.assertIn(mock.call(table),
+                          self.iptables_raw_mock.call_args_list)
+
+        self.ip_ns_list_mock.assert_called_with()
+        self.assertEqual(len(self.ip_ns_list_mock.return_value),
+                         self.ip_ns_addr_mock.call_count)
+        self.assertEqual(len(self.ip_ns_list_mock.return_value),
+                         self.ip_ns_route_mock.call_count)
+        for ns in self.ip_ns_list_mock.return_value:
+            self.assertIn(mock.call(ns),
+                          self.ip_ns_addr_mock.call_args_list)
+            self.assertIn(mock.call(ns),
+                          self.ip_ns_route_mock.call_args_list)
+
+        self.assertEqual(len(tables) * len(self.ip_ns_list_mock.return_value),
+                         self.iptables_ns_mock.call_count)
+        for ns in self.ip_ns_list_mock.return_value:
+            for table in tables:
+                self.assertIn(mock.call(ns, table),
+                              self.iptables_ns_mock.call_args_list)
+
+    def test_log_ovs_db_debug_disabled(self):
+        self.useFixture(mockpatch.PatchObject(test.CONF.debug,
+                                              'enable', False))
+        self.useFixture(mockpatch.PatchObject(test.CONF.service_available,
+                                              'neutron', False))
+        debug.log_ovs_db()
+        self.assertFalse(self.ovs_db_dump_mock.called)
+
+        self.useFixture(mockpatch.PatchObject(test.CONF.debug,
+                                              'enable', True))
+        self.useFixture(mockpatch.PatchObject(test.CONF.service_available,
+                                              'neutron', False))
+        debug.log_ovs_db()
+        self.assertFalse(self.ovs_db_dump_mock.called)
+
+        self.useFixture(mockpatch.PatchObject(test.CONF.debug,
+                                              'enable', False))
+        self.useFixture(mockpatch.PatchObject(test.CONF.service_available,
+                                              'neutron', True))
+        debug.log_ovs_db()
+        self.assertFalse(self.ovs_db_dump_mock.called)
+
+    def test_log_ovs_db_debug_enabled(self):
+        self.useFixture(mockpatch.PatchObject(test.CONF.debug,
+                                              'enable', True))
+        self.useFixture(mockpatch.PatchObject(test.CONF.service_available,
+                                              'neutron', True))
+        debug.log_ovs_db()
+        self.ovs_db_dump_mock.assert_called_with()
+
+    def test_log_net_debug(self):
+        self.log_ip_ns_mock = self.patch('tempest.common.debug.log_ip_ns')
+        self.log_ovs_db_mock = self.patch('tempest.common.debug.log_ovs_db')
+
+        debug.log_net_debug()
+        self.log_ip_ns_mock.assert_called_with()
+        self.log_ovs_db_mock.assert_called_with()
diff --git a/tempest/tests/test_rest_client.py b/tempest/tests/test_rest_client.py
index b54b0c2..cfbb37d 100644
--- a/tempest/tests/test_rest_client.py
+++ b/tempest/tests/test_rest_client.py
@@ -384,3 +384,63 @@
         self.assertRaises(NotImplementedError,
                           self.rest_client.wait_for_resource_deletion,
                           '1234')
+
+
+class TestNegativeRestClient(BaseRestClientTestClass):
+
+    def setUp(self):
+        self.fake_http = fake_http.fake_httplib2()
+        super(TestNegativeRestClient, self).setUp()
+        self.negative_rest_client = rest_client.NegativeRestClient(
+            fake_auth_provider.FakeAuthProvider())
+        self.useFixture(mockpatch.PatchObject(self.negative_rest_client,
+                                              '_log_request'))
+
+    def test_post(self):
+        __, return_dict = self.negative_rest_client.send_request('POST',
+                                                                 self.url,
+                                                                 [], {})
+        self.assertEqual('POST', return_dict['method'])
+
+    def test_get(self):
+        __, return_dict = self.negative_rest_client.send_request('GET',
+                                                                 self.url,
+                                                                 [])
+        self.assertEqual('GET', return_dict['method'])
+
+    def test_delete(self):
+        __, return_dict = self.negative_rest_client.send_request('DELETE',
+                                                                 self.url,
+                                                                 [])
+        self.assertEqual('DELETE', return_dict['method'])
+
+    def test_patch(self):
+        __, return_dict = self.negative_rest_client.send_request('PATCH',
+                                                                 self.url,
+                                                                 [], {})
+        self.assertEqual('PATCH', return_dict['method'])
+
+    def test_put(self):
+        __, return_dict = self.negative_rest_client.send_request('PUT',
+                                                                 self.url,
+                                                                 [], {})
+        self.assertEqual('PUT', return_dict['method'])
+
+    def test_head(self):
+        self.useFixture(mockpatch.PatchObject(self.negative_rest_client,
+                                              'response_checker'))
+        __, return_dict = self.negative_rest_client.send_request('HEAD',
+                                                                 self.url,
+                                                                 [])
+        self.assertEqual('HEAD', return_dict['method'])
+
+    def test_copy(self):
+        __, return_dict = self.negative_rest_client.send_request('COPY',
+                                                                 self.url,
+                                                                 [])
+        self.assertEqual('COPY', return_dict['method'])
+
+    def test_other(self):
+        self.assertRaises(AssertionError,
+                          self.negative_rest_client.send_request,
+                          'OTHER', self.url, [])