def test_reference_properties(self): """Test 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)}))
def create_ciminstancename(self): kb = {'Chicken': 'Ham', 'Beans': 42} obj_name = CIMInstanceName('CIM_Foo', kb, namespace='root/cimv2', host='woot.com') return obj_name
def CreateInstance(self, *args, **kwargs): """ Create a CIM instance in the local repository of this class. This method is derived from the the same method in the pywbem mof compiler but modified to: 1. Use a dictionary as the container for instances where the key is the path. This means that all instances must have a path component to be inserted into the repository. Normally the path component is built within the compiler by using the instance alias. 2. Fail with a CIMError exception if the instance already exists in the repository. For a description of the parameters, see :meth:`pywbem.WBEMConnection.CreateInstance`. """ namespace = self.default_namespace inst = args[0] if args else kwargs['NewInstance'] # Get list of properties in class defined for this instance cln = inst.classname cls = self.GetClass(cln, IncludeQualifiers=True, LocalOnly=False) cls_key_properties = [ p for p, v in cls.properties.items() if 'key' in v.qualifiers ] # Validate all key properties are in instance for pname in cls_key_properties: if pname not in inst.properties: raise CIMError( CIM_ERR_INVALID_PARAMETER, _format( 'CreateInstance failed. Key property {0!A} in ' 'class {1!A} but not in new_instance: {2!A}', pname, cln, str(inst))) # Build path from instance and class if inst.path is None or not inst.path.keybindings: inst.path = CIMInstanceName.from_instance( cls, inst, namespace=self.default_namespace) # Exception if duplicate. NOTE: compiler overrides this with # modify instance. instance_store = self.repo.get_instance_store(namespace) if instance_store.exists(inst.path): raise CIMError( CIM_ERR_ALREADY_EXISTS, _format( 'CreateInstance failed. Instance with path {0!A} ' 'already exists in mock repository', inst.path)) try: # TODO: This should go through self.conn.CreateInstance instance_store.create(inst.path, inst) except KeyError: raise return inst.path
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'})))
def test_leaks_CIMInstanceName_minimal(): """ Test function with a CIMInstanceName object that has keybindings with two keys. """ _ = CIMInstanceName( 'CIM_Foo', namespace='root', host='woot.com', keybindings=dict(P1='a', P2=42), )
def test_all(self): self._run_single(CIMInstanceName('CIM_Foo')) self._run_single( CIMInstanceName('CIM_Foo', { 'Name': 'Foo', 'Chicken': 'Ham' })) self._run_single( CIMInstanceName( 'CIM_Foo', { 'Name': 'Foo', 'Number': 42, 'Boolean': False, 'Ref': CIMInstanceName('CIM_Bar') })) self._run_single( CIMInstanceName('CIM_Foo', {'Name': 'Foo'}, namespace='root/cimv2')) self._run_single( CIMInstanceName('CIM_Foo', {'Name': 'Foo'}, host='woot.com', namespace='root/cimv2'))
def test_all(self): self._run_single('<INSTANCENAME CLASSNAME="CIM_Foo"/>', CIMInstanceName('CIM_Foo')) self._run_single( '<INSTANCENAME CLASSNAME="CIM_Foo"><KEYBINDING NAME="InstanceID">' '<KEYVALUE VALUETYPE="string">1234</KEYVALUE></KEYBINDING>' '</INSTANCENAME>', CIMInstanceName('CIM_Foo', {'InstanceID': '1234'})) # XXX: single KEYVALUE form not supported self._run_single( '<INSTANCENAME CLASSNAME="CIM_Foo"><KEYBINDING NAME="Ref">' '<VALUE.REFERENCE><INSTANCENAME CLASSNAME="CIM_Bar">' '<KEYBINDING NAME="InstanceID"><KEYVALUE VALUETYPE="string">' '1234</KEYVALUE></KEYBINDING></INSTANCENAME></VALUE.REFERENCE>' '</KEYBINDING></INSTANCENAME>', CIMInstanceName( 'CIM_Foo', {'Ref': CIMInstanceName('CIM_Bar', {'InstanceID': '1234'})}))
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]))
def build_central_instances(self, conn, central_instances): """ Build the central_instances from the definitions provided in the list central_instance where each definition is a python CIMInstance object and add them to the repositoryu. This method adds the path to each """ for inst in central_instances: cls = conn.GetClass(inst.classname, namespace=self.interop_ns, LocalOnly=False, IncludeQualifiers=True, IncludeClassOrigin=True) inst.path = CIMInstanceName.from_instance( cls, inst, namespace=self.interop_ns, strict=True) conn.add_cimobjects(inst, namespace=self.interop_ns)
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)
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
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
def test_complexassoc_instnames(conn, ns, target, ro, rr, ac, rc, mof, exp_rslt, complex_assoc_mof, cond): # pylint: disable=redefined-outer-name,invalid-name """ Test associatornames class operations against a ternary model defined by the fixture complex_assoc_mof """ if not cond: pytest.skip("Condition for test case not met") if cond == 'pdb': # pylint: disable=import-outside-toplevel import pdb pdb.set_trace() # pylint: disable=forgotten-debug-statement skip_if_moftab_regenerated() mof = mof or "" conn.compile_mof_string(complex_assoc_mof + mof, namespace=ns) if VERBOSE: conn.display_repository() assert isinstance(target, (tuple, list)) for rslt in exp_rslt: assert isinstance(rslt, (tuple, list)) target_inst = CIMInstanceName(target[0], keybindings={'InstanceID': target[1]}, namespace=ns) exp_ns = ns or conn.default_namespace exp_instnames = [] if exp_rslt: for item in exp_rslt: assert conn.GetClass(item[0]) # Test to assure class exists exp_instnames.append( CIMInstanceName(item[0], keybindings={'InstanceID': item[1]}, namespace=exp_ns, host=conn.host)) rtn_instnames = conn.AssociatorNames(target_inst, AssocClass=ac, Role=ro, ResultRole=rr, ResultClass=rc) assert isinstance(rtn_instnames, list) for instname in rtn_instnames: assert isinstance(instname, CIMInstanceName) assert instname.host == conn.host assert instname.namespace == exp_ns rtn_instnames_str = [str(n) for n in rtn_instnames] exp_instnames_str = [str(n) for n in exp_instnames] if VERBOSE: print('\nACT:\n%s\nEXP:\n%s' % ("\n".join(rtn_instnames_str), "\n".join(exp_instnames_str))) request = "pywbemcli class associators {0} --role {1} --assoc-class {2} " \ "--result-role {3} --result-class {4}". \ format(target_inst, ro, ac, rr, rc) save_data(conn, complex_assoc_mof, request, rtn_instnames_str, exp_instnames_str) assert set(exp_instnames) == set(rtn_instnames)
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
def test_complexref_instnames(conn, ns, target, ro, rc, mof, exp_rslt, complex_assoc_mof, cond): # pylint: disable=redefined-outer-name,invalid-name """ Test referencenames class operations against a ternary model defined by the fixture complex_assoc_mof """ if not cond: pytest.skip("Condition for test case not met") skip_if_moftab_regenerated() mof = mof or "" conn.compile_mof_string(complex_assoc_mof + mof, namespace=ns) if cond == 'pdb': # pylint: disable=import-outside-toplevel import pdb pdb.set_trace() # pylint: disable=forgotten-debug-statement target_inst = CIMInstanceName(target[0], keybindings={'InstanceID': target[1]}, namespace=ns) rtn_instnames = conn.ReferenceNames(target_inst, ResultClass=rc, Role=ro) exp_ns = ns or conn.default_namespace assert isinstance(rtn_instnames, list) for instname in rtn_instnames: assert isinstance(instname, CIMInstanceName) assert instname.host == conn.host assert instname.namespace == exp_ns # Build the expected instance name to be returned. With the defined model # this is the association with 3 references. Each entry in exp_rslt # defines a classname and 3 integers representing the InstanceID of the # reference property exp_instnames = [] if exp_rslt: for response_item in exp_rslt: kb = {} for prop_def, prop_value in response_item[1].items(): kb[prop_def] = CIMInstanceName( prop_value[0], keybindings={'InstanceID': prop_value[1]}, namespace=exp_ns) exp_instnames.append( CIMInstanceName(response_item[0], keybindings=kb, namespace=exp_ns, host=conn.host)) rtn_instnames_str = [str(n) for n in rtn_instnames] exp_instnames_str = [str(n) for n in exp_instnames] if VERBOSE: print('\nACT:\n%s\nEXP:\n%s' % ("\n".join(rtn_instnames_str), "\n".join(exp_instnames_str))) request = "pywbemcli class references {0} --role {1} --result_class {2}". \ format(target_inst, ro, rc) save_data(conn, complex_assoc_mof, request, rtn_instnames_str, exp_instnames_str) assert set(exp_instnames) == set(rtn_instnames)
# pylint: enable=wrong-import-position, wrong-import-order, invalid-name TESTCASES_PERF_EQ = [ # Testcases for performance tests for equality tests # Each list item is a testcase tuple with these items: # * desc: Short testcase description. # * obj1: Object #1 for equality test. # * obj2: Object #2 for equality test. ( "CIMInstanceName with two keybindings, last one different", CIMInstanceName( 'CIM_Foo', keybindings=dict( Chicken='Ham', Beans=Uint8(42), ), ), CIMInstanceName( 'CIM_Foo', keybindings=dict( Chicken='Ham', Beans=Uint8(43), ), ), ), ( "CIMClass with 10 properties, last one different", CIMClass( 'CIM_Foo',
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(
), 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), ] @pytest.mark.parametrize( "desc, kwargs, exp_exc_types, exp_warn_types, condition", TESTCASES_CIMTYPE) @simplified_test_function def test_cimtype(testcase, obj, exp_type_name):
def CreateInstance(self, namespace, new_instance): """ Default provider method for :meth:`pywbem.WBEMConnection.CreateInstance`. Create a new CIM instance in the CIM repository of the mock WBEM server. Validation already performed by the provider dispatcher that calls this provider method: - The provider method is called only for the registered class and namespace (only applies to user-defined providers). - The Python types of all input parameters to this provider method are as specified below. - The namespace exists in the CIM repository. - The creation class of the new instance exists in the namespace in the CIM repository. - All properties specified in the new instance are exposed (i.e. defined and inherited with any overrides resolved) by the creation class in the CIM repository, and have the same type-related attributes (i.e. type, is_array, embedded_object). Validation that should be performed by this provider method: - new_instance does not specify any properties that are not allowed to be initialized by the client, depending on the model implemented by the provider. - new_instance specifies all key properties needed by the provider, depending on the model implemented by the provider. The CIM repository will reject any new instance that does not have all key properties specified. - The new instance (i.e. an instance with the new instance path) does not exist in the CIM repository. This validation needs to be done by the provider because the determination of the key properties for the new instance path may depend on the model implemented by the provider. The CIM repository will reject the creation of instances that already exist, so this check can be delegated to the repository once the new instance path has been determined. Parameters: namespace (:term:`string`): The name of the CIM namespace in which the CIM instance is to be created, in any lexical case, and with leading and trailing slash characters removed. new_instance (:class:`~pywbem.CIMInstance`): A representation of the CIM instance to be created. This object is a deep copy of the original client parameter, and may be modified by the provider as needed, before storing it in the CIM repository. The property names in this object have been adjusted to match the lexical case of the property definitions in the creation class of the instance in the CIM repository. The `classname` attribute of this object will specify the creation class for the new instance, in any lexical case. The `properties` attribute of this object will specify the initial property values for the new CIM instance, with property names in any lexical case. Key properties may or may not be included. The `path` attribute of this object will be `None`. The `qualifiers` attribute of this object, if non-empty, should be ignored by the provider, because instance-level qualifiers have been deprecated in CIM. Returns: :class:`~pywbem.CIMInstanceName`: Instance path of the new CIM instance. Raises: :exc:`~pywbem.CIMError`: The provider may raise CIMError with any status code, and typically raises: - CIM_ERR_INVALID_PARAMETER - CIM_ERR_ALREADY_EXISTS """ # Get the creation class with all exposed properties and qualifiers. # Since the existence of the class has already been verified, this # will always succeed. class_store = self.cimrepository.get_class_store(namespace) creation_class = class_store.get(new_instance.classname, copy=False) # This default provider determines the instance path from the key # properties in the new instance. A user-defined provider may do that # as well, or invent key properties such as InstanceID. # Specifying strict=True in from_instance() verifies that all key # properties exposed by the class are specified in the new instance, # and raises ValueError if key properties are missing. try: new_instance.path = CIMInstanceName.from_instance( creation_class, new_instance, namespace=namespace, strict=True) except ValueError as exc: raise CIMError(CIM_ERR_INVALID_PARAMETER, str(exc)) # Get the instance store of the CIM repository. Since the existence of # the namespace has already been verified, this will always succeed. instance_store = self.cimrepository.get_instance_store(namespace) # Store the new instance in the CIM repository, verifying that it does # not exist yet. try: instance_store.create(new_instance.path, new_instance) except ValueError: raise CIMError( CIM_ERR_ALREADY_EXISTS, _format( "New instance {0!A} already exists in namespace " "{1!A}.", new_instance.path, namespace)) # CreateInstance returns the instance path of the new instance return new_instance.path
def test_wbemserver_basic(self, tst_namespace): # pylint: disable=no-self-use """ Test the basic functions that access server information. This test creates the CIM repository and adds classes and instances for the WBEMServer tests that involve namespaces, brand, profiles and a subset of the central_instance tests. It includes no tests for errors. The primary goal of this test was to develop the mechanisms for easily getting classes and instances into the repo and to provide a basic test of functionality. """ # Build the wbem server mock using the WbemServerMock default test # data except that we define the interop namespace mock_wbemserver = WbemServerMock(interop_ns=tst_namespace) server = mock_wbemserver.wbem_server # Build instances for get_central instance # using central methodology, i.e. ElementConformsToProfile # Test basic brand, version, namespace methods assert server.namespace_classname == 'CIM_Namespace' assert server.url == 'http://FakedUrl:5988' assert server.brand == "Mock_Test" # assert server.version == "2.15.0" assert server.interop_ns == tst_namespace assert set(server.namespaces) == set([tst_namespace]) # Test basic profiles methods org_vm = ValueMapping.for_property(server, server.interop_ns, 'CIM_RegisteredProfile', 'RegisteredOrganization') for inst in server.profiles: org = org_vm.tovalues(inst['RegisteredOrganization']) name = inst['RegisteredName'] vers = inst['RegisteredVersion'] tst_tup = (org, name, vers) pass_tst = False for tup in mock_wbemserver.registered_profiles: if tst_tup == tup: pass_tst = True break assert pass_tst sel_prof = server.get_selected_profiles(registered_org='DMTF', registered_name='Indications') assert len(sel_prof) == 1 for inst in sel_prof: assert org_vm.tovalues(inst['RegisteredOrganization']) == 'DMTF' assert inst['RegisteredName'] == 'Indications' # Test case insensitive matching sel_prof = server.get_selected_profiles(registered_org='DmtF', registered_name='inDiCations') assert len(sel_prof) == 1 for inst in sel_prof: assert org_vm.tovalues(inst['RegisteredOrganization']) == 'DMTF' assert inst['RegisteredName'] == 'Indications' sel_prof = server.get_selected_profiles(registered_org='DMTF') assert len(sel_prof) == 3 for inst in sel_prof: assert org_vm.tovalues(inst['RegisteredOrganization']) == 'DMTF' # Simple get_cental_instance. # profile_path, central_class=None, # scoping_class=None, scoping_path=None profile_insts = server.get_selected_profiles( registered_org='SNIA', registered_name='Server', registered_version='1.1.0') profile_path = profile_insts[0].path insts = server.get_central_instances(profile_path, 'CIM_ObjectManager') assert len(insts) == 1 kb = NocaseDict([ ('SystemCreationClassName', 'CIM_ComputerSystem'), ('SystemName', mock_wbemserver.system_name), ('CreationClassName', 'CIM_ObjectManager'), ('Name', 'FakeObjectManager'), ]) assert insts[0] == CIMInstanceName('CIM_ObjectManager', keybindings=kb, namespace=tst_namespace, host=server.conn.host)
# * exp_paths: Expected returned instance paths, as a list of # CIMInstanceName objects. # * exp_exc_types: Expected exception type(s), or None. # * exp_warn_types: Expected warning type(s), or None. # * condition: Boolean condition for testcase to run, or 'pdb' for debugger ("Valid central class", dict(profile_name=('SNIA', 'Server', '1.2.0'), central_class='XXX_StorageComputerSystem', scoping_class=None, scoping_path=None, direction='snia', exp_paths=[ CIMInstanceName('XXX_StorageComputerSystem', keybindings={ 'Name': "10.1.2.3", 'CreationClassName': 'XXX_StorageComputerSystem' }, host='FakedUrl', namespace='interop'), ]), None, None, True), ("Invalid reference direction", dict(profile_name=('SNIA', 'Server', '1.2.0'), central_class='XXX_StorageComputerSystem', scoping_class=None, scoping_path=None, direction='foo', exp_paths=None), ValueError, None, True), # TODO add more central instance tests ]
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
""" 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
def test_wbemserver_basic(self, tst_namespace): """ Test the basic functions that access server information. This test creates the mock repository and adds classes and instances for the WBEMServer tests that involve namespaces, brand, profiles and a subset of the central_instance tests. It includes no tests for errors. The primary goal of this test was to develop the mechanisms for easily getting classes and instances into the repo and to provide a basic test of functionality. """ system_name = 'Mock_Test_subscription_mgr' object_manager_name = 'MyFakeObjectManager' conn = self.build_class_repo(tst_namespace) server = WBEMServer(conn) # Build CIM_ObjectManager instance om_inst = self.build_obj_mgr_inst(conn, tst_namespace, system_name, object_manager_name) # build CIM_Namespace instances test_namespaces = [tst_namespace, 'root/cimv2'] self.build_cimnamespace_insts(conn, tst_namespace, system_name, object_manager_name, test_namespaces) # Build RegisteredProfile instances profiles = [('DMTF', 'Indications', '1.1.0'), ('DMTF', 'Profile Registration', '1.0.0'), ('SNIA', 'Server', '1.2.0'), ('SNIA', 'Server', '1.1.0'), ('SNIA', 'SMI-S', '1.2.0')] self.build_reg_profile_insts(conn, tst_namespace, profiles) # Build instances for get_central instance # Using central methodology, i.e. ElementConformsToProfile # Element conforms for SNIA server to object manager prof_inst = server.get_selected_profiles(registered_org='SNIA', registered_name='Server', registered_version='1.1.0') self.build_elementconformstoprofile_inst(conn, tst_namespace, prof_inst[0].path, om_inst.path) # Test basic brand, version, namespace methods assert server.namespace_classname == 'CIM_Namespace' assert server.url == 'http://FakedUrl' assert server.brand == "OpenPegasus" assert server.version == "2.15.0" assert server.interop_ns == tst_namespace assert set(server.namespaces) == set([tst_namespace, 'root/cimv2']) # Test basic profiles methods org_vm = ValueMapping.for_property(server, server.interop_ns, 'CIM_RegisteredProfile', 'RegisteredOrganization') for inst in server.profiles: org = org_vm.tovalues(inst['RegisteredOrganization']) name = inst['RegisteredName'] vers = inst['RegisteredVersion'] tst_tup = (org, name, vers) pass_tst = False for tup in profiles: if tst_tup == tup: pass_tst = True break assert pass_tst sel_prof = server.get_selected_profiles(registered_org='DMTF', registered_name='Indications') assert len(sel_prof) == 1 for inst in sel_prof: assert org_vm.tovalues(inst['RegisteredOrganization']) == 'DMTF' assert inst['RegisteredName'] == 'Indications' sel_prof = server.get_selected_profiles(registered_org='DMTF') assert len(sel_prof) == 2 for inst in sel_prof: assert org_vm.tovalues(inst['RegisteredOrganization']) == 'DMTF' # Simple get_cental_instance. # profile_path, central_class=None, # scoping_class=None, scoping_path=None profile_insts = server.get_selected_profiles( registered_org='SNIA', registered_name='Server', registered_version='1.1.0') profile_path = profile_insts[0].path insts = server.get_central_instances(profile_path, 'CIM_ObjectManager') print('central inst %s' % insts[0]) assert len(insts) == 1 kb = NocaseDict([('SystemCreationClassName', 'CIM_ComputerSystem'), ('SystemName', system_name), ('CreationClassName', 'CIM_ObjectManager')]) assert insts[0] == CIMInstanceName('CIM_ObjectManager', keybindings=kb, namespace=tst_namespace, host=conn.host)
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
def path_str_to_cim_path(path_str): """ Convert a string into CIMInstanceName. """ path_dict = json.loads(path_str) return CIMInstanceName(**path_dict)
def build_mock(self): """ Builds the classes and instances for a mock WBEMServer from data in the init parameter. This calls the builder for: the object manager the namespaces the profiles """ conn = self.build_class_repo(self.interop_ns) server = WBEMServer(conn) # NOTE: The wbemserver is not complete until the instances for at # least object manager and namespaces have been inserted. Any attempt # to display the instance object before that will fail because the # enumerate namespaces will be inconsistent # Build CIM_ObjectManager instance into the interop namespace since # this is required to build namespace instances om_inst = self.build_obj_mgr_inst( conn, self.system_name, self.object_manager_name, self.server_mock_data['object_manager']['ElementName'], self.server_mock_data['object_manager']['Description']) # build CIM_Namespace instances based on the init parameters namespaces = [self.interop_ns] if self.server_mock_data['other_namespaces']: namespaces.extend(self.server_mock_data['other_namespaces']) self.build_cimnamespace_insts(conn, namespaces) self.build_reg_profile_insts(conn, self.registered_profiles) self.build_referenced_profile_insts( server, self.server_mock_data['referenced_profiles']) self.build_central_instances( conn, self.server_mock_data['central-instances']) # Element conforms for SNIA server to object manager prof_inst = server.get_selected_profiles(registered_org='SNIA', registered_name='Server', registered_version='1.1.0') # TODO this is simplistic form and only builds one instance # conforms to. Should expand but need better way to define instance # at other end. self.build_elementconformstoprofile_inst(conn, prof_inst[0].path, om_inst.path) for item in self.server_mock_data['element_conforms_to_profile']: profile_name = item[0] # TODO we are fixing the host name here. Not good central_inst_path = CIMInstanceName(item[1][0], keybindings=item[1][1], host='FakedUrl', namespace=server.interop_ns) prof_insts = server.get_selected_profiles( registered_org=profile_name[0], registered_name=profile_name[1], registered_version=profile_name[2]) assert len(prof_insts) == 1 self.build_elementconformstoprofile_inst(conn, prof_insts[0].path, central_inst_path) return server
"Test invalid invokemethod inferred object integer None", dict( init_kwargs={}, method='invokemethod', args=[None, "ObjectName"], kwargs={"param1": 1}, ), TypeError, None, False # Fails with connection failure. ), ("Test enumerateinstances, fails, classname is not CIMClassname or Str", dict( init_kwargs={}, 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={},