# 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 oslo_config import cfg
from oslo_messaging.rpc import dispatcher as rpc
from oslo_utils import uuidutils
import six

from senlin.common import consts
from senlin.common import exception as exc
from senlin.common.i18n import _
from senlin.engine.actions import base as action_mod
from senlin.engine import dispatcher
from senlin.engine import node as node_mod
from senlin.engine import service
from senlin.objects import cluster as co
from senlin.objects import node as no
from senlin.objects.requests import nodes as orno
from senlin.tests.unit.common import base
from senlin.tests.unit.common import utils


class NodeTest(base.SenlinTestCase):

    def setUp(self):
        super(NodeTest, self).setUp()
        self.ctx = utils.dummy_context(project='node_test_project')
        self.eng = service.EngineService('host-a', 'topic-a')

    @mock.patch.object(no.Node, 'get')
    def test_node_find_by_uuid(self, mock_get):
        x_node = mock.Mock()
        mock_get.return_value = x_node
        aid = uuidutils.generate_uuid()

        result = self.eng.node_find(self.ctx, aid)

        self.assertEqual(x_node, result)
        mock_get.assert_called_once_with(self.ctx, aid, project_safe=True)

    @mock.patch.object(no.Node, 'get_by_name')
    @mock.patch.object(no.Node, 'get')
    def test_node_find_by_uuid_as_name(self, mock_get, mock_name):
        mock_get.return_value = None
        x_node = mock.Mock()
        mock_name.return_value = x_node
        aid = uuidutils.generate_uuid()

        result = self.eng.node_find(self.ctx, aid, False)

        self.assertEqual(x_node, result)
        mock_get.assert_called_once_with(self.ctx, aid, project_safe=False)
        mock_name.assert_called_once_with(self.ctx, aid, project_safe=False)

    @mock.patch.object(no.Node, 'get_by_name')
    def test_node_find_by_name(self, mock_name):
        x_node = mock.Mock()
        mock_name.return_value = x_node
        aid = 'not-a-uuid'

        result = self.eng.node_find(self.ctx, aid)

        self.assertEqual(x_node, result)
        mock_name.assert_called_once_with(self.ctx, aid, project_safe=True)

    @mock.patch.object(no.Node, 'get_by_short_id')
    @mock.patch.object(no.Node, 'get_by_name')
    def test_node_find_by_short_id(self, mock_name, mock_shortid):
        mock_name.return_value = None
        x_node = mock.Mock()
        mock_shortid.return_value = x_node
        aid = 'abcdef'

        result = self.eng.node_find(self.ctx, aid, False)

        self.assertEqual(x_node, result)
        mock_name.assert_called_once_with(self.ctx, aid, project_safe=False)
        mock_shortid.assert_called_once_with(self.ctx, aid, project_safe=False)

    @mock.patch.object(no.Node, 'get_by_short_id')
    def test_node_find_not_found(self, mock_shortid):
        mock_shortid.return_value = None

        ex = self.assertRaises(exc.ResourceNotFound,
                               self.eng.node_find,
                               self.ctx, 'BOGUS')
        self.assertEqual("The node (BOGUS) could not be found.",
                         six.text_type(ex))
        mock_shortid.assert_called_once_with(self.ctx, 'BOGUS',
                                             project_safe=True)

    @mock.patch.object(node_mod.Node, 'load_all')
    def test_node_list2(self, mock_load):
        obj_1 = mock.Mock()
        obj_1.to_dict.return_value = {'k': 'v1'}
        obj_2 = mock.Mock()
        obj_2.to_dict.return_value = {'k': 'v2'}
        mock_load.return_value = [obj_1, obj_2]

        req = orno.NodeListRequest()
        result = self.eng.node_list2(self.ctx, req.obj_to_primitive())

        self.assertEqual([{'k': 'v1'}, {'k': 'v2'}], result)
        mock_load.assert_called_once_with(self.ctx, project_safe=True)

    @mock.patch.object(service.EngineService, 'cluster_find')
    @mock.patch.object(node_mod.Node, 'load_all')
    def test_node_list2_with_cluster_id(self, mock_load, mock_find):
        obj_1 = mock.Mock()
        obj_1.to_dict.return_value = {'k': 'v1'}
        obj_2 = mock.Mock()
        obj_2.to_dict.return_value = {'k': 'v2'}
        mock_load.return_value = [obj_1, obj_2]
        mock_find.return_value = mock.Mock(id='CLUSTER_ID')

        req = orno.NodeListRequest(cluster_id='MY_CLUSTER_NAME',
                                   project_safe=True)
        result = self.eng.node_list2(self.ctx, req.obj_to_primitive())

        self.assertEqual([{'k': 'v1'}, {'k': 'v2'}], result)
        mock_find.assert_called_once_with(self.ctx, 'MY_CLUSTER_NAME')
        mock_load.assert_called_once_with(self.ctx, cluster_id='CLUSTER_ID',
                                          project_safe=True)

    @mock.patch.object(node_mod.Node, 'load_all')
    def test_node_list2_with_params(self, mock_load):
        obj_1 = mock.Mock()
        obj_1.to_dict.return_value = {'k': 'v1'}
        obj_2 = mock.Mock()
        obj_2.to_dict.return_value = {'k': 'v2'}
        mock_load.return_value = [obj_1, obj_2]

        MARKER_UUID = '2fd5b45f-bae4-4cdb-b283-a71e9f9805c7'
        req = orno.NodeListRequest(status=['ACTIVE'], sort='status',
                                   limit=123, marker=MARKER_UUID,
                                   project_safe=True)
        result = self.eng.node_list2(self.ctx, req.obj_to_primitive())

        self.assertEqual([{'k': 'v1'}, {'k': 'v2'}], result)
        mock_load.assert_called_once_with(self.ctx, sort='status', limit=123,
                                          marker=MARKER_UUID,
                                          project_safe=True,
                                          filters={'status': ['ACTIVE']})

    @mock.patch.object(service.EngineService, 'cluster_find')
    def test_node_list2_cluster_not_found(self, mock_find):
        mock_find.side_effect = exc.ResourceNotFound(type='cluster',
                                                     id='BOGUS')

        req = orno.NodeListRequest(cluster_id='BOGUS', project_safe=True)

        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.node_list2,
                               self.ctx, req.obj_to_primitive())

        self.assertEqual(exc.ResourceNotFound, ex.exc_info[0])
        self.assertEqual("The cluster (BOGUS) could not be found.",
                         six.text_type(ex.exc_info[1]))
        mock_find.assert_called_once_with(self.ctx, 'BOGUS')

    @mock.patch.object(node_mod.Node, 'load_all')
    def test_node_list2_with_project_safe(self, mock_load):
        mock_load.return_value = []

        req = orno.NodeListRequest(project_safe=True)
        result = self.eng.node_list2(self.ctx, req.obj_to_primitive())
        self.assertEqual([], result)
        mock_load.assert_called_once_with(self.ctx, project_safe=True)
        mock_load.reset_mock()

        req = orno.NodeListRequest(project_safe=False)
        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.node_list2,
                               self.ctx, req.obj_to_primitive())
        self.assertEqual(exc.Forbidden, ex.exc_info[0])

        self.ctx.is_admin = True
        req = orno.NodeListRequest(project_safe=False)
        result = self.eng.node_list2(self.ctx, req.obj_to_primitive())
        self.assertEqual([], result)
        mock_load.assert_called_once_with(self.ctx, project_safe=False)
        mock_load.reset_mock()

    @mock.patch.object(node_mod.Node, 'load_all')
    def test_node_list2_empty(self, mock_load):
        mock_load.return_value = []

        req = orno.NodeListRequest()
        result = self.eng.node_list2(self.ctx, req.obj_to_primitive())

        self.assertEqual([], result)
        mock_load.assert_called_once_with(self.ctx, project_safe=True)

    @mock.patch.object(action_mod.Action, 'create')
    @mock.patch('senlin.engine.node.Node')
    @mock.patch.object(service.EngineService, 'profile_find')
    @mock.patch.object(dispatcher, 'start_action')
    def test_node_create2(self, notify, mock_profile, mock_node, mock_action):
        mock_profile.return_value = mock.Mock(id='PROFILE_ID')
        x_node = mock.Mock(id='NODE_ID')
        x_node.to_dict.return_value = {'foo': 'bar'}
        mock_node.return_value = x_node
        mock_action.return_value = 'ACTION_ID'
        req = orno.NodeCreateRequestBody(name='NODE1',
                                         profile_id='PROFILE_NAME')

        result = self.eng.node_create2(self.ctx, req.obj_to_primitive())

        self.assertEqual({'foo': 'bar', 'action': 'ACTION_ID'}, result)
        mock_profile.assert_called_once_with(self.ctx, 'PROFILE_NAME')
        mock_node.assert_called_once_with(
            'NODE1', 'PROFILE_ID', '', self.ctx,
            index=-1, role='', metadata={},
            user=self.ctx.user,
            project=self.ctx.project,
            domain=self.ctx.domain)
        x_node.store.assert_called_once_with(self.ctx)
        mock_action.assert_called_once_with(
            self.ctx, 'NODE_ID', consts.NODE_CREATE,
            name='node_create_NODE_ID',
            cause=action_mod.CAUSE_RPC,
            status=action_mod.Action.READY)
        notify.assert_called_once_with()

    @mock.patch.object(action_mod.Action, 'create')
    @mock.patch('senlin.engine.node.Node')
    @mock.patch.object(co.Cluster, 'get_next_index')
    @mock.patch.object(service.EngineService, 'cluster_find')
    @mock.patch.object(service.EngineService, 'profile_find')
    @mock.patch.object(dispatcher, 'start_action')
    def test_node_create2_same_profile(self, notify, mock_profile,
                                       mock_cluster, mock_index,
                                       mock_node, mock_action):
        mock_profile.return_value = mock.Mock(id='PROFILE_ID',
                                              type='PROFILE_TYPE')
        x_cluster = mock.Mock(id='CLUSTER_ID', profile_id='PROFILE_ID')
        mock_cluster.return_value = x_cluster
        mock_index.return_value = 12345
        x_node = mock.Mock(id='NODE_ID')
        x_node.to_dict.return_value = {'foo': 'bar'}
        mock_node.return_value = x_node
        mock_action.return_value = 'ACTION_ID'
        req = orno.NodeCreateRequestBody(name='NODE1',
                                         profile_id='PROFILE_NAME',
                                         cluster_id='FAKE_CLUSTER')

        result = self.eng.node_create2(self.ctx, req.obj_to_primitive())

        self.assertEqual({'foo': 'bar', 'action': 'ACTION_ID'}, result)
        mock_cluster.assert_called_once_with(self.ctx, 'FAKE_CLUSTER')
        mock_profile.assert_called_once_with(self.ctx, 'PROFILE_NAME')
        mock_index.assert_called_once_with(self.ctx, 'CLUSTER_ID')
        mock_node.assert_called_once_with(
            'NODE1', 'PROFILE_ID', 'CLUSTER_ID', self.ctx,
            index=12345, role='', metadata={},
            user=self.ctx.user,
            project=self.ctx.project,
            domain=self.ctx.domain)
        x_node.store.assert_called_once_with(self.ctx)
        mock_action.assert_called_once_with(
            self.ctx, 'NODE_ID', consts.NODE_CREATE,
            name='node_create_NODE_ID',
            cause=action_mod.CAUSE_RPC,
            status=action_mod.Action.READY)
        notify.assert_called_once_with()

    @mock.patch.object(action_mod.Action, 'create')
    @mock.patch('senlin.engine.node.Node')
    @mock.patch.object(co.Cluster, 'get_next_index')
    @mock.patch.object(service.EngineService, 'cluster_find')
    @mock.patch.object(service.EngineService, 'profile_find')
    @mock.patch.object(dispatcher, 'start_action')
    def test_node_create2_same_profile_type(self, notify, mock_profile,
                                            mock_cluster, mock_index,
                                            mock_node, mock_action):
        mock_profile.side_effect = [
            mock.Mock(id='NODE_PROFILE_ID', type='PROFILE_TYPE'),
            mock.Mock(id='CLUSTER_PROFILE_ID', type='PROFILE_TYPE'),
        ]
        x_cluster = mock.Mock(id='CLUSTER_ID', profile_id='CLUSTER_PROFILE_ID')
        mock_cluster.return_value = x_cluster
        mock_index.return_value = 12345
        x_node = mock.Mock(id='NODE_ID')
        x_node.to_dict.return_value = {'foo': 'bar'}
        mock_node.return_value = x_node
        mock_action.return_value = 'ACTION_ID'
        req = orno.NodeCreateRequestBody(name='NODE1',
                                         profile_id='PROFILE_NAME',
                                         cluster_id='FAKE_CLUSTER')

        result = self.eng.node_create2(self.ctx, req.obj_to_primitive())

        self.assertEqual({'foo': 'bar', 'action': 'ACTION_ID'}, result)
        mock_cluster.assert_called_once_with(self.ctx, 'FAKE_CLUSTER')
        mock_profile.assert_has_calls([
            mock.call(self.ctx, 'PROFILE_NAME'),  # for node
            mock.call(self.ctx, 'CLUSTER_PROFILE_ID'),  # for cluster
        ])
        mock_index.assert_called_once_with(self.ctx, 'CLUSTER_ID')
        mock_node.assert_called_once_with(
            'NODE1', 'NODE_PROFILE_ID', 'CLUSTER_ID', self.ctx,
            index=12345, role='', metadata={},
            user=self.ctx.user,
            project=self.ctx.project,
            domain=self.ctx.domain)
        x_node.store.assert_called_once_with(self.ctx)
        mock_action.assert_called_once_with(
            self.ctx, 'NODE_ID', consts.NODE_CREATE,
            name='node_create_NODE_ID',
            cause=action_mod.CAUSE_RPC,
            status=action_mod.Action.READY)
        notify.assert_called_once_with()

    @mock.patch.object(no.Node, 'get_by_name')
    def test_node_create2_name_conflict(self, mock_get):
        cfg.CONF.set_override('name_unique', True, enforce_type=True)
        mock_get.return_value = mock.Mock()
        req = orno.NodeCreateRequestBody(name='NODE1',
                                         profile_id='PROFILE_NAME')

        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.node_create2,
                               self.ctx, req.obj_to_primitive())

        self.assertEqual(exc.BadRequest, ex.exc_info[0])
        self.assertEqual(_("The request is malformed: The node named "
                           "(NODE1) already exists."),
                         six.text_type(ex.exc_info[1]))

    @mock.patch.object(service.EngineService, 'profile_find')
    def test_node_create2_profile_not_found(self, mock_profile):
        mock_profile.side_effect = exc.ResourceNotFound(type='profile',
                                                        id='Bogus')
        req = orno.NodeCreateRequestBody(name='NODE1',
                                         profile_id='Bogus')

        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.node_create2,
                               self.ctx, req.obj_to_primitive())
        self.assertEqual(exc.BadRequest, ex.exc_info[0])
        self.assertEqual("The request is malformed: The specified profile "
                         "(Bogus) could not be found.",
                         six.text_type(ex.exc_info[1]))
        mock_profile.assert_called_once_with(self.ctx, 'Bogus')

    @mock.patch.object(service.EngineService, 'cluster_find')
    @mock.patch.object(service.EngineService, 'profile_find')
    def test_node_create2_cluster_not_found(self, mock_profile, mock_cluster):
        mock_profile.return_value = mock.Mock()
        mock_cluster.side_effect = exc.ResourceNotFound(type='cluster',
                                                        id='Bogus')
        req = orno.NodeCreateRequestBody(name='NODE1',
                                         profile_id='PROFILE_NAME',
                                         cluster_id='Bogus')

        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.node_create2,
                               self.ctx, req.obj_to_primitive())

        self.assertEqual(exc.BadRequest, ex.exc_info[0])
        self.assertEqual("The request is malformed: The specified cluster "
                         "(Bogus) could not be found.",
                         six.text_type(ex.exc_info[1]))
        mock_profile.assert_called_once_with(self.ctx, 'PROFILE_NAME')
        mock_cluster.assert_called_once_with(self.ctx, 'Bogus')

    @mock.patch.object(service.EngineService, 'cluster_find')
    @mock.patch.object(service.EngineService, 'profile_find')
    def test_node_create2_profile_type_not_match(self, mock_profile,
                                                 mock_cluster):
        mock_profile.side_effect = [
            mock.Mock(id='NODE_PROFILE_ID', type='TYPE-A'),
            mock.Mock(id='CLUSTER_PROFILE_ID', type='TYPE-B'),
        ]
        mock_cluster.return_value = mock.Mock(id='CLUSTER_ID',
                                              profile_id='CLUSTER_PROFILE_ID')
        req = orno.NodeCreateRequestBody(name='NODE1',
                                         profile_id='NODE_PROFILE',
                                         cluster_id='FAKE_CLUSTER')

        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.node_create2,
                               self.ctx, req.obj_to_primitive())

        self.assertEqual(exc.ProfileTypeNotMatch, ex.exc_info[0])
        self.assertEqual("Node and cluster have different profile type, "
                         "operation aborted.",
                         six.text_type(ex.exc_info[1]))
        mock_profile.assert_has_calls([
            mock.call(self.ctx, 'NODE_PROFILE'),
            mock.call(self.ctx, 'CLUSTER_PROFILE_ID'),
        ])
        mock_cluster.assert_called_once_with(self.ctx, 'FAKE_CLUSTER')

    @mock.patch.object(node_mod.Node, 'load')
    @mock.patch.object(service.EngineService, 'node_find')
    def test_node_get2(self, mock_find, mock_load):
        x_obj = mock.Mock()
        mock_find.return_value = x_obj
        x_node = mock.Mock(physical_id='PHYSICAL_ID')
        x_node.to_dict.return_value = {'foo': 'bar'}
        mock_load.return_value = x_node

        req = orno.NodeGetRequest(identity='NODE1', show_details=False)
        result = self.eng.node_get2(self.ctx, req.obj_to_primitive())

        self.assertEqual({'foo': 'bar'}, result)
        mock_find.assert_called_once_with(self.ctx, 'NODE1')
        mock_load.assert_called_once_with(self.ctx, db_node=x_obj)
        x_node.to_dict.assert_called_once_with()

    @mock.patch.object(node_mod.Node, 'load')
    @mock.patch.object(service.EngineService, 'node_find')
    def test_node_get2_with_details(self, mock_find, mock_load):
        x_obj = mock.Mock()
        mock_find.return_value = x_obj
        x_node = mock.Mock(physical_id='PHYSICAL_ID')
        x_node.to_dict.return_value = {'foo': 'bar'}
        x_node.get_details.return_value = {'info': 'blahblah'}
        mock_load.return_value = x_node

        req = orno.NodeGetRequest(identity='NODE1', show_details=True)
        result = self.eng.node_get2(self.ctx, req.obj_to_primitive())

        self.assertEqual({'foo': 'bar', 'details': {'info': 'blahblah'}},
                         result)
        mock_find.assert_called_once_with(self.ctx, 'NODE1')
        mock_load.assert_called_once_with(self.ctx, db_node=x_obj)
        x_node.to_dict.assert_called_once_with()
        x_node.get_details.assert_called_once_with(self.ctx)

    @mock.patch.object(service.EngineService, 'node_find')
    def test_node_get2_node_not_found(self, mock_find):
        mock_find.side_effect = exc.ResourceNotFound(type='node', id='Bogus')

        req = orno.NodeGetRequest(identity='Bogus', show_details=False)
        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.node_get2,
                               self.ctx, req.obj_to_primitive())

        self.assertEqual(exc.ResourceNotFound, ex.exc_info[0])
        self.assertEqual("The node (Bogus) could not be found.",
                         six.text_type(ex.exc_info[1]))
        mock_find.assert_called_once_with(self.ctx, 'Bogus')

    @mock.patch.object(node_mod.Node, 'load')
    @mock.patch.object(service.EngineService, 'node_find')
    def test_node_get2_no_physical_id(self, mock_find, mock_load):
        x_obj = mock.Mock()
        mock_find.return_value = x_obj
        x_node = mock.Mock(physical_id=None)
        x_node.to_dict.return_value = {'foo': 'bar'}
        mock_load.return_value = x_node

        req = orno.NodeGetRequest(identity='NODE1', show_details=True)
        result = self.eng.node_get2(self.ctx, req.obj_to_primitive())

        self.assertEqual({'foo': 'bar'}, result)
        mock_find.assert_called_once_with(self.ctx, 'NODE1')
        mock_load.assert_called_once_with(self.ctx, db_node=x_obj)
        x_node.to_dict.assert_called_once_with()
        self.assertEqual(0, x_node.get_details.call_count)

    @mock.patch.object(dispatcher, 'start_action')
    @mock.patch.object(action_mod.Action, 'create')
    @mock.patch.object(node_mod.Node, 'load')
    @mock.patch.object(service.EngineService, 'node_find')
    def test_node_update2(self, mock_find, mock_load, mock_action, mock_start):
        x_obj = mock.Mock(id='FAKE_NODE_ID', name='NODE1', role='ROLE1',
                          metadata={'KEY': 'VALUE'})
        mock_find.return_value = x_obj
        x_node = mock.Mock()
        x_node.to_dict.return_value = {'foo': 'bar'}
        mock_load.return_value = x_node
        mock_action.return_value = 'ACTION_ID'

        req = orno.NodeUpdateRequest(identity='FAKE_NODE',
                                     name='NODE2',
                                     role='NEW_ROLE',
                                     metadata={'foo1': 'bar1'})

        # all properties changed except profile id
        result = self.eng.node_update2(self.ctx, req.obj_to_primitive())

        self.assertEqual({'foo': 'bar', 'action': 'ACTION_ID'}, result)
        mock_find.assert_called_once_with(self.ctx, 'FAKE_NODE')
        mock_action.assert_called_once_with(
            self.ctx, 'FAKE_NODE_ID', consts.NODE_UPDATE,
            name='node_update_FAKE_NOD',
            cause=action_mod.CAUSE_RPC,
            status=action_mod.Action.READY,
            inputs={
                'name': 'NODE2',
                'role': 'NEW_ROLE',
                'metadata': {
                    'foo1': 'bar1',
                }
            })
        mock_start.assert_called_once_with()
        mock_load.assert_called_once_with(self.ctx, db_node=x_obj)

    @mock.patch.object(dispatcher, 'start_action')
    @mock.patch.object(action_mod.Action, 'create')
    @mock.patch.object(service.EngineService, 'profile_find')
    @mock.patch.object(node_mod.Node, 'load')
    @mock.patch.object(service.EngineService, 'node_find')
    def test_node_update2_new_profile(self, mock_find, mock_load, mock_profile,
                                      mock_action, mock_start):
        x_obj = mock.Mock(id='FAKE_NODE_ID', role='ROLE1',
                          metadata={'KEY': 'VALUE'},
                          profile_id='OLD_PROFILE_ID')
        x_obj.name = 'NODE1'
        mock_find.return_value = x_obj
        # Same profile type
        mock_profile.side_effect = [
            mock.Mock(id='NEW_PROFILE_ID', type='PROFILE_TYPE'),
            mock.Mock(id='OLD_PROFILE_ID', type='PROFILE_TYPE'),
        ]
        x_node = mock.Mock()
        x_node.to_dict.return_value = {'foo': 'bar'}
        mock_load.return_value = x_node
        mock_action.return_value = 'ACTION_ID'

        # all properties are filtered out except for profile_id
        req = orno.NodeUpdateRequest(identity='FAKE_NODE',
                                     name='NODE1',
                                     role='ROLE1',
                                     metadata={'KEY': 'VALUE'},
                                     profile_id='NEW_PROFILE')
        result = self.eng.node_update2(self.ctx, req.obj_to_primitive())

        self.assertEqual({'foo': 'bar', 'action': 'ACTION_ID'}, result)
        mock_find.assert_called_once_with(self.ctx, 'FAKE_NODE')
        mock_profile.assert_has_calls([
            mock.call(self.ctx, 'NEW_PROFILE'),
            mock.call(self.ctx, 'OLD_PROFILE_ID'),
        ])
        mock_action.assert_called_once_with(
            self.ctx, 'FAKE_NODE_ID', consts.NODE_UPDATE,
            name='node_update_FAKE_NOD',
            cause=action_mod.CAUSE_RPC,
            status=action_mod.Action.READY,
            inputs={
                'new_profile_id': 'NEW_PROFILE_ID',
            })
        mock_start.assert_called_once_with()
        mock_load.assert_called_once_with(self.ctx, db_node=x_obj)

    @mock.patch.object(service.EngineService, 'node_find')
    def test_node_update2_node_not_found(self, mock_find):
        mock_find.side_effect = exc.ResourceNotFound(type='node', id='Bogus')

        req = orno.NodeUpdateRequest(identity='Bogus')
        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.node_update2, self.ctx,
                               req.obj_to_primitive())

        self.assertEqual(exc.ResourceNotFound, ex.exc_info[0])
        self.assertEqual('The node (Bogus) could not be found.',
                         six.text_type(ex.exc_info[1]))
        mock_find.assert_called_once_with(self.ctx, 'Bogus')

    @mock.patch.object(service.EngineService, 'profile_find')
    @mock.patch.object(service.EngineService, 'node_find')
    def test_node_update2_profile_not_found(self, mock_find, mock_profile):
        mock_find.return_value = mock.Mock()
        mock_profile.side_effect = exc.ResourceNotFound(type='profile',
                                                        id='Bogus')

        req = orno.NodeUpdateRequest(identity='FAKE_NODE',
                                     profile_id='Bogus')
        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.node_update2,
                               self.ctx, req.obj_to_primitive())

        self.assertEqual(exc.BadRequest, ex.exc_info[0])
        self.assertEqual('The request is malformed: The specified profile '
                         '(Bogus) could not be found.',
                         six.text_type(ex.exc_info[1]))
        mock_find.assert_called_once_with(self.ctx, 'FAKE_NODE')
        mock_profile.assert_called_once_with(self.ctx, 'Bogus')

    @mock.patch.object(service.EngineService, 'profile_find')
    @mock.patch.object(service.EngineService, 'node_find')
    def test_node_update2_diff_profile_type(self, mock_find, mock_profile):
        mock_find.return_value = mock.Mock(profile_id='OLD_PROFILE_ID')
        mock_profile.side_effect = [
            mock.Mock(id='NEW_PROFILE_ID', type='NEW_PROFILE_TYPE'),
            mock.Mock(id='OLD_PROFILE_ID', type='OLD_PROFILE_TYPE'),
        ]

        req = orno.NodeUpdateRequest(identity='FAKE_NODE',
                                     profile_id='NEW_PROFILE')
        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.node_update2,
                               self.ctx, req.obj_to_primitive())

        self.assertEqual(exc.ProfileTypeNotMatch, ex.exc_info[0])
        self.assertEqual('Cannot update a node to a different profile type, '
                         'operation aborted.',
                         six.text_type(ex.exc_info[1]))
        mock_find.assert_called_once_with(self.ctx, 'FAKE_NODE')
        mock_profile.assert_has_calls([
            mock.call(self.ctx, 'NEW_PROFILE'),
            mock.call(self.ctx, 'OLD_PROFILE_ID'),
        ])

    @mock.patch.object(service.EngineService, 'node_find')
    def test_node_update2_no_property_for_update(self, mock_find):
        x_obj = mock.Mock(id='FAKE_NODE_ID', name='NODE1', role='ROLE1',
                          metadata={'KEY': 'VALUE'})
        mock_find.return_value = x_obj

        # no property has been specified for update
        req = orno.NodeUpdateRequest(identity='FAKE_NODE')
        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.node_update2,
                               self.ctx, req.obj_to_primitive())

        self.assertEqual(exc.BadRequest, ex.exc_info[0])
        self.assertEqual('The request is malformed: No property needs an '
                         'update.',
                         six.text_type(ex.exc_info[1]))
        mock_find.assert_called_once_with(self.ctx, 'FAKE_NODE')

    @mock.patch.object(dispatcher, 'start_action')
    @mock.patch.object(action_mod.Action, 'create')
    @mock.patch.object(service.EngineService, 'node_find')
    def test_node_delete2(self, mock_find, mock_action, mock_start):
        mock_find.return_value = mock.Mock(id='12345678AB', status='ACTIVE',
                                           dependents={})
        mock_action.return_value = 'ACTION_ID'

        req = orno.NodeDeleteRequest(identity='FAKE_NODE')
        result = self.eng.node_delete2(self.ctx, req.obj_to_primitive())

        self.assertEqual({'action': 'ACTION_ID'}, result)
        mock_find.assert_called_once_with(self.ctx, 'FAKE_NODE')
        mock_action.assert_called_once_with(
            self.ctx, '12345678AB', consts.NODE_DELETE,
            name='node_delete_12345678',
            cause=action_mod.CAUSE_RPC,
            status=action_mod.Action.READY)
        mock_start.assert_called_once_with()

    @mock.patch.object(service.EngineService, 'node_find')
    def test_node_delete2_node_not_found(self, mock_find):
        mock_find.side_effect = exc.ResourceNotFound(type='node', id='Bogus')

        req = orno.NodeDeleteRequest(identity='Bogus')
        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.node_delete2, self.ctx,
                               req.obj_to_primitive())

        self.assertEqual(exc.ResourceNotFound, ex.exc_info[0])
        self.assertEqual('The node (Bogus) could not be found.',
                         six.text_type(ex.exc_info[1]))
        mock_find.assert_called_once_with(self.ctx, 'Bogus')

    @mock.patch.object(service.EngineService, 'node_find')
    def test_node_delete2_improper_status(self, mock_find):
        for bad_status in [consts.NS_CREATING, consts.NS_UPDATING,
                           consts.NS_DELETING, consts.NS_RECOVERING]:
            fake_node = mock.Mock(id='12345678AB', status=bad_status)
            mock_find.return_value = fake_node
            req = orno.NodeDeleteRequest(identity='BUSY')
            ex = self.assertRaises(rpc.ExpectedException,
                                   self.eng.node_delete2,
                                   self.ctx, req.obj_to_primitive())

            self.assertEqual(exc.ActionInProgress, ex.exc_info[0])
            self.assertEqual("The node BUSY is in status %s." % bad_status,
                             six.text_type(ex.exc_info[1]))
            # skipping assertion on mock_find

    @mock.patch.object(service.EngineService, 'node_find')
    def test_node_delete2_contain_container(self, mock_find):
        dependents = {'containers': ['container1']}
        node = mock.Mock(id='NODE_ID', status='ACTIVE', dependents=dependents)
        mock_find.return_value = node
        req = orno.NodeDeleteRequest(identity='node1')
        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.node_delete2,
                               self.ctx, req.obj_to_primitive())
        self.assertEqual(exc.ResourceInUse, ex.exc_info[0])
        self.assertEqual("The node node1 cannot be deleted: still depended "
                         "by other clusters and/or nodes.",
                         six.text_type(ex.exc_info[1]))

    @mock.patch.object(dispatcher, 'start_action')
    @mock.patch.object(action_mod.Action, 'create')
    @mock.patch.object(service.EngineService, 'node_find')
    def test_node_check2(self, mock_find, mock_action, mock_start):
        mock_find.return_value = mock.Mock(id='12345678AB')
        mock_action.return_value = 'ACTION_ID'

        params = {'k1': 'v1'}
        req = orno.NodeCheckRequest(identity='FAKE_NODE', params=params)
        result = self.eng.node_check2(self.ctx, req.obj_to_primitive())

        self.assertEqual({'action': 'ACTION_ID'}, result)
        mock_find.assert_called_once_with(self.ctx, 'FAKE_NODE')
        mock_action.assert_called_once_with(
            self.ctx, '12345678AB', consts.NODE_CHECK,
            name='node_check_12345678',
            cause=action_mod.CAUSE_RPC,
            status=action_mod.Action.READY,
            inputs={'k1': 'v1'})
        mock_start.assert_called_once_with()

    @mock.patch.object(service.EngineService, 'node_find')
    def test_node_check2_not_found(self, mock_find):
        mock_find.side_effect = exc.ResourceNotFound(type='node', id='Bogus')

        req = orno.NodeCheckRequest(identity='Bogus')
        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.node_check2,
                               self.ctx, req.obj_to_primitive())

        self.assertEqual(exc.ResourceNotFound, ex.exc_info[0])
        self.assertEqual('The node (Bogus) could not be found.',
                         six.text_type(ex.exc_info[1]))
        mock_find.assert_called_once_with(self.ctx, 'Bogus')

    @mock.patch.object(dispatcher, 'start_action')
    @mock.patch.object(action_mod.Action, 'create')
    @mock.patch.object(service.EngineService, 'node_find')
    def test_node_recover2(self, mock_find, mock_action, mock_start):
        mock_find.return_value = mock.Mock(id='12345678AB')
        mock_action.return_value = 'ACTION_ID'

        params = {'k1': 'v1'}
        req = orno.NodeRecoverRequest(identity='FAKE_NODE', params=params)
        result = self.eng.node_recover2(self.ctx, req.obj_to_primitive())

        self.assertEqual({'action': 'ACTION_ID'}, result)
        mock_find.assert_called_once_with(self.ctx, 'FAKE_NODE')
        mock_action.assert_called_once_with(
            self.ctx, '12345678AB', consts.NODE_RECOVER,
            name='node_recover_12345678',
            cause=action_mod.CAUSE_RPC,
            status=action_mod.Action.READY,
            inputs={'k1': 'v1'})
        mock_start.assert_called_once_with()

    @mock.patch.object(service.EngineService, 'node_find')
    def test_node_recover2_not_found(self, mock_find):
        mock_find.side_effect = exc.ResourceNotFound(type='node', id='Bogus')

        req = orno.NodeRecoverRequest(identity='Bogus')
        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.node_recover2,
                               self.ctx, req.obj_to_primitive())

        self.assertEqual(exc.ResourceNotFound, ex.exc_info[0])
        self.assertEqual('The node (Bogus) could not be found.',
                         six.text_type(ex.exc_info[1]))
        mock_find.assert_called_once_with(self.ctx, 'Bogus')
