Ejemplo n.º 1
0
    def test_boolean(self):
        input_val = 'true'
        expected_val = BooleanValue(True)
        actual_val = DataValueConverter.convert_to_data_value(input_val)
        self.assertEqual(expected_val, actual_val)

        input_val = 'false'
        expected_val = BooleanValue(False)
        actual_val = DataValueConverter.convert_to_data_value(input_val)
        self.assertEqual(expected_val, actual_val)
Ejemplo n.º 2
0
 def test_publish(self):
     info = self.task_handle.get_info()
     progress = Progress()
     progress.total = 100
     progress.completed = 42
     progress.message = self.progress_msg
     desc2 = LocalizableMessage(id='msg2', default_message='task1', args=[])
     info.description = desc2
     info.cancelable = False
     info.status = 'RUNNING'
     info.start_time = datetime.utcnow()
     info.progress = progress
     self.task_handle.publish()
     result = self.task_manager.get_info(self.task_id)
     self.assertEqual(result.get_field('status'), StringValue('RUNNING'))
     progress_val = StructValue('com.vmware.cis.task.progress')
     progress_val.set_field('total', IntegerValue(100))
     progress_val.set_field('completed', IntegerValue(42))
     progress_val.set_field(
         'message',
         TypeConverter.convert_to_vapi(
             self.progress_msg, LocalizableMessage.get_binding_type()))
     self.assertEqual(result.get_field('progress'),
                      OptionalValue(progress_val))
     self.assertEqual(result.get_field('cancelable'), BooleanValue(False))
Ejemplo n.º 3
0
 def test_boolean_value(self):
     input_val = BooleanValue(True)
     actual_val = DataValueConverter.convert_to_json(input_val)
     expected_val = 'true'
     self.assertEqual(expected_val, actual_val)
     # Verify json is valid
     json.loads(actual_val)
Ejemplo n.º 4
0
 def test_set_info(self):
     service_uuid = str(uuid.uuid4())
     task_id = self.task_manager.create_task(service_uuid,
                                             None,
                                             'test.service',
                                             'op',
                                             False)
     info_val = self.task_manager.get_info(task_id)
     info = TypeConverter.convert_to_python(info_val,
                                            Info.get_binding_type())
     info.description = self.description
     progress = Progress()
     progress.total = 100
     progress.completed = 10
     progress.message = self.progress_msg
     info.progress = progress
     info.start_time = datetime.utcnow()
     info.status = Status.RUNNING
     info.cancelable = True
     self.task_manager.set_info(task_id,
                                TypeConverter.convert_to_vapi(info, Info.get_binding_type()))
     result = self.task_manager.get_info(task_id)
     self.assertEqual(result.get_field('progress'),
                      OptionalValue(TypeConverter.convert_to_vapi(progress,
                         Progress.get_binding_type())))
     self.assertEqual(result.get_field('cancelable'), BooleanValue(info.cancelable))
     self.assertEqual(result.get_field('status'), StringValue('RUNNING'))
Ejemplo n.º 5
0
 def get_data_values(self):
     # Data values
     list_value = ListValue()
     list_value.add_all([IntegerValue(val) for val in range(1,15)])
     data_values = [
         VoidValue(),
         IntegerValue(3),
         DoubleValue(decimal.Decimal('7.2')),
         StringValue('blah'),
         SecretValue(),
         BooleanValue(True),
         BlobValue(b"a blob"),
         BlobValue(b"0\x82\x04\x00"),
         list_value,
         OptionalValue(),
         OptionalValue(IntegerValue(7)),
         StructValue('name'),
         self.get_struct_value(),
         self.get_error_value(),
     ]
     struct_value = StructValue('struct')
     for idx, data_val in enumerate(data_values):
         struct_value.set_field(str(idx), data_val)
     data_values.append(struct_value)
     return data_values
Ejemplo n.º 6
0
 def test_dict(self):
     input_val = '{"int_field":10, "bool_field":true}'
     values = {
         'bool_field': BooleanValue(True),
         'int_field': IntegerValue(10)
     }
     expected_val = StructValue(values=values)
     actual_val = DataValueConverter.convert_to_data_value(input_val)
     self.assertEqual(expected_val, actual_val)
Ejemplo n.º 7
0
    def create_task(self,
                    description,
                    service_id,
                    operation_id,
                    cancelable,
                    error_types,
                    id_=None):
        """
        Creates a task in task manager.

        :type  description: :class:`com.vmware.vapi.std.LocalizableMessage`
        :param description: Task description.
        :type  service_id: :class:`str`
        :param service_id: Service Id.
        :type  operation_id: :class:`str`
        :param operation_id: Operation Id.
        :type  cancelable: :class:`bool`
        :param cancelable: Is the task cancelable.
        :type  error_types: :class:`list` of
            :class:`vmware.vapi.bindings.type.ReferenceType`
        :param error_types: Error definitions describing the errors this
            operation can report
        :type  id_: :class:`str`
        :param id_: Base task id
        """
        task_info = StructValue()
        if description is not None:
            task_info.set_field(
                'description',
                TypeConverter.convert_to_vapi(
                    description, LocalizableMessage.get_binding_type()))
        else:
            desc_value = StructValue()
            desc_value.set_field('id', StringValue())
            desc_value.set_field('default_message', StringValue())
            desc_value.set_field('args', ListValue())
            task_info.set_field('description', desc_value)

        user = self._get_user_from_sec_ctx()
        if user is not None:
            task_info.set_field('user', StringValue(user))

        task_info.set_field('service', StringValue(service_id))
        task_info.set_field('operation', StringValue(operation_id))
        task_info.set_field('cancelable',
                            BooleanValue(True if cancelable else False))
        task_info.set_field('status', PENDING_STRING_VALUE)
        base_id = id_ if id_ is not None else str(uuid.uuid4())
        task_id = self._create_task_id(base_id, service_id)

        task_summary = TaskSummary(task_info, error_types)
        with self.lock:
            self.task_map.setdefault(task_id, task_summary)

        self._remove_expired_task()
        return task_id
Ejemplo n.º 8
0
    def _visit_bool(self, obj):  # pylint: disable=R0201
        """
        Visit python boolean object

        :type  obj: :class:`bool`
        :param obj: Python boolean object
        :rtype: :class:`vmware.vapi.data.value.BooleanValue`
        :return: Boolean value
        """
        return BooleanValue(obj)
Ejemplo n.º 9
0
 def test_invoke_error(self):
     ctx = ExecutionContext()
     input_ = StructValue(method_name)
     input_.set_field('message', IntegerValue(10))
     input_.set_field('throw', BooleanValue(True))
     actual_method_result = self.provider.invoke(interface_name,
                                                 method_name,
                                                 input_,
                                                 ctx)
     self.assertFalse(actual_method_result.success())
Ejemplo n.º 10
0
 def test_create_task_no_desc(self):
     service_uuid = str(uuid.uuid4())
     task_id = self.task_manager.create_task(service_uuid,
                                             None,
                                             'test.service1',
                                             'op',
                                             False)
     info = self.task_manager.get_info(task_id)
     self.assertIn(service_uuid, task_id)
     self.assertEqual(info.get_field('service'), StringValue('test.service1'))
     self.assertEqual(info.get_field('operation'), StringValue('op'))
     self.assertEqual(info.get_field('cancelable'), BooleanValue(False))
     self.assertEqual(info.get_field('status'), StringValue('PENDING'))
Ejemplo n.º 11
0
 def test_invoke_long_running_sync(self):
     ctx = ExecutionContext()
     input_ = StructValue(method_name)
     input_.set_field('message', StringValue('hello'))
     input_.set_field('throw', BooleanValue(False))
     actual_method_result = self.provider.invoke(interface_name,
                                                 task_method_name,
                                                 input_,
                                                 ctx)
     expected_method_result = MethodResult(output=StringValue('hello'))
     self.assertEqual(actual_method_result.output,
                      expected_method_result.output)
     self.assertEqual(actual_method_result.error,
                      expected_method_result.error)
Ejemplo n.º 12
0
    def create_task(self,
                    provider_id,
                    description,
                    service_id,
                    operation_id,
                    cancelable,
                    id_=None):
        """
        Creates a task in task manager.

        :type  provider_id: :class:`str`
        :param provider_id: Service UUID
        :type  description: :class:`com.vmware.vapi.std.LocalizableMessage`
        :param description: Task description.
        :type  service_id: :class:`str`
        :param service_id: Service Id.
        :type  operation_id: :class:`str`
        :param operation_id: Operation Id.
        :type  cancelable: :class:`bool`
        :param cancelable: Is the task cancelable.
        :type  id_: :class:`str`
        :param id_: Base task id
        """
        task_info = StructValue()
        if description is not None:
            task_info.set_field(
                'description',
                TypeConverter.convert_to_vapi(
                    description, LocalizableMessage.get_binding_type()))
        else:
            desc_value = StructValue()
            desc_value.set_field('id', StringValue())
            desc_value.set_field('default_message', StringValue())
            desc_value.set_field('args', ListValue())
            task_info.set_field('description', desc_value)

        task_info.set_field('service', StringValue(service_id))
        task_info.set_field('operation', StringValue(operation_id))
        task_info.set_field('cancelable',
                            BooleanValue(True if cancelable else False))
        task_info.set_field('status', StringValue('PENDING'))
        base_id = id_ if id_ is not None else str(uuid.uuid4())
        task_id = self._create_task_id(base_id, provider_id)

        with self.lock:
            self.task_map.setdefault(task_id, task_info)

        self._remove_expired_task()
        return task_id
Ejemplo n.º 13
0
 def test_create_task(self):
     service_uuid = str(uuid.uuid4())
     task_id = self.task_manager.create_task(service_uuid,
                                             self.description,
                                             'test.service1',
                                             'op',
                                             False)
     info = self.task_manager.get_info(task_id)
     self.assertIn(service_uuid, task_id)
     self.assertEqual(info.get_field('description'),
                      TypeConverter.convert_to_vapi(self.description,
                         LocalizableMessage.get_binding_type()))
     self.assertEqual(info.get_field('service'), StringValue('test.service1'))
     self.assertEqual(info.get_field('operation'), StringValue('op'))
     self.assertEqual(info.get_field('cancelable'), BooleanValue(False))
     self.assertEqual(info.get_field('status'), StringValue('PENDING'))
Ejemplo n.º 14
0
 def invoke(self, service_id, operation_id, input, ctx):
     if operation_id == report_vapi_error:
         error_value = make_error_value_from_msgs(not_found_def, self.msg)
         return MethodResult(error=error_value)
     elif operation_id == report_vapi_success:
         return MethodResult(output=BooleanValue(True))
     elif operation_id == 'echo':
         msg = input.get_field('message')
         return MethodResult(output=msg)
     elif operation_id == 'echo_long_running':
         msg = input.get_field('message')
         return MethodResult(output=msg)
     elif operation_id == 'echo_long_running$task':
         return MethodResult(output=StringValue(str(uuid.uuid4())))
     else:
         error_value = make_error_value_from_msgs(operation_not_found_def,
                                                  self.msg)
         return MethodResult(error=error_value)
Ejemplo n.º 15
0
 def test_invoke_long_running(self):
     ctx = ExecutionContext()
     input_ = StructValue(method_name)
     input_.set_field('message', StringValue('hello'))
     input_.set_field('throw', BooleanValue(False))
     actual_method_result = self.provider.invoke(interface_name,
                                                 '%s$task' % task_method_name,
                                                 input_,
                                                 ctx)
     expected_method_result = MethodResult(output=StringValue('hello'))
     try:
         id_split = actual_method_result.output.value.split(':')
         uuid.UUID(id_split[0], version=4)
         uuid.UUID(id_split[1], version=4)
     except ValueError:
         # There's no assertNotRaises so explicitly fail assert
         # in case a ValueError is thrown for invalid uuid.
         self.assertTrue(False)
     self.assertEqual(actual_method_result.error,
                      expected_method_result.error)
Ejemplo n.º 16
0
 def test_query_params_boolean(self):
     input_val = StructValue(name='operation-input',
                             values={
                                 'string_val': StringValue('string1'),
                                 'action1_val': BooleanValue(value=False)
                             })
     rest_metadata = OperationRestMetadata(http_method='POST',
                                           url_template='/foo/bar',
                                           query_parameters={
                                               'action1_val': 'action1',
                                           })
     url_path, actual_headers, actual_body, _ = RestSerializer.serialize_request(
         input_value=input_val,
         ctx=None,
         rest_metadata=rest_metadata,
         is_vapi_rest=True)
     expected_url_path = '/foo/bar?action1=false'
     expected_headers = {}
     expected_body = '{"string_val":"string1"}'
     self.assertEqual(expected_url_path, url_path)
     self.assertEqual(expected_headers, actual_headers)
     self.assertEqual(expected_body, actual_body)
Ejemplo n.º 17
0
 def _invoke(self, raise_error=False):
     ctx = ExecutionContext()
     input_ = StructValue('input')
     input_.set_field('raise', BooleanValue(raise_error))
     return self.provider.invoke(interface_name, mock_method_name, input_,
                                 ctx)
Ejemplo n.º 18
0
import threading
import uuid
from com.vmware.vapi.std_provider import LocalizableMessage
from vmware.vapi.bindings.converter import TypeConverter
from vmware.vapi.common.context import get_context
from vmware.vapi.data.value import (BooleanValue, ListValue, StringValue,
                                    StructValue)
from vmware.vapi.lib.constants import AUTHN_IDENTITY
from vmware.vapi.task.task_manager import TaskManager

URI_DELIMITER = ':'
TASK_EXPIRE_DURATION_SEC = 24 * 60 * 60
PENDING_STRING_VALUE = StringValue('PENDING')
SUCCEEDED_STRING_VALUE = StringValue('SUCCEEDED')
FAILED_STRING_VALUE = StringValue('FAILED')
TRUE_BOOLEAN_VALUE = BooleanValue(True)


class TaskSummary(object):
    """
    TaskSummary class to store task info, operation output type
    and error types
    """
    def __init__(self, info, errors):
        self.info = info
        self.errors = [error.resolved_type for error in errors]

    def __repr__(self):
        args = (repr(self.info), repr(self.errors))
        return 'TaskSummary(info=%s, errors=%s)' % args