示例#1
0
def test_leaks_CIMInstance_property():
    """
    Test function with a CIMInstance object that has one property.
    """
    _ = CIMInstance('CIM_Foo', properties=[
        CIMProperty('P1', value='p'),
    ])
示例#2
0
    def create_cimnamespace_instance(conn, namespace, interop_namespace,
                                     klass):
        """
        Build and execute CreateInstance for an instance of CIM_Namespace using
        the `namespace` parameter as the value of the name property in the
        instance. The instance is created in the `interop_namespace`

        Parameters:

          namespace (:term:`string`):
            Namespace that this instance defines.

          interop_namespace (:term:`string`):
            Interop namespace for this environment.

          klass (:class:`~pywbem.CIMClass`):
            The CIM class CIM_Namespace which is used to create the instance.

        Raises:

            :exc:`~pywbem.CIMError`: For errors encountered with CreateInstance
        """
        properties = NocaseDict([
            ('Name', namespace), ('CreationClassName', klass.classname),
            ('ObjectManagerName', OBJECTMANAGERNAME),
            ('ObjectManagerCreationClassName', OBJECTMANAGERCREATIONCLASSNAME),
            ('SystemName', SYSTEMNAME),
            ('SystemCreationClassName', SYSTEMCREATIONCLASSNAME)
        ])

        new_instance = CIMInstance.from_class(klass,
                                              property_values=properties)
        conn.CreateInstance(new_instance, interop_namespace)
示例#3
0
def test_leaks_CIMInstance_qualifier():
    """
    Test function with a CIMInstance object that has one qualifier.
    """
    _ = CIMInstance('CIM_Foo', qualifiers=[
        CIMQualifier('Q1', value='q'),
    ])
示例#4
0
    def inst_from_classname(self,
                            class_name,
                            namespace=None,
                            property_list=None,
                            property_values=None,
                            include_missing_properties=True,
                            include_path=True):
        # pylint: disable=too-many-arguments
        """
        Build instance from classname using class_name property to get class
        from a repository.
        """
        cls = self.conn.GetClass(class_name,
                                 namespace=namespace,
                                 LocalOnly=False,
                                 IncludeQualifiers=True,
                                 IncludeClassOrigin=True,
                                 PropertyList=property_list)

        return CIMInstance.from_class(
            cls,
            namespace=namespace,
            property_values=property_values,
            include_missing_properties=include_missing_properties,
            include_path=include_path)
示例#5
0
    def inst_from_classname(conn,
                            class_name,
                            namespace=None,
                            property_list=None,
                            property_values=None,
                            include_missing_properties=True,
                            include_path=True):
        # TODO AM 8/18 The inst_from_classname() method is not used.
        """
        Build instance from class using class_name property to get class
        from a repository.
        """
        cls = conn.GetClass(class_name,
                            namespace=namespace,
                            LocalOnly=False,
                            IncludeQualifiers=True,
                            include_class_origin=True,
                            property_list=property_list)

        return CIMInstance.from_class(
            cls,
            namespace=namespace,
            property_values=property_values,
            include_missing_properties=include_missing_properties,
            include_path=include_path)
示例#6
0
    def create_ciminstance(self):
        """
        Create a sample instance with multiple properties and
        property types.
        """
        class TZ(tzinfo):
            """'Simplistic tsinfo subclass for this test"""
            def utcoffset(self, dt):  # pylint: disable=unused-argument
                return timedelta(minutes=-399)

        dt = datetime(year=2016,
                      month=3,
                      day=31,
                      hour=19,
                      minute=30,
                      second=40,
                      microsecond=654321,
                      tzinfo=MinutesFromUTC(120))
        cim_dt = CIMDateTime(dt)
        props_input = {
            'S1':
            b'Ham',
            'Bool':
            True,
            'UI8':
            Uint8(42),
            'UI16':
            Uint16(4216),
            'UI32':
            Uint32(4232),
            'UI64':
            Uint64(4264),
            'SI8':
            Sint8(-42),
            'SI16':
            Sint16(-4216),
            'SI32':
            Sint32(-4232),
            'SI64':
            Sint64(-4264),
            'R32':
            Real32(42.0),
            'R64':
            Real64(42.64),
            'DTI':
            CIMDateTime(timedelta(10, 49, 20)),
            'DTF':
            cim_dt,
            'DTP':
            CIMDateTime(datetime(2014, 9, 22, 10, 49, 20, 524789,
                                 tzinfo=TZ())),
        }
        # TODO python 2.7 will not write the following unicode character
        # For the moment, only add this property in python 3 test
        if six.PY3:
            props_input['S2'] = u'H\u00E4m'  # U+00E4 = lower case a umlaut

        inst = CIMInstance('CIM_Foo', props_input)
        return inst
示例#7
0
    def test_all(self):

        self._run_single(CIMInstance('CIM_Foo'))

        self._run_single(
            CIMInstance(
                'CIM_Foo', {
                    'string': 'string',
                    'uint8': Uint8(0),
                    'uint8array': [Uint8(1), Uint8(2)],
                    'ref': CIMInstanceName('CIM_Bar')
                }))

        self._run_single(
            CIMInstance('CIM_Foo', {'InstanceID': '1234'},
                        path=CIMInstanceName('CIM_Foo',
                                             {'InstanceID': '1234'})))
示例#8
0
def make_instances(cls, number, value_profile):
    """
    Construct and return a number of CIMInstance objects with path, with
    random values for the instance properties.
    """
    insts = []
    for _ in range(0, number):
        inst = CIMInstance(cls.classname)
        # TODO: Make namespace flexible
        inst.path = CIMInstanceName(cls.classname, namespace='root/cimv2')
        for pname, cls_prop in cls.properties.items():
            ptype = cls_prop.type
            _, pvalue = random_type_value(value_profile, type=ptype)
            inst_prop = CIMProperty(pname, type=ptype, value=pvalue)
            inst.properties[pname] = inst_prop
            if cls_prop.qualifiers.get('Key', False):
                inst.path.keybindings[pname] = pvalue
        insts.append(inst)
    return insts
示例#9
0
 def test_close_export(self):  # pylint: disable=no-self-use
     """
     Test closing a connection and invoking an export operation.
     """
     conn = WBEMConnection('http://localhost')
     conn.close()
     assert conn.session is None
     indi = CIMInstance("CIM_AlertIndication")
     with pytest.raises(ConnectionError) as exc_info:
         conn.ExportIndication(NewIndication=indi)
         exc = exc_info.value
         assert re.match(r'is closed', str(exc))
示例#10
0
    def test_inst_to_yaml_array_props(self):
        """Test  property with array toyaml"""
        str_data = "The pink fox jumped over the big blue dog"
        dt = datetime(2014, 9, 22, 10, 49, 20, 524789)
        array_props = {
            'MyString':
            str_data,
            'MyUint8Array': [Uint8(1), Uint8(2)],
            'MySint8Array': [Sint8(1), Sint8(2)],
            'MyUint64Array':
            [Uint64(123456789),
             Uint64(123456789),
             Uint64(123456789)],
            'MyUint32Array': [Uint32(9999), Uint32(9999)],
            'MyDateTimeArray': [dt, dt, dt],
            'MyStrLongArray': [str_data, str_data, str_data]
        }
        inst = CIMInstance('CIM_FooArray', array_props)
        test_yaml = self.test_recorder.toyaml(inst)

        self.assertEqual(test_yaml['pywbem_object'], 'CIMInstance')
        self.assertEqual(test_yaml['classname'], 'CIM_FooArray')
        properties = test_yaml['properties']
        my_string = properties['MyString']
        self.assertEqual(my_string['name'], 'MyString')
        self.assertEqual(my_string['type'], 'string')
        self.assertEqual(my_string['value'], str_data)

        my_uint8array = properties['MyUint8Array']
        self.assertEqual(my_uint8array['name'], 'MyUint8Array')
        self.assertEqual(my_uint8array['type'], 'uint8')
        self.assertEqual(my_uint8array['value'], [Uint8(1), Uint8(2)])

        my_sint8array = properties['MySint8Array']
        self.assertEqual(my_sint8array['name'], 'MySint8Array')
        self.assertEqual(my_sint8array['type'], 'sint8')
        self.assertEqual(my_sint8array['value'], [Sint8(1), Sint8(2)])

        my_sint64array = properties['MyUint64Array']
        self.assertEqual(my_sint64array['name'], 'MyUint64Array')
        self.assertEqual(my_sint64array['type'], 'uint64')
        self.assertEqual(
            my_sint64array['value'],
            [Uint64(123456789),
             Uint64(123456789),
             Uint64(123456789)])

        my_datetimearray = properties['MyDateTimeArray']
        self.assertEqual(my_datetimearray['name'], 'MyDateTimeArray')
        self.assertEqual(my_datetimearray['type'], 'datetime')
        cim_dt = str(CIMDateTime(dt))
        self.assertEqual(my_datetimearray['value'], [cim_dt, cim_dt, cim_dt])
示例#11
0
    def test_all(self):

        # Test instance

        instance = CIMInstance('PyWBEM_Person', {
            'CreationClassName': 'PyWBEM_Person',
            'Name': 'Test'
        },
                               path=CIMInstanceName(
                                   'PyWBEM_Person', {
                                       'CreationClassName': 'PyWBEM_Person',
                                       'Name': 'Test'
                                   }))

        # Delete if already exists
        try:
            self.cimcall(self.conn.DeleteInstance, instance.path)
        except CIMError as ce:
            if ce.args[0] == CIM_ERR_NOT_FOUND:
                pass

        # Create instance

        try:
            self.cimcall(self.conn.CreateInstance, instance)
        except CIMError as ce:
            if ce.args[0] == CIM_ERR_INVALID_CLASS:
                # does not support creation
                pass
        else:

            # Modify instance

            instance['Title'] = 'Sir'

            instance.path.namespace = 'root/cimv2'
            result = self.cimcall(self.conn.ModifyInstance, instance)

            self.assertTrue(result is None)

            # TODO add get and test for change.

            # Clean up

            self.cimcall(self.conn.DeleteInstance, instance.path)
示例#12
0
    def test_all(self):

        # Test instance

        instance = CIMInstance('PyWBEM_Person', {
            'CreationClassName': 'PyWBEM_Person',
            'Name': 'Test'
        },
                               path=CIMInstanceName(
                                   'PyWBEM_Person', {
                                       'CreationClassName': 'PyWBEM_Person',
                                       'Name': 'Test'
                                   }))

        # Delete if already exists (previous test incomplete)

        try:
            self.cimcall(self.conn.DeleteInstance, instance.path)
        except CIMError as ce:
            if ce.args[0] == CIM_ERR_NOT_FOUND:
                pass

        # Simple create and delete

        try:
            result = self.cimcall(self.conn.CreateInstance, instance)
        except CIMError as ce:
            if ce.args[0] == CIM_ERR_INVALID_CLASS:
                # does not support creation
                pass
        else:
            self.assertTrue(isinstance(result, CIMInstanceName))
            self.assertTrue(len(result.namespace) > 0)

            result = self.cimcall(self.conn.DeleteInstance, instance.path)

            self.assertTrue(result is None)

        try:
            self.cimcall(self.conn.GetInstance(instance.path))
        except CIMError as arg:
            if arg == CIM_ERR_NOT_FOUND:
                pass
示例#13
0
    def build_elementconformstoprofile_inst(self, conn, profile_path,
                                            element_path):
        """
        Build an instance of CIM_ElementConformsToProfile and insert into
        repository
        """
        class_name = 'CIM_ElementConformsToProfile'
        element_conforms_dict = {
            'ConformantStandard': profile_path,
            'ManagedElement': element_path
        }

        # TODO modify this when issue #1540  (resolve qualifiers)fixed
        # inst = self.inst_from_classname(conn, class_name,
        #                                namespace=self.interop_ns,
        #                                property_values=element_conforms_dict,
        #                                include_missing_properties=False,
        #                                include_path=True)
        cls = conn.GetClass(class_name,
                            namespace=self.interop_ns,
                            LocalOnly=False,
                            IncludeQualifiers=True,
                            IncludeClassOrigin=True)

        for pvalue in cls.properties.values():
            if pvalue.type == 'reference':
                if "key" not in pvalue.qualifiers:
                    pvalue.qualifiers['Key'] = \
                        CIMQualifier('Key', True, propagated=True)

        inst = CIMInstance.from_class(cls,
                                      namespace=self.interop_ns,
                                      property_values=element_conforms_dict,
                                      include_missing_properties=False,
                                      include_path=True)
        # TODO end of temp code

        conn.add_cimobjects(inst, namespace=self.interop_ns)

        assert conn.EnumerateInstances(class_name, namespace=self.interop_ns)
        assert conn.GetInstance(inst.path)
示例#14
0
    def test_all(self):

        # Single-valued properties

        self._run_single(CIMProperty('Spotty', 'Foot'))
        self._run_single(CIMProperty('Age', Uint16(32)))
        self._run_single(CIMProperty('Foo', '', type='string'))
        self._run_single(CIMProperty('Foo', None, type='string'))
        self._run_single(
            CIMProperty('Age',
                        None,
                        type='uint16',
                        qualifiers={'Key': CIMQualifier('Key', True)}))

        # Property arrays

        self._run_single(CIMProperty('Foo', ['a', 'b', 'c']))
        self._run_single(CIMProperty('Foo', None, type='string',
                                     is_array=True))
        self._run_single(
            CIMProperty('Foo', [Uint8(x) for x in [1, 2, 3]],
                        qualifiers={'Key': CIMQualifier('Key', True)}))

        # Reference properties

        self._run_single(CIMProperty('Foo', None, type='reference'))
        self._run_single(CIMProperty('Foo', CIMInstanceName('CIM_Foo')))
        self._run_single(
            CIMProperty('Foo',
                        CIMInstanceName('CIM_Foo'),
                        qualifiers={'Key': CIMQualifier('Key', True)}))

        # EmbeddedObject properties

        inst = CIMInstance('Foo_Class', {'one': Uint8(1), 'two': Uint8(2)})
        self._run_single(CIMProperty('Foo', inst))
        self._run_single(CIMProperty('Foo', [inst]))
示例#15
0
    'element_conforms_to_profile': [
        (('SNIA', 'Server', '1.2.0'), ("XXX_StorageComputerSystem", {
            'Name':
            "10.1.2.3",
            'CreationClassName':
            "XXX_StorageComputerSystem"
        })),
    ],
    # List of CIMInstances. Each entry is a CIM instance with classname,
    # and properties. All properties required to build the path must be
    # defined. No other properties are required for this test.
    # TODO: We may expand this for more scoping tests.
    'central-instances': [
        CIMInstance('XXX_StorageComputerSystem',
                    properties={
                        'Name': "10.1.2.3",
                        'CreationClassName': "XXX_StorageComputerSystem",
                        'NameFormat': "IP"
                    }),
    ],
    'scoping-instances': []
}


class WbemServerMock(object):
    """
    Class that mocks the classes and methods used by the pywbem
    WBEMServer class so that the WBEMServer class will produce valid data
    for the server CIM_ObjectManager, CIM_Namespace, CIM_RegisteredProfile
    instances.

    This can be used to test the WbemServer class but is also required for
示例#16
0
    def inst_from_class(klass,
                        namespace=None,
                        property_values=None,
                        include_null_properties=True,
                        include_path=True,
                        strict=False,
                        include_class_origin=False):
        """
        Build a new CIMInstance from the input CIMClass using the
        property_values dictionary to complete properties and the other
        parameters to filter properties, validate the properties, and
        optionally set the path component of the CIMInstance.  If any of the
        properties in the class have default values, those values are passed
        to the instance unless overridden by the property_values dictionary.
        No CIMProperty qualifiers are included in the created instance and the
        `class_origin` attribute is transfered from the class only if the
        `include_class_origin` parameter is True

        Parameters:
          klass (:class:`pywbem:CIMClass`)
            CIMClass from which the instance will be constructed.  This
            class must include qualifiers and should include properties
            from any superclasses to be sure it includes all properties
            that are to be built into the instance. Properties may be
            excluded from the instance by not including them in the `klass`
            parameter.

          namespace (:term:`string`):
            Namespace in the WBEMConnection used to retrieve the class or
            `None` if the default_namespace is to be used.

          property_values (dictionary):
            Dictionary containing name/value pairs where the names are the
            names of properties in the class and the properties are the
            property values to be set into the instance. If a property is in
            the property_values dictionary but not in the class an ValueError
            exception is raised.

          include_null_properties (:class:`py:bool`):
            Determines if properties with Null values are included in the
            instance.

            If `True` they are included in the instance returned.

            If `False` they are not included in the instance returned

         inclued_class_origin  (:class:`py:bool`):
            Determines if ClassOrigin information is included in the returned
            instance.

            If None or False, class origin information is not included.

            If True, class origin information is included.

          include_path (:class:`py:bool`:):
            If `True` the CIMInstanceName path is build and inserted into
            the new instance.  If `strict` all key properties must be in the
            instance.

          strict (:class:`py:bool`:):
            If `True` and `include_path` is set, all key properties must be in
            the instance so that

            If not `True` The path component is created even if not all
            key properties are in the created instance.

        Returns:
            Returns an instance with the defined properties and optionally
            the path set.  No qualifiers are included in the returned instance
            and the existence of ClassOrigin depends on the
            `include_class_origin` parameter. The value of each property is
            either the value from the `property_values` dictionary, the
            default_value from the class or Null(unless
            `include_null_properties` is False). All other attributes of each
            property are the same as the corresponding class property.

        Raises:
           ValueError if there are conflicts between the class and
           property_values dictionary or strict is set and the class is not
           complete.
        """
        class_name = klass.classname
        inst = CIMInstance(class_name)
        for p in property_values:
            if p not in klass.properties:
                raise ValueError('Property Name %s in property_values but '
                                 'not in class %s' % (p, class_name))
        for cp in klass.properties:
            ip = klass.properties[cp].copy()
            ip.qualifiers = NocaseDict()
            if not include_class_origin:
                ip.class_origin = None
            if ip.name in property_values:
                ip.value = property_values[ip.name]
            if include_null_properties:
                inst[ip.name] = ip
            else:
                if ip.value:
                    inst[ip.name] = ip

        if include_path:
            inst.path = CIMInstanceName.from_instance(klass,
                                                      inst,
                                                      namespace,
                                                      strict=strict)
        return inst
示例#17
0
    scope='module')
def status_tuple(request):
    """
    Fixture representing variations of CIM status codes for initializing a
    CIMError exception class.

    Returns a tuple of positional arguments for initializing a CIMError
    exception object.
    """
    return request.param


@pytest.fixture(params=[
    None,
    [],
    [CIMInstance('CIM_Err')],
    [CIMInstance('CIM_Err1'), CIMInstance('CIM_Err2')],
],
                scope='module')
def error_instances(request):
    """
    Fixture representing variations of the list of instances that can be
    set on a CIMError exception.

    Returns a list of CIMInstance objects, or None.
    """
    return request.param


def test_cimerror_1(status_tuple, conn_info):
    # pylint: disable=redefined-outer-name
示例#18
0
def test_objectstore(testcase, init_args, cls_kwargs, inst_kwargs, qual_kwargs):
    # pylint: disable=unused-argument
    """
    Simple test inserts one inst of defined type and tests retrievail
    methods.
    """
    namespace = "root/cimv2"

    # Setup the ObjectStore
    xxx_repo = InMemoryObjectStore(*init_args)

    if cls_kwargs:
        cls = CIMClass(**cls_kwargs)
    if inst_kwargs:
        inst = CIMInstance(**inst_kwargs)
        inst.path = CIMInstanceName.from_instance(
            cls, inst, namespace=namespace, host='me', strict=True)
    if qual_kwargs:
        qual = CIMQualifierDeclaration(**qual_kwargs)

    # Is this instance or class test
    if inst_kwargs:
        name = inst.path
        obj = inst
    elif qual_kwargs:
        name = qual.name
        obj = qual
    else:
        name = cls.classname
        obj = cls

    # The code to be tested. The test include adding , getting, and deleting
    # with the various inspection methods and testing for
    # correct returns

    # Create the object in the object store
    xxx_repo.create(name, obj)

    # confirm that exists works
    assert xxx_repo.object_exists(name)

    # Test repository object count; len()
    assert xxx_repo.len() == 1

    # Test get the object and test for same object
    rtn_obj = xxx_repo.get(name)

    # Test that the properties have changed indicating the deepcopy
    # Uses only class and instance because we they have properties
    if isinstance(obj, (CIMClass, CIMInstance)):
        for prop in obj.properties:
            assert rtn_obj.properties[prop] is not \
                obj.properties[prop]

    # Test same object return on two gets
    rtn_obj2 = xxx_repo.get(name)
    assert rtn_obj2 == rtn_obj

    # Test that return with copy gets same object.
    rtn_obj3 = xxx_repo.get(name, copy=True)
    assert rtn_obj3 == obj

    # Test that with copy=True the property ids have changed between the
    # two gets indicating that the deepcopy was executed.
    if isinstance(obj, (CIMClass, CIMInstance)):
        for prop in obj.properties:
            assert rtn_obj.properties[prop] is not \
                rtn_obj3.properties[prop]

    names = list(xxx_repo.iter_names())
    assert len(names) == 1
    assert names[0] == name

    objs = list(xxx_repo.iter_values())
    assert len(objs) == 1
    assert objs[0] == obj

    objs = list(xxx_repo.iter_values(copy=True))
    assert len(objs) == 1
    assert objs[0] == obj

    if isinstance(obj, (CIMClass, CIMInstance)):
        for prop in obj.properties:
            assert objs[0].properties[prop] is not \
                obj.properties[prop]

    # Test update

    # Test update; should work. Note that this test does not modify the
    # object before creating the copy.
    obj2 = obj.copy()
    xxx_repo.update(name, obj2)
    assert xxx_repo.get(name) == obj2

    # Test valid delete of object
    xxx_repo.delete(name)
    assert not xxx_repo.object_exists(name)
    assert xxx_repo.len() == 0

    # Test errors

    # Test update with unknown object; should fail
    try:
        xxx_repo.update(name, obj)
    except KeyError:
        pass

    # Test delete nonexistent entity; should fail
    try:
        xxx_repo.delete(name)
        assert False
    except KeyError:
        pass

    # Test get non existent entity; should fail
    try:
        xxx_repo.get(name)
        assert False
    except KeyError:
        pass

    # Test exists; entity should not exist
    assert not xxx_repo.object_exists(name)

    # Test create with existing object
    xxx_repo.create(name, obj)

    # Test duplicate create; should fail
    try:
        xxx_repo.create(name, obj)
        assert False
    except ValueError:
        pass
示例#19
0
    else:
        with pytest.raises(exp_exc.__class__) as exec_info:

            # The code to be tested
            repo.remove_namespace(test_ns)
            print(exec_info)


TEST_OBJECTS = [
    CIMClass('Foo', properties=[
        CIMProperty('P1', None, type='string',
                    qualifiers=[CIMQualifier('Key', value=True)])]),
    CIMClass('Bar', properties=[
        CIMProperty('P2', None, type='string',
                    qualifiers=[CIMQualifier('Key', value=True)])]),
    CIMInstance('Foo', path=CIMInstanceName('Foo',
                                            keybindings=NocaseDict(P1="P1"))),
    CIMInstance('Bar', path=CIMInstanceName('Bar',
                                            keybindings=NocaseDict(P2="P2"))),
    CIMQualifierDeclaration('Qual1', type='string'),
    CIMQualifierDeclaration('Qual2', type='string'), ]

TEST_OBJECTS2 = [
    CIMClass('Foo', properties=[
        CIMProperty('P2', None, type='string',
                    qualifiers=[CIMQualifier('Key', value=True)])]),
    CIMInstance('Foo', path=CIMInstanceName('Foo',
                                            keybindings=NocaseDict(P2="P2"))),
]


@pytest.mark.parametrize(
示例#20
0
     ), None, None, True),

    # Other CIM object tests
    (
        "Object is a CIMClass object",
        dict(
            obj=CIMClass('CIM_Foo'),
            exp_type_name=u'string',  # embedded object
        ),
        None,
        None,
        True),
    (
        "Object is a CIMInstance object",
        dict(
            obj=CIMInstance('CIM_Foo'),
            exp_type_name=u'string',  # embedded object
        ),
        None,
        None,
        True),
    ("Object is a CIMInstanceName object",
     dict(
         obj=CIMInstanceName('CIM_Foo'),
         exp_type_name=u'reference',
     ), None, None, True),
    ("Object is a CIMClassName object",
     dict(
         obj=CIMClassName('CIM_Foo'),
         exp_type_name=None,
     ), TypeError, None, True),
示例#21
0
    def test_all(self):

        self._run_single(CIMInstance('CIM_Foo'))
        self._run_single(CIMInstance('CIM_Foo', {'InstanceID': '1234'}))
示例#22
0
 def test_embeddedobject_properties(self):
     """Test EmbeddedObject properties"""
     inst = CIMInstance('Foo_Class',
                        {'one': Uint8(1), 'two': Uint8(2)})
     self._run_single(CIMProperty('Foo', inst))
     self._run_single(CIMProperty('Foo', [inst]))
示例#23
0
      method='enumerateinstances',
      args=[CIMInstanceName("CIM_Blah")],
      kwargs={},
  ), TypeError, None, OK),
 ("Test GetInstance, invalid InstanceName tyhpe",
  dict(
      init_kwargs={},
      method='getinstance',
      args=[CIMClassName("CIM_Blah")],
      kwargs={},
  ), TypeError, None, OK),
 ("Test ModifyInstance, No path in ModifiedInstance",
  dict(
      init_kwargs={},
      method='modifyinstance',
      args=[CIMInstance("CIMBlah")],
      kwargs={},
  ), ValueError, None, OK),
 ("Test EnumerateInstances, Invalid args type",
  dict(
      init_kwargs={},
      method='enumerateinstances',
      args=[CIMClass("CIMBlah")],
      kwargs={},
  ), TypeError, None, OK),
 ("Test OpenEnumerateInstances, Invalid type for operationtimeout",
  dict(
      init_kwargs={},
      method='openenumerateinstances',
      args=[CIMClass("CIMBlah")],
      kwargs={"OperationTimeout": "shouldbeinteger"},
示例#24
0
"""
Test file for use with wbemcli -mock-server parameter that adds an instance
to the mock repository
This file assumes that the file simple_mock_model.mof has already been loaded
so the class CIM_Foo exists.
"""

from __future__ import absolute_import, print_function

from ..utils import import_installed
pywbem = import_installed('pywbem')  # noqa: E402

from pywbem import CIMInstance, CIMInstanceName

_INAME = 'CIM_Foo%s' % 'wbemcli_tst-1'
_INST_PATH = CIMInstanceName('CIM_Foo', {'InstanceID': _INAME})
_INST = CIMInstance('CIM_Foo',
                    properties={'InstanceID': _INAME},
                    path=_INST_PATH)

# CONN is a defined global variable in the wbemcli environment
global CONN  # pylint: disable=global-at-module-level

CONN.add_cimobjects(_INST)  # noqa: F821 pylint: disable=undefined-variable

# test that instance inserted
assert(CONN.GetInstance(_INST_PATH))  # noqa: F821,E501 pylint: disable=undefined-variable
示例#25
0
def test_objectstore(testcase, init_args, cls_kwargs, inst_kwargs, qual_kwargs):
    # pylint: disable=unused-argument
    """
    Simple test inserts one inst of defined type and tests retrievail
    methods.
    """
    namespace = "root/cimv2"

    # Setup the ObjectStore
    xxx_repo = InMemoryObjectStore(*init_args)

    if cls_kwargs:
        cls = CIMClass(**cls_kwargs)
    if inst_kwargs:
        inst = CIMInstance(**inst_kwargs)
        inst.path = CIMInstanceName.from_instance(
            cls, inst, namespace=namespace, host='me', strict=True)
    if qual_kwargs:
        qual = CIMQualifierDeclaration(**qual_kwargs)

    # is this instance or class test
    if inst_kwargs:
        name = inst.path
        obj = inst
    elif qual_kwargs:
        name = qual.name
        obj = qual
    else:
        name = cls.classname
        obj = cls

    # The code to be tested. The test include adding and testing the
    # various inspection methods for correct returns

    # Create the object in the object store
    xxx_repo.create(name, obj)

    # confirm that exists works
    assert xxx_repo.exists(name)

    # Test len()
    assert xxx_repo.len() == 1

    # Test get the object and test for same object
    rtn_obj = xxx_repo.get(name)
    assert rtn_obj == obj

    names = [n for n in xxx_repo.iter_names()]
    assert len(names) == 1
    assert names[0] == name

    objs = [x for x in xxx_repo.iter_values()]
    assert len(objs) == 1
    assert objs[0] == obj

    # Test update

    # Test update; should work
    obj2 = obj.copy()
    xxx_repo.update(name, obj2)
    assert xxx_repo.get(name) == obj2

    # Test valid delete of object
    xxx_repo.delete(name)
    assert not xxx_repo.exists(name)
    assert xxx_repo.len() == 0

    # Test errors

    # Test update with unknown object; should fail
    try:
        xxx_repo.update(name, obj)
    except KeyError:
        pass

    # Test delete nonexistent entity; should fail
    try:
        xxx_repo.delete(name)
        assert False
    except KeyError:
        pass

    # Test get non existent entity; should fail
    try:
        xxx_repo.get(name)
        assert False
    except KeyError:
        pass

    # Test exists; entity should not exist
    assert not xxx_repo.exists(name)

    # Test create with existing object
    xxx_repo.create(name, obj)

    # Test duplicate create; should fail
    try:
        xxx_repo.create(name, obj)
        assert False
    except ValueError:
        pass
示例#26
0
    def build_referenced_profile_insts(self, server, referenced_profiles):
        """
        Build and install in repository the referemced profile instances
        defined by the referemces parameter. A dictionary of tuples where each
        tuple contains Antecedent and Dependent reference in terms of the
        profile name as a tuple (org, name, version).

        Parameters:
          conn:
          profiles (dict of tuples where each tuple defines the antecedent
          and dependent)
        """
        class_name = 'CIM_ReferencedProfile'
        for profile_name in referenced_profiles:
            antecedent = profile_name[0]
            dependent = profile_name[1]
            antecedent_inst = server.get_selected_profiles(
                registered_org=antecedent[0],
                registered_name=antecedent[1],
                registered_version=antecedent[2])
            dependent_inst = server.get_selected_profiles(
                registered_org=dependent[0],
                registered_name=dependent[1],
                registered_version=dependent[2])

            assert len(antecedent_inst) == 1, \
                "Antecedent: {0}".format(antecedent)
            assert len(dependent_inst) == 1, \
                "Dependent: {0}".format(dependent)

            ref_profile_dict = {
                'Antecedent': antecedent_inst[0].path,
                'Dependent': dependent_inst[0].path
            }

            # TODO replace the setting of key qualifier with the commented
            # code with #issue 1540 is fixed, i.e the key qualifier is
            # included in the class.
            # inst = self.inst_from_classname(server.conn, class_name,
            #                                namespace=self.interop_ns,
            #                                property_values=ref_profile_dict,
            #                                include_missing_properties=False,
            #                                include_path=True)

            cls = server.conn.GetClass(class_name,
                                       namespace=self.interop_ns,
                                       LocalOnly=False,
                                       IncludeQualifiers=True,
                                       IncludeClassOrigin=True,
                                       PropertyList=None)

            for pvalue in cls.properties.values():
                if pvalue.type == 'reference':
                    if "key" not in pvalue.qualifiers:
                        pvalue.qualifiers['Key'] = \
                            CIMQualifier('Key', True, propagated=True)

            inst = CIMInstance.from_class(cls,
                                          namespace=self.interop_ns,
                                          property_values=ref_profile_dict,
                                          include_missing_properties=False,
                                          include_path=True)
            # TODO end of code to drop for #1540 fix

            server.conn.add_cimobjects(inst, namespace=self.interop_ns)

            assert server.conn.EnumerateInstances(class_name,
                                                  namespace=self.interop_ns)
            assert server.conn.GetInstance(inst.path)
示例#27
0
def test_leaks_CIMInstance_minimal():
    """
    Test function with a minimal CIMInstance object (i.e. no properties, no
    qualifiers).
    """
    _ = CIMInstance('CIM_Foo', )