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
def test_datetime_inheritance(): """Test inheritance""" obj = CIMDateTime('00000000000000.000000:000') assert isinstance(obj, CIMDateTime) assert isinstance(obj, CIMType) assert not isinstance(obj, CIMFloat) assert not isinstance(obj, CIMInt)
def test_datetime_init(datetime_init_tuple): """Test initialization from all input types using datetime_init_tuple pytest.fixture. """ # pylint: disable=redefined-outer-name (dtarg, exp_kind, exp_datetime, exp_timedelta, exp_precision, exp_minutesfromutc, exp_str) = datetime_init_tuple try: obj = CIMDateTime(dtarg) except Exception as exc: # pylint: disable=broad-except assert isinstance(exc, exp_kind) else: assert not hasattr(obj, '__dict__') assert obj.is_interval == (exp_kind == 'interval') assert obj.datetime == exp_datetime if obj.datetime is not None: assert isinstance(obj.datetime, datetime) # We ensure that the datetime is always timezone-aware: assert obj.datetime.tzinfo is not None assert obj.timedelta == exp_timedelta if obj.timedelta is not None: assert isinstance(obj.timedelta, timedelta) assert obj.precision == exp_precision assert obj.minutes_from_utc == exp_minutesfromutc assert str(obj) == exp_str
def paramvalue(obj): """Return a cim_xml node to be used as the value for a parameter.""" if isinstance(obj, (datetime, timedelta)): obj = CIMDateTime(obj) if isinstance(obj, (cim_types.CIMType, bool, StringTypes)): return cim_xml.VALUE(cim_types.atomic_to_cim_xml(obj)) if isinstance(obj, (CIMClassName, CIMInstanceName)): return cim_xml.VALUE_REFERENCE(obj.tocimxml()) if isinstance(obj, (CIMClass, CIMInstance)): return cim_xml.VALUE(obj.tocimxml().toxml()) if isinstance(obj, list): if isinstance(obj[0], (CIMClassName, CIMInstanceName)): return cim_xml.VALUE_REFARRAY([paramvalue(x) for x in obj]) return cim_xml.VALUE_ARRAY([paramvalue(x) for x in obj]) raise TypeError('Unsupported parameter type "%s"' % type(obj))
def ModifyInstance(self, modified_instance, IncludeQualifiers=None): # pylint: disable=invalid-name """ Modification of CIM_IndicationSubscription instance allowed only for selected properties. See the documentation in CommonMethodsMixin.validate_modify_instance for parameter documentation. """ # NOTE: The choice of modifiable properties is just to support tests # and may not reflect user needs since profile definition is # flexible modifiable_properties = [ 'SubscriptionInfo', 'SubscriptionState', 'SubscriptionDuration' ] # Validates the modify instance but does not change any properties. # If not valid, it generates exception self.validate_modify_instance( modified_instance, modifiable_properties=modifiable_properties, IncludeQualifiers=IncludeQualifiers) if modified_instance['SubscriptionDuration']: modified_instance['SubscriptionTimeRemaining'] = \ modified_instance['SubscriptionDuration'] if modified_instance['SubscriptionDuration']: modified_instance['SubscriptionTimeRemaining'] = \ modified_instance['SubscriptionDuration'] modified_instance['TimeOfLastStateChange'] = CIMDateTime.now() return super(CIMIndicationSubscriptionProvider, self).ModifyInstance(modified_instance, IncludeQualifiers=IncludeQualifiers)
def test_to_yaml_simple2(self): """Test Simple cimdatetime and other primitive types to toyaml""" test_yaml = self.test_recorder.toyaml( CIMDateTime('20140924193040.654321+120')) self.assertEqual(test_yaml, '20140924193040.654321+120') self.assertEqual(self.test_recorder.toyaml(True), True) self.assertEqual(self.test_recorder.toyaml(False), False) self.assertEqual(self.test_recorder.toyaml(1234), 1234) self.assertEqual(self.test_recorder.toyaml('blahblah '), 'blahblah ')
def test_invoke_method(self): """ Emulates call to invokemethod to test parameter processing. Currently creates the pywbem_request component. Each test emulated a single cim operation with fixed data to create the input for the yaml, create the yaml, and test the result """ obj_name = self.create_ciminstancename() params = [ ('StringParam', 'Spotty'), ('Uint8', Uint8(1)), ('Sint8', Sint8(2)), ('Uint16', Uint16(3)), ('Sint16', Sint16(3)), ('Uint32', Uint32(4)), ('Sint32', Sint32(5)), ('Uint64', Uint64(6)), ('Sint64', Sint64(7)), ('Real32', Real32(8)), ('Real64', Real64(9)), ('Bool', True), ('DTN', CIMDateTime.now()), # ('DTI', timedelta(60)), ('Ref', obj_name) ] self.test_recorder.stage_pywbem_args(method='InvokeMethod', MethodName='Blah', ObjectName=obj_name, Params=params) method_result_tuple = None method_exception = None self.test_recorder.stage_pywbem_result(method_result_tuple, method_exception) self.test_recorder.record_staged() # reload the yaml to test created values test_yaml = self.loadYamlFile() test_yaml = test_yaml[0] pywbem_request = test_yaml['pywbem_request'] self.assertEqual(pywbem_request['url'], 'http://acme.com:80') operation = pywbem_request['operation'] self.assertEqual(operation['pywbem_method'], 'InvokeMethod') self.assertEqual(operation['MethodName'], 'Blah') param_dict = dict(params) self.assertEqual(len(param_dict), 14) self.assertEqual(param_dict['StringParam'], 'Spotty') self.assertEqual(param_dict['Uint8'], 1) self.assertEqual(param_dict['Bool'], True) # test other parameters ref = param_dict['Ref'] self.assertEqual(ref, obj_name)
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])
def test_init(self, datetime_init_tuple): """Test initialization from all input types""" (dtarg, exp_kind, exp_datetime, exp_timedelta, exp_minutesfromutc, exp_str) = datetime_init_tuple try: obj = CIMDateTime(dtarg) except Exception as exc: assert isinstance(exc, exp_kind) else: assert obj.is_interval == (exp_kind == 'interval') assert obj.datetime == exp_datetime assert obj.timedelta == exp_timedelta assert obj.minutes_from_utc == exp_minutesfromutc assert str(obj) == exp_str
def test_datetime_str(datetime_init_tuple): """ Test str(CIMDateTime) from all input types using datetime_init_tuple pytest.fixture. """ # pylint: disable=redefined-outer-name (dtarg, exp_kind, _, _, _, _, _) = datetime_init_tuple if isinstance(exp_kind, type) and issubclass(exp_kind, Exception): pytest.skip("Testing str() needs CIMDatetime object") obj = CIMDateTime(dtarg) # The code to be tested. # The actual test is that no exception is raised. str(obj)
def random_type_value(values, type=None): # pylint: disable=redefined-builtin """ Return a random valid tuple of CIM type name and value according to a value profile. Parameters: values (ValueProfile or value): Values type (string): Use this type instead of a random type from the profile """ if not isinstance(values, ValueProfile): if type is None: raise ValueError("Specifying a value directly requires specifying " "a type") return type, values if type is None: type = random.choice(values.types) if type == 'string': value = random_string(values.string_len) elif type == 'char16': value = random_string(Range(1, 1)) elif type in INTEGER_TYPES: # TODO: Consider value range of type value = random.randint(0, 127) elif type in REAL_TYPES: # TODO: Consider value range of type value = float(random.randint(-1000, 1000)) elif type in 'boolean': value = random.choice((True, False)) elif type in 'datetime': year = random.randint(1, 3000) month = random.randint(1, 12) day = random.randint(1, 31) hour = random.randint(0, 23) minute = random.randint(0, 59) second = random.randint(0, 59) value = CIMDateTime(datetime(year, month, day, hour, minute, second)) else: # The 'reference' type is intentionally not supported here raise AssertionError('Invalid CIM type name: {}'.format(type)) return type, value
def test_datetime_init(datetime_init_tuple): """Test initialization from all input types""" (dtarg, exp_kind, exp_datetime, exp_timedelta, exp_minutesfromutc, exp_str) = datetime_init_tuple try: obj = CIMDateTime(dtarg) except Exception as exc: assert isinstance(exc, exp_kind) else: assert obj.is_interval == (exp_kind == 'interval') assert obj.datetime == exp_datetime if obj.datetime is not None: assert isinstance(obj.datetime, datetime) # We ensure that the datetime is always timezone-aware: assert obj.datetime.tzinfo is not None assert obj.timedelta == exp_timedelta if obj.timedelta is not None: assert isinstance(obj.timedelta, timedelta) assert obj.minutes_from_utc == exp_minutesfromutc assert str(obj) == exp_str
hours=22, minutes=44, seconds=55, microseconds=654321), 'interval', None, timedelta(days=12345678, hours=22, minutes=44, seconds=55, microseconds=654321), 0, '12345678224455.654321:000'), ('12345678224455.654321:000', 'interval', None, timedelta(days=12345678, hours=22, minutes=44, seconds=55, microseconds=654321), 0, '12345678224455.654321:000'), (CIMDateTime('12345678224455.654321:000'), 'interval', None, timedelta(days=12345678, hours=22, minutes=44, seconds=55, microseconds=654321), 0, '12345678224455.654321:000'), ('12345678224455.654321:777', ValueError, None, None, None, None), ('12345678224455,654321:000', ValueError, None, None, None, None), (datetime(year=2014, month=9, day=24, hour=19, minute=30, second=40, microsecond=654321, tzinfo=MinutesFromUTC(120)), 'timestamp',
timedelta(days=12345678, hours=22, minutes=44, seconds=55, microseconds=654321), 0, '12345678224455.654321:000' ), ( '12345678224455.654321:000', 'interval', None, timedelta(days=12345678, hours=22, minutes=44, seconds=55, microseconds=654321), 0, '12345678224455.654321:000' ), ( CIMDateTime('12345678224455.654321:000'), 'interval', None, timedelta(days=12345678, hours=22, minutes=44, seconds=55, microseconds=654321), 0, '12345678224455.654321:000' ), ( '12345678224455.654321:777', ValueError, None, None, None, None ), ( '12345678224455,654321:000', ValueError, None, None, None, None ),
def test_datetime_class_attrs_inst(): """Test class attrs via instance level""" obj = CIMDateTime('00000000000000.000000:000') assert obj.cimtype == 'datetime'
hours=22, minutes=44, seconds=55, microseconds=654321), 'interval', None, timedelta(days=12345678, hours=22, minutes=44, seconds=55, microseconds=654321), None, 0, '12345678224455.654321:000'), ('12345678224455.654321:000', 'interval', None, timedelta(days=12345678, hours=22, minutes=44, seconds=55, microseconds=654321), None, 0, '12345678224455.654321:000'), (CIMDateTime('12345678224455.654321:000'), 'interval', None, timedelta(days=12345678, hours=22, minutes=44, seconds=55, microseconds=654321), None, 0, '12345678224455.654321:000'), ('12345678224455.65432*:000', 'interval', None, timedelta(days=12345678, hours=22, minutes=44, seconds=55, microseconds=654320), 20, 0, '12345678224455.65432*:000'), ('12345678224455.6543**:000', 'interval', None, timedelta(days=12345678, hours=22, minutes=44,
def test_all(self): # Invoke on classname try: self.cimcall( self.conn.InvokeMethod, 'FooMethod', TEST_CLASS) except CIMError as ce: if ce.args[0] != CIM_ERR_METHOD_NOT_AVAILABLE: raise # Invoke on an InstanceName inst_names = self.cimcall(self.conn.EnumerateInstanceNames, TEST_CLASS) self.assertTrue(len(inst_names) >= 1) name = inst_names[0] # Pick the first returned instance try: self.cimcall(self.conn.InvokeMethod, 'FooMethod', name) except CIMError as ce: if ce.args[0] not in (CIM_ERR_METHOD_NOT_AVAILABLE, CIM_ERR_METHOD_NOT_FOUND): raise # Test remote instance name name2 = name.copy() name2.host = 'woot.com' name2.namespace = 'root/cimv2' try: self.cimcall(self.conn.InvokeMethod, 'FooMethod', name) except CIMError as ce: if ce.args[0] not in (CIM_ERR_METHOD_NOT_AVAILABLE, CIM_ERR_METHOD_NOT_FOUND): raise # Call with all possible parameter types try: self.cimcall(self.conn.InvokeMethod, 'FooMethod', TEST_CLASS, String='Spotty', Uint8=Uint8(1), Sint8=Sint8(2), Uint16=Uint16(3), Sint16=Sint16(3), Uint32=Uint32(4), Sint32=Sint32(5), Uint64=Uint64(6), Sint64=Sint64(7), Real32=Real32(8), Real64=Real64(9), Bool=True, Date1=CIMDateTime.now(), Date2=timedelta(60), Ref=name) except CIMError as ce: if ce.args[0] != CIM_ERR_METHOD_NOT_AVAILABLE: raise # Call with non-empty arrays try: self.cimcall(self.conn.InvokeMethod, 'FooMethod', TEST_CLASS, StringArray='Spotty', Uint8Array=[Uint8(1)], Sint8Array=[Sint8(2)], Uint16Array=[Uint16(3)], Sint16Array=[Sint16(3)], Uint32Array=[Uint32(4)], Sint32Array=[Sint32(5)], Uint64Array=[Uint64(6)], Sint64Array=[Sint64(7)], Real32Array=[Real32(8)], Real64Array=[Real64(9)], BoolArray=[False, True], Date1Array=[CIMDateTime.now(), CIMDateTime.now()], Date2Array=[timedelta(0), timedelta(60)], RefArray=[name, name]) except CIMError as ce: if ce.args[0] != CIM_ERR_METHOD_NOT_AVAILABLE: raise # Call with new Params arg try: self.cimcall(self.conn.InvokeMethod, 'FooMethod', TEST_CLASS, [('Spam', Uint16(1)), ('Ham', Uint16(2))], # Params Drink=Uint16(3), # begin of **params Beer=Uint16(4)) except CIMError as ce: if ce.args[0] != CIM_ERR_METHOD_NOT_AVAILABLE: raise
def test_all(self): # Invoke on classname try: self.cimcall(self.conn.InvokeMethod, 'FooMethod', TEST_CLASS) except CIMError as ce: if ce.args[0] != CIM_ERR_METHOD_NOT_AVAILABLE: raise # Invoke on an InstanceName inst_names = self.cimcall(self.conn.EnumerateInstanceNames, TEST_CLASS) self.assertTrue(len(inst_names) >= 1) name = inst_names[0] # Pick the first returned instance try: self.cimcall(self.conn.InvokeMethod, 'FooMethod', name) except CIMError as ce: if ce.args[0] not in (CIM_ERR_METHOD_NOT_AVAILABLE, CIM_ERR_METHOD_NOT_FOUND): raise # Test remote instance name name2 = name.copy() name2.host = 'woot.com' name2.namespace = 'root/cimv2' try: self.cimcall(self.conn.InvokeMethod, 'FooMethod', name) except CIMError as ce: if ce.args[0] not in (CIM_ERR_METHOD_NOT_AVAILABLE, CIM_ERR_METHOD_NOT_FOUND): raise # Call with all possible parameter types try: self.cimcall(self.conn.InvokeMethod, 'FooMethod', TEST_CLASS, String='Spotty', Uint8=Uint8(1), Sint8=Sint8(2), Uint16=Uint16(3), Sint16=Sint16(3), Uint32=Uint32(4), Sint32=Sint32(5), Uint64=Uint64(6), Sint64=Sint64(7), Real32=Real32(8), Real64=Real64(9), Bool=True, Date1=CIMDateTime.now(), Date2=timedelta(60), Ref=name) except CIMError as ce: if ce.args[0] != CIM_ERR_METHOD_NOT_AVAILABLE: raise # Call with non-empty arrays try: self.cimcall(self.conn.InvokeMethod, 'FooMethod', TEST_CLASS, StringArray='Spotty', Uint8Array=[Uint8(1)], Sint8Array=[Sint8(2)], Uint16Array=[Uint16(3)], Sint16Array=[Sint16(3)], Uint32Array=[Uint32(4)], Sint32Array=[Sint32(5)], Uint64Array=[Uint64(6)], Sint64Array=[Sint64(7)], Real32Array=[Real32(8)], Real64Array=[Real64(9)], BoolArray=[False, True], Date1Array=[CIMDateTime.now(), CIMDateTime.now()], Date2Array=[timedelta(0), timedelta(60)], RefArray=[name, name]) except CIMError as ce: if ce.args[0] != CIM_ERR_METHOD_NOT_AVAILABLE: raise # Call with new Params arg try: self.cimcall( self.conn.InvokeMethod, 'FooMethod', TEST_CLASS, [('Spam', Uint16(1)), ('Ham', Uint16(2))], # Params Drink=Uint16(3), # begin of **params Beer=Uint16(4)) except CIMError as ce: if ce.args[0] != CIM_ERR_METHOD_NOT_AVAILABLE: raise
def CreateInstance(self, namespace, new_instance): # pylint: disable=invalid-name """ Create an instance of the CIM_IndicationFilter class in an Interop namespace of the CIM repository, and if not yet existing create the new namespace in the CIM repository. See `~pywbem_mock.InstanceWriteProvider.CreateInstance` for documentation of validation and description of input parameters, noting extra conditions for this provider as described below: Parameters: namespace (:term:`string`): Must be a valid Interop namespace. new_instance (:class:`~pywbem.CIMInstance`): The following applies regarding its properties: * The 'Filter' and 'Handler' reference properties must exist. * If 'SubscriptionDuration' exists, 'SubscriptionTimeRemaining' will be set. * 'CreationClassName' property: This property is required and its value must match the class name of the new instance. Raises: :exc:`~pywbem.CIMError`: (CIM_ERR_INVALID_PARAMETER) if namespace is not the Interop namespace in the CIM repository or the Name property does not exist or the other properties cannot be added to the instance. """ self.parameter_is_interop(namespace, new_instance.classname) required_properties = ["Filter", "Handler"] self.validate_required_properties_exist(new_instance, namespace, required_properties) # Add missing properties that the might come from CIM_IndicationService new_instance['SubscriptionStartTime'] = CIMDateTime.now() new_instance['TimeOfLastStateChange'] = CIMDateTime.now() # Conditionally add the following properties set_property(new_instance, 'OnFatalErrorPolicy', Uint16(2)) set_property(new_instance, 'RepeatNotificationPolicy', Uint16(2)) set_property(new_instance, 'SubscriptionState', Uint16(2)) if 'SubscriptionDuration' in new_instance: new_instance['SubscriptionTimeRemaining'] = \ new_instance['SubscriptionDuration'] else: new_instance['SubscriptionDuration'] = CIMProperty( 'SubscriptionDuration', None, type='uint64') set_property(new_instance, 'SubscriptionInfo', CIMProperty('SubscriptionInfo', None, type='string')) set_property(new_instance, 'Description', "Pywbem mock CIMIndicationSubscriptionProvider instance") # Create the CIM instance for the new namespace in the CIM repository, # by delegating to the default provider method. return super(CIMIndicationSubscriptionProvider, self).CreateInstance(namespace, new_instance)