def test_workflow_error_delegation(self):
        try:
            workflow_context.get_rest_client = \
                lambda: rest_client_mock.MockRestclient()
            decorators.get_rest_client = \
                lambda: rest_client_mock.MockRestclient()
            manager.get_rest_client = \
                lambda: rest_client_mock.MockRestclient()

            kwargs = {'__cloudify_context': {}}
            try:
                error_workflow(picklable=False, **kwargs)
                self.fail('Expected exception')
            except ProcessExecutionError as e:
                self.assertTrue('hello world!' in e.message)
                self.assertTrue('test_decorators.py' in e.traceback)
                self.assertTrue(
                    MockNotPicklableException.__name__ in e.error_type)
            try:
                error_workflow(picklable=True, **kwargs)
                self.fail('Expected exception')
            except ProcessExecutionError as e:
                self.assertTrue('hello world!' in e.message)
                self.assertTrue('test_decorators.py' in e.traceback)
                self.assertTrue(
                    MockPicklableException.__name__ in e.error_type)
        finally:
            from cloudify.workflows import api
            api.ctx = None
            api.pipe = None
    def test_provided_capabilities(self):
        ctx = {
            'node_id': '5678',
        }

        # using a mock rest client
        manager.get_rest_client = \
            lambda: rest_client_mock.MockRestclient()

        rest_client_mock.put_node_instance('5678',
                                           relationships=[{
                                               'target_id':
                                               'some_node',
                                               'target_name':
                                               'some_node'
                                           }])
        rest_client_mock.put_node_instance('some_node',
                                           runtime_properties={'k': 'v'})

        kwargs = {'__cloudify_context': ctx}
        ctx = acquire_context(0, 0, **kwargs)
        with warnings.catch_warnings(record=True) as warns:
            self.assertIn('k', ctx.capabilities)
            self.assertEquals('v', ctx.capabilities['k'])
        if sys.version_info < (2, 7):
            # i was unable to make this work on py2.6
            return
        self.assertEqual(len(warns), 2)
        for w in warns:
            self.assertIn('capabilities is deprecated', str(w))
    def test_capabilities_clash(self):
        ctx = {
            'node_id': '5678',
        }

        # using a mock rest client
        manager.get_rest_client = \
            lambda: rest_client_mock.MockRestclient()

        rest_client_mock.put_node_instance('5678',
                                           relationships=[{
                                               'target_id':
                                               'node1',
                                               'target_name':
                                               'node1'
                                           }, {
                                               'target_id':
                                               'node2',
                                               'target_name':
                                               'node2'
                                           }])

        rest_client_mock.put_node_instance('node1',
                                           runtime_properties={'k': 'v1'})
        rest_client_mock.put_node_instance('node2',
                                           runtime_properties={'k': 'v2'})

        kwargs = {'__cloudify_context': ctx}
        ctx = acquire_context(0, 0, **kwargs)
        self.assertRaises(NonRecoverableError, ctx.capabilities.__contains__,
                          'k')
    def test_serial_operation_install_workflow(self, _mock, list_fn):

        _ctx = MockCloudifyContext(node_id='test_node',
                                   deployment_id='test_deployment',
                                   index=7)

        # Check that we raise if the preceder is not 'started'.
        _ctx._context['workflow_id'] = 'install'
        current_ctx.set(_ctx)
        _mock.side_effect = lambda: rest_client_mock.MockRestclient()
        _caller = Mock()

        @serial_operation(workflows=['scale'])
        def run_op_neither(ctx=_ctx, **kwargs):
            _caller()

        list_fn.return_value = [
            Mock(id='test_node{x}'.format(x=n),
                 index=n,
                 state='started' if n == 6 else 'uninitialized')
            for n in range(0, 6)
        ]
        run_op_neither()
        self.assertTrue(_caller.called)
        current_ctx.clear()
    def test_provided_capabilities(self):
        ctx = {
            'node_id': '5678',
        }

        # using a mock rest client
        manager.get_rest_client = \
            lambda: rest_client_mock.MockRestclient()

        rest_client_mock.put_node_instance(
            '5678',
            relationships=[{'target_id': 'some_node',
                            'target_name': 'some_node'}])
        rest_client_mock.put_node_instance('some_node',
                                           runtime_properties={'k': 'v'})

        kwargs = {'__cloudify_context': ctx}
        ctx = acquire_context(0, 0, **kwargs)
        self.assertIn('k', ctx.capabilities)
        self.assertEquals('v', ctx.capabilities['k'])
    def test_serial_operation_uninstall_wait_3(self, _mock, list_fn):

        _ctx = MockCloudifyContext(node_id='test_node',
                                   deployment_id='test_deployment',
                                   index=7)

        # Check that we raise if the preceder is not 'started'.
        _ctx._context['workflow_id'] = 'uninstall'
        current_ctx.set(_ctx)
        _mock.side_effect = lambda: rest_client_mock.MockRestclient()
        _caller = Mock()

        @serial_operation(threshold=3, workflows=['uninstall'])
        def run_op_wait_for_3(ctx=_ctx, **kwargs):
            _caller()

        finished3 = []
        for n in range(1, 8):
            if n == 7:
                continue
            elif n in [1, 2, 3]:
                state = 'started'
            else:
                state = 'uninitialized'
            finished3.append(
                Mock(id='test_node{x}'.format(x=n), index=n, state=state))
        list_fn.return_value = finished3
        self.assertRaises(CloudifySerializationRetry, run_op_wait_for_3)
        self.assertFalse(_caller.called)

        # Check if we cross the serialization_type threshold,
        # then we do not trigger the retry.
        list_fn.return_value = [
            Mock(id='test_node{x}'.format(x=n),
                 index=n,
                 state='started' if n < 7 else 'uninitialized')
            for n in range(3, 10) if n != 7
        ]
        run_op_wait_for_3()
        self.assertTrue(_caller.called)
        current_ctx.clear()
    def test_serial_operation_uninstall(self, _mock, list_fn):

        _ctx = MockCloudifyContext(node_id='test_node',
                                   deployment_id='test_deployment',
                                   index=7)

        # Check that we raise if the preceder is not 'started'.
        _ctx._context['workflow_id'] = 'uninstall'
        current_ctx.set(_ctx)
        _mock.side_effect = lambda: rest_client_mock.MockRestclient()
        _caller = Mock()

        @serial_operation(workflows=['uninstall'])
        def run_op_uninstall_only(ctx=_ctx, **kwargs):
            _caller()

        list_fn.return_value = [
            Mock(id='test_node{x}'.format(x=n), index=n, state='uninitialized')
            for n in range(1, 8) if n != 7
        ]
        self.assertRaises(CloudifySerializationRetry, run_op_uninstall_only)
        self.assertFalse(_caller.called)
        current_ctx.clear()
    def test_capabilities_clash(self):
        ctx = {
            'node_id': '5678',
        }

        # using a mock rest client
        manager.get_rest_client = \
            lambda: rest_client_mock.MockRestclient()

        rest_client_mock.put_node_instance('5678',
                                           relationships=[{
                                               'target_id':
                                               'node1',
                                               'target_name':
                                               'node1'
                                           }, {
                                               'target_id':
                                               'node2',
                                               'target_name':
                                               'node2'
                                           }])

        rest_client_mock.put_node_instance('node1',
                                           runtime_properties={'k': 'v1'})
        rest_client_mock.put_node_instance('node2',
                                           runtime_properties={'k': 'v2'})

        kwargs = {'__cloudify_context': ctx}
        ctx = acquire_context(0, 0, **kwargs)
        with warnings.catch_warnings(record=True) as warns:
            self.assertRaises(NonRecoverableError,
                              lambda: 'k' in ctx.capabilities)
        if sys.version_info < (2, 7):
            # i was unable to make this work on py2.6
            return
        self.assertEqual(len(warns), 1)
        self.assertIn('capabilities is deprecated', str(warns[0]))