Ejemplo n.º 1
0
def test_cimtype(desc, kwargs, exp_exc_types, exp_warn_types, condition):
    """
    All test cases for cimtype().
    """

    obj = kwargs['obj']

    # The code to be tested
    type_name = cimtype(obj)

    exp_type_name = kwargs['exp_type_name']

    assert type_name == exp_type_name
Ejemplo n.º 2
0
def test_cimtype(testcase, obj, exp_type_name):
    """
    Test function for cimtype().
    """

    # The code to be tested
    type_name = cimtype(obj)

    # Ensure that exceptions raised in the remainder of this function
    # are not mistaken as expected exceptions
    assert testcase.exp_exc_types is None

    assert type_name == exp_type_name
 def pywbem2cmpi_data(self, pdata, _type=None):
     is_array = isinstance(pdata, list)
     if _type is None:
         _type = pywbem.cimtype(pdata)
     # This doesn't work below.  cmpi.CMPIData() takes a CMPIData argument. ??
     data = cmpi.CMPIData()
     data.state = 0
     data.type = _pywbem2cmpi_typemap[_type]
     if is_array:
         data.type = data.type | cmpi.CMPI_ARRAY
     if _type == 'reference':
         _type = 'ref'
         pdata = self.pywbem2cmpi_instname(pdata)
     self.pywbem2cmpi_value(pdata, _type, data.value)
     return data
Ejemplo n.º 4
0
def test_cimtype(testcase, obj, exp_type_name):
    """
    Test function for cimtype().
    """

    # There are no init testcases covering all CIM types, so the following
    # check is placed here.
    # TODO: Create init testcaes for CIM types and move this check to there.
    assert not hasattr(obj, '__dict__')

    # The code to be tested
    type_name = cimtype(obj)

    # Ensure that exceptions raised in the remainder of this function
    # are not mistaken as expected exceptions
    assert testcase.exp_exc_types is None

    assert type_name == exp_type_name
 def pywbem2cmpi_value(self, pdata, _type=None, cval=None):
     if pdata is None:
         assert(_type is not None)
         return None, _type
     is_array = isinstance(pdata, list)
     if _type is None:
         if isinstance(pdata, pywbem.CIMInstance):
             _type = 'instance'
         elif isinstance(pdata, pywbem.CIMInstanceName):
             _type = 'reference'
         else:
             _type = pywbem.cimtype(pdata)
     attr = _type
     if cval is None:
         cval = cmpi.CMPIValue()
     if is_array:
         ralen = len(pdata)
         ctype = _pywbem2cmpi_typemap[_type]
         car = self.broker.new_array(ralen, ctype)
         for i, rael in enumerate(pdata):
             cv, tt = self.pywbem2cmpi_value(rael, _type=_type)
             car.set(i, cv, ctype)
         cval.array = car
         return cval, _type
     if _type == 'reference':
         attr = 'ref'
         pdata = self.pywbem2cmpi_instname(pdata)
     elif _type == 'string':
         pdata = self.broker.new_string(str(pdata))
     elif _type == 'datetime':
         attr = 'dateTime'
         pdata = self.pywbem2cmpi_datetime(pdata)
     elif _type == 'instance':
         attr = 'inst'
         pdata = self.pywbem2cmpi_inst(pdata)
     elif _type == 'chars':
         pdata = self.broker.new_string(str(pdata))
     setattr(cval, attr, pdata)
     return cval, _type
Ejemplo n.º 6
0
    def InvokeMethod(self, methodname, localobject, params):
        # pylint: disable=invalid-name
        """
        Dispatcher for the InvokeMethod provider method.

        This method performs validations and if successful, routes the provider
        method call either to a registered provider, or to the default provider.

        Parameters:

          methodname (string): Method name

          localobject (CIMInstanceName or CIMClassName): Target object, with
            namespace set. Types are validated.

          params (NocaseDict): Input parameters, as follows:
            * key (string): Parameter name.
            * value (CIMParameter): Parameter value.
            Types are validated.

        Returns:

          A tuple of (returnvalue, outparams), with these tuple items:

            * returnvalue (CIM data type): Return value.

            * outparams (NocaseDict): Output parameters, with:
              * key (string): Parameter name
              * value (CIM data type): Parameter value
        """

        namespace = localobject.namespace

        # Verify the input parameter types (type errors have already been
        # raised during checks in WBEMConnection.InvokeMethod(), and in
        # FakedWBEMConnection._mock_methodcall()).
        assert isinstance(namespace, six.string_types)
        assert isinstance(methodname, six.string_types)
        assert isinstance(localobject, (CIMInstanceName, CIMClassName))
        assert isinstance(params, NocaseDict)

        # Verify that the namespace exists in the CIM repository.
        self.validate_namespace(namespace)

        class_store = self.cimrepository.get_class_store(namespace)
        instance_store = self.cimrepository.get_instance_store(namespace)

        if isinstance(localobject, CIMInstanceName):
            # instance-level use

            # Get the creation class of the target instance from the CIM
            # repository, verifying that it exists.
            try:
                klass = class_store.get(localobject.classname)
            except KeyError:
                raise CIMError(
                    CIM_ERR_INVALID_CLASS,
                    _format(
                        "Creation class {0!A} of target instance does "
                        "not exist in namespace {1!A} of the CIM "
                        "repository.", localobject.classname, namespace))

            # Verify that the target instance exists in the CIM repository.
            if not instance_store.object_exists(localobject):
                raise CIMError(
                    CIM_ERR_NOT_FOUND,
                    _format(
                        "Target instance does not exist in the CIM "
                        "repository: {0!A}", localobject))

        else:
            assert isinstance(localobject, CIMClassName)
            # class-level use

            # Get the target class from the CIM repository, verifying that it
            # exists.
            try:
                klass = class_store.get(localobject.classname)
            except KeyError:
                raise CIMError(
                    CIM_ERR_NOT_FOUND,
                    _format(
                        "Target class {0!A} does not exist in namespace "
                        "{1!A} of the CIM repository.", localobject.classname,
                        namespace))

        # Verify that the class exposes the CIM method.
        if methodname not in klass.methods:
            raise CIMError(
                CIM_ERR_METHOD_NOT_FOUND,
                _format(
                    "Method {0!A} is not exposed by class {1!A} in "
                    "namespace {2!A} of the CIM repository.", methodname,
                    klass.classname, namespace))
        method = klass.methods[methodname]

        if isinstance(localobject, CIMClassName):
            # class-level use

            # Verify that the method is static.
            # Note: A similar check for instance-level use is not appropriate
            # because static methods can be invoked on instances or on classes.
            static_qual = method.qualifiers.get('Static')
            static_value = static_qual.value if static_qual else False
            if not static_value:
                raise CIMError(
                    CIM_ERR_INVALID_PARAMETER,
                    _format(
                        "Non-static method {0!A} in class {1!A} in "
                        "namespace {2!A} cannot be invoked on a class "
                        "object.", methodname, klass.classname, namespace))

        # Verify that the input parameters are defined by the method and have
        # the correct type-related attributes.
        for pn in params:
            assert isinstance(pn, six.string_types)
            param_in = params[pn]
            assert isinstance(param_in, CIMParameter)

            if pn not in method.parameters:
                raise CIMError(
                    CIM_ERR_INVALID_PARAMETER,
                    _format(
                        "The specified input parameter {0!A} is not "
                        "defined in method {1!A} of class {2!A} in "
                        "namespace {3!A} of the CIM repository", pn,
                        methodname, klass.classname, namespace))

            param_cls = method.parameters[pn]

            in_qual = method.qualifiers.get('In')
            in_value = in_qual.value if in_qual else True
            if not in_value:
                raise CIMError(
                    CIM_ERR_INVALID_PARAMETER,
                    _format(
                        "The specified input parameter {0!A} is "
                        "defined as an output-only parameter according to "
                        "its method {1!A} of class {2!A} in namespace "
                        "{3!A} of the CIM repository", pn, methodname,
                        klass.classname, namespace))

            if param_in.type != param_cls.type:
                raise CIMError(
                    CIM_ERR_INVALID_PARAMETER,
                    _format(
                        "The specified input parameter {0!A} has "
                        "incorrect type={1!A}, but should have type={2!A} "
                        "according to its method {3!A} in class {4!A} in "
                        "namespace {5!A} of the CIM repository", pn,
                        param_in.type, param_cls.type, methodname,
                        klass.classname, namespace))

            if param_in.is_array != param_cls.is_array:
                raise CIMError(
                    CIM_ERR_INVALID_PARAMETER,
                    _format(
                        "The specified input parameter {0!A} has "
                        "incorrect is_array={1!A}, but should have "
                        "is_array={2!A} "
                        "according to its method {3!A} in class {4!A} in "
                        "namespace {5!A} of the CIM repository", pn,
                        param_in.is_array, param_cls.is_array, methodname,
                        klass.classname, namespace))

            if param_in.embedded_object != param_cls.embedded_object:
                raise CIMError(
                    CIM_ERR_INVALID_PARAMETER,
                    _format(
                        "The specified input parameter {0!A} has "
                        "incorrect embedded_object={1!A}, but should have "
                        "embedded_object={2!A} "
                        "according to its method {3!A} in class {4!A} in "
                        "namespace {5!A} of the CIM repository", pn,
                        param_in.embedded_object, param_cls.embedded_object,
                        methodname, klass.classname, namespace))

        # Determine the provider to be used.
        provider = self.provider_registry.get_registered_provider(
            namespace, 'method', klass.classname)
        if not provider:
            provider = self.default_method_provider

        # Call the provider method
        result = provider.InvokeMethod(methodname, localobject, params)

        # Verify provider method result
        if not isinstance(result, (list, tuple)):
            raise TypeError(
                _format(
                    "InvokeMethod provider method returned invalid type: "
                    "{0}. Must return list/tuple (return value, output "
                    "parameters)", type(result)))
        if len(result) != 2:
            raise ValueError(
                _format(
                    "InvokeMethod provider method returned invalid number "
                    "of items: {0}. Must be list/tuple (return value, "
                    "output parameters)", len(result)))
        return_value = result[0]
        output_params = result[1]

        # Map the more flexible way output parameters can be returned from
        # the provider method to what _mock_methodcall() expects
        output_params_dict = NocaseDict()
        if isinstance(output_params, Sequence):
            # sequence of CIMParameter
            for param in output_params:
                if not isinstance(param, CIMParameter):
                    raise TypeError(
                        _format(
                            "InvokeMethod provider method returned invalid "
                            "type for item in output parameters "
                            "sequence: {0}. Item type must be "
                            "CIMParameter", type(param)))
                output_params_dict[param.name] = param.value
        elif isinstance(output_params, Mapping):
            # mapping of name:value or name:CIMParameter
            for pname in output_params:
                pvalue = output_params[pname]
                if isinstance(pvalue, CIMParameter):
                    pvalue = pvalue.value
                else:
                    # Perform check for valid CIM data type:
                    try:
                        cimtype(pvalue)
                    except TypeError:
                        new_exc = TypeError(
                            _format(
                                "InvokeMethod provider method returned "
                                "invalid type for value in output "
                                "parameters mapping: {0}. Value type must "
                                "be a CIM data type or CIMParameter",
                                type(pvalue)))
                        new_exc.__cause__ = None
                        raise new_exc
                    except ValueError:
                        # Empty array
                        pass
                output_params_dict[pname] = pvalue
        else:
            raise TypeError(
                _format(
                    "InvokeMethod provider method returned invalid type "
                    "for output parameters: {0}. Must be "
                    "Sequence(CIMParameter) or "
                    "Mapping(name: value/CIMParameter)", type(output_params)))

        return return_value, output_params_dict
def test_conversions(proxy):
    s = 'foo'
    cs, _type = pywbem2cmpi_value(s)
    assert(cs.string.__str__() == s)
    assert(_type == 'string')
    ns = cmpi2pywbem_value(cs, _type)
    assert(s == ns)
    #cdata = cmpi.CMPIData(None)
    i = pywbem.Uint32(5)
    ci, _type = pywbem2cmpi_value(i)
    assert(_type == 'uint32')
    assert(ci.uint32 == i)
    ni = cmpi2pywbem_value(ci, _type)
    assert(isinstance(ni, pywbem.Uint32))
    assert(i == ni)
    l = ['python','is','great']
    cl, _type = pywbem2cmpi_value(l)
    nl = cmpi2pywbem_value(cl, _type, is_array=True)
    assert(nl == l)

    l = [pywbem.Real32(3.4), pywbem.Real32(3.14159)] 
    cl, _type = pywbem2cmpi_value(l)
    nl = cmpi2pywbem_value(cl, _type, is_array=True)
    assert(_type == 'real32')
    for i in xrange(0, len(l)):
        assert(abs(l[i] - nl[i]) <= 0.001)

            
    

    #print s == cmpi2pywbem_

    pcop = pywbem.CIMInstanceName('Cmpi_Swig', namespace='root/cimv2', 
            keybindings={'k1':'A', 'k2':'B'})
    ccop = pywbem2cmpi_instname(pcop)
    ncop = cmpi2pywbem_instname(ccop)
    assert(ncop.classname == 'Cmpi_Swig')
    assert(ncop.namespace == 'root/cimv2')
    assert(len(ncop.keybindings) == 2)
    assert(ncop['k1'] == 'A')
    assert(ncop['k2'] == 'B')

    cinst = cmpi.CMPIInstance(proxy.broker, ccop)
    assert(cinst.objectpath() is not None)

    pinst = pywbem.CIMInstance('Cmpi_Swig', path=pcop, 
            properties={'k1':'A', 'k2':'B',
                'p3':'string prop', 
                'p4':pywbem.Uint32(47)
                })
    cinst = pywbem2cmpi_inst(pinst)
    ninst = cmpi2pywbem_inst(cinst)
    assert(ninst.classname == pinst.classname)
    pinst.properties['n'] = pywbem.CIMProperty('n', None, type='uint32')
    cinst = pywbem2cmpi_inst(pinst)
    ninst = cmpi2pywbem_inst(cinst)
    #assert(ninst['n'] is None)
    assert(ninst.classname == pinst.classname)
    pinst['sint16'] = pywbem.Sint16(16)
    cinst = pywbem2cmpi_inst(pinst)
    ninst = cmpi2pywbem_inst(cinst)
    assert(ninst['sint16'] == 16)
    pinst['sint8'] = pywbem.Sint8(8)
    cinst = pywbem2cmpi_inst(pinst)
    ninst = cmpi2pywbem_inst(cinst)
    assert(ninst['sint8'] == 8)
    pinst['uint8a'] = [pywbem.Uint8(1), pywbem.Uint8(2), pywbem.Uint8(3)]
    cinst = pywbem2cmpi_inst(pinst)
    ninst = cmpi2pywbem_inst(cinst)
    assert(ninst['uint8a'] == pinst['uint8a'])

    pdt = pywbem.CIMDateTime.now()
    cdt = pywbem2cmpi_datetime(pdt)
    ndt = cmpi2pywbem_datetime(cdt)
    assert(pdt == ndt)
    cdt = proxy.broker.new_datetime_from_string('20080623144759.823564-360')
    print '** ctd.is_interval()', cdt.is_interval()
    print '** ctd.__str__()', cdt.__str__()

    pinst['dt'] = pywbem.CIMDateTime('20080623144759.823564-360')
    cinst = pywbem2cmpi_inst(pinst)
    ninst = cmpi2pywbem_inst(cinst)
    print '** ninst["dt"]', ninst['dt']
    print '** pinst["dt"]', pinst['dt']
    assert(ninst['dt'] == pinst['dt'])

    pargs = {
            'one':'one',
            'two':pywbem.Uint32(43), 
            'three':pywbem.CIMDateTime.now(),
            'four':['one','two','three'],
            'five':[pywbem.CIMDateTime.now(), pywbem.CIMDateTime.now()],
            'six':[pywbem.Sint32(-1), pywbem.Sint32(-2)]
            }
    iargs = dict([(k, (pywbem.cimtype(v), v)) for k, v in pargs.items()])
    cargs = pywbem2cmpi_args(iargs)
    nargs = cmpi2pywbem_args(cargs)
    assert(pargs == nargs)


    print '** tests passed'