def test_AudioPassThruCapabilities(self): members = OrderedDict() members['range'] = Param(name='range', param_type=Float(max_value=10000.0, min_value=0.0)) members['samplingRate'] = Param(name='samplingRate', param_type=Enum(name='SamplingRate')) item = Struct(name='AudioPassThruCapabilities', members=members) expected = { 'class_name': 'AudioPassThruCapabilities', 'extends_class': 'RPCStruct', 'package_name': 'com.smartdevicelink.proxy.rpc', 'imports': ['androidx.annotation.NonNull', '', 'com.smartdevicelink.proxy.RPCStruct', 'com.smartdevicelink.proxy.rpc.enums.SamplingRate', 'com.smartdevicelink.util.SdlDataTypeConverter', '', 'java.util.Hashtable'], 'deprecated': None, 'since': None, 'history': None, 'params': (self.producer.params(deprecated=None, key='KEY_RANGE', last='range', mandatory=True, origin='range', return_type='Float', since=None, title='Range', description=None, param_doc=None, name=None), self.producer.params(deprecated=None, key='KEY_SAMPLING_RATE', last='samplingRate', mandatory=True, origin='samplingRate', return_type='SamplingRate', name=None, since=None, title='SamplingRate', description=None, param_doc=None)), } actual = self.producer.transform(item) self.comparison(expected, actual)
def test_PutFileRequest(self): params = OrderedDict() params['fileType'] = Param( name='fileType', param_type=Enum( name='FileType', description=['Enumeration listing'], elements={'AUDIO_MP3': EnumElement(name='AUDIO_MP3')}), description=['Selected file type.']) params['syncFileName'] = Param(name='syncFileName', param_type=String(max_length=255, min_length=1)) item = Function(name='PutFile', function_id=None, description=['\n Used to'], message_type=EnumElement(name='request'), params=params) expected = self.expected_template.copy() expected['kind'] = 'request' expected['function_id'] = 'PUT_FILE' expected['class_name'] = 'PutFile' expected['extends_class'] = 'RPCRequest' expected['history'] = None expected['imports'] = [ 'androidx.annotation.NonNull', '', 'com.smartdevicelink.protocol.enums.FunctionID', 'com.smartdevicelink.proxy.RPCRequest', 'com.smartdevicelink.proxy.rpc.enums.FileType', '', 'java.util.Hashtable' ] expected['description'] = ['Used to'] expected['params'] = (self.producer.params( deprecated=None, description=['Selected file type.'], key='KEY_FILE_TYPE', last='fileType', mandatory=True, origin='fileType', SuppressWarnings=None, return_type='FileType', since=None, title='FileType', param_doc=None, name=None), self.producer.params(deprecated=None, key='KEY_SDL_FILE_NAME', last='sdlFileName', mandatory=True, origin='syncFileName', return_type='String', description=None, since=None, title='SdlFileName', SuppressWarnings=None, param_doc=None, name=None)) actual = self.producer.transform(item) self.comparison(expected, actual)
def test_RegisterAppInterface(self): params = OrderedDict() params['syncMsgVersion'] = Param( name='syncMsgVersion', param_type=Struct(name='SyncMsgVersion')) params['ttsName'] = Param( name='ttsName', param_type=Array(element_type=Struct(name='TTSChunk'))) item = Function(name='RegisterAppInterface', function_id=None, message_type=EnumElement(name='request'), params=params) expected = self.expected_template.copy() expected['kind'] = 'request' expected['function_id'] = 'REGISTER_APP_INTERFACE' expected['class_name'] = 'RegisterAppInterface' expected['extends_class'] = 'RPCRequest' expected['history'] = None expected['imports'] = [ 'androidx.annotation.NonNull', '', 'com.smartdevicelink.protocol.enums.FunctionID', 'com.smartdevicelink.proxy.RPCRequest', '', 'java.util.Hashtable', 'java.util.List' ] expected['params'] = (self.producer.params(deprecated=None, key='KEY_SDL_MSG_VERSION', last='sdlMsgVersion', mandatory=True, SuppressWarnings=None, origin='syncMsgVersion', return_type='SdlMsgVersion', since=None, title='SdlMsgVersion', description=None, param_doc=None, name=None), self.producer.params( SuppressWarnings='unchecked', deprecated=None, key='KEY_TTS_NAME', last='ttsName', mandatory=True, origin='ttsName', description=None, return_type='List<TTSChunk>', since=None, title='TtsName', param_doc=None, name=None)) actual = self.producer.transform(item) self.comparison(expected, actual)
def test_process_function_name(self): """ generator/transformers/common_producer.py 29% generator/transformers/functions_producer.py 61% """ functions = { 'RegisterAppInterface': Function(name='RegisterAppInterface', function_id=EnumElement(name='RegisterAppInterfaceID'), since='3.0.0', message_type=EnumElement(name='request'), description=['RegisterAppInterface description'], params={ 'syncMsgVersion': Param(name='syncMsgVersion', param_type=Float(), since='3.5.0', description=['syncMsgVersion description'])}), 'OnHMIStatus': Function(name='OnHMIStatus', function_id=EnumElement(name='OnHMIStatusID'), since='4.0.0', message_type=EnumElement(name='notification'), description=['OnHMIStatus description'], params={ 'acEnable': Param(name='acEnable', param_type=Integer(), since='4.5.0', description=['acEnable description'])})} structs = { 'SoftButton': Struct(name='SoftButton', members={ 'image': Param(name='image', param_type=String(), since='1.0.0', description=['image description']), 'dayColorScheme': Param(name='dayColorScheme', param_type=Struct(name='TemplateColorScheme', description=[ '\nA color scheme for all display layout templates.\n']))}), 'PresetBankCapabilities': Struct(name='PresetBankCapabilities', members={ 'availableHdChannelsAvailable': Param(name='availableHdChannelsAvailable', param_type=Boolean(), since='2.0.0', description=['availableHDChannelsAvailable description'])})} expected = [ self.producer.common_names( description=['OnHMIStatus description'], name='OnHMIStatus', origin='OnHMIStatus', since='4.0.0'), self.producer.common_names( description=['RegisterAppInterface description'], name='RegisterAppInterface', origin='RegisterAppInterface', since='3.0.0')] actual = self.producer.get_function_names(functions) self.assertListEqual(expected, actual['params']) expected = [ self.producer.common_names(description=['acEnable description'], name='AcEnable', origin='acEnable', since='4.5.0'), self.producer.common_names(description=['availableHDChannelsAvailable description'], since='2.0.0', name='AvailableHdChannelsAvailable', origin='availableHdChannelsAvailable'), self.producer.common_names(description=[], name='DayColorScheme', origin='dayColorScheme', since=None), self.producer.common_names(description=['image description'], name='Image', origin='image', since='1.0.0'), self.producer.common_names(description=['syncMsgVersion description'], name='SdlMsgVersion', origin='syncMsgVersion', since='3.5.0')] actual = self.producer.get_simple_params(functions, structs) self.assertCountEqual(expected, actual['params'])
def test_Alert(self): item = Function(name='Alert', function_id=None, message_type=EnumElement(name='request'), params={ 'alertText2': Param(name='alertText2', param_type=String(max_length=500)) }) expected = self.expected_template.copy() expected['kind'] = 'request' expected['function_id'] = 'ALERT' expected['class_name'] = 'Alert' expected['extends_class'] = 'RPCRequest' expected['imports'] = [ 'android.support.annotation.NonNull', '', 'com.smartdevicelink.protocol.enums.FunctionID', 'com.smartdevicelink.proxy.RPCRequest', '', 'java.util.Hashtable' ] expected['params'] = (self.producer.params(deprecated=None, key='KEY_ALERT_TEXT_2', last='alertText2', mandatory=True, origin='alertText2', param_doc=None, return_type='String', since=None, title='AlertText2', description=None, SuppressWarnings=None, name=None), ) actual = self.producer.transform(item) self.comparison(expected, actual)
def extract_param(self, param: Param, item_name: str): """ Preparing self.param_named with prepared params :param param: Param from initial Model :return: self.param_named with prepared params """ param.name = self.replace_keywords(param.name) data = { 'constructor_argument_override': None, 'description': self.extract_description(param.description), 'since': param.since, 'mandatory': param.is_mandatory, 'deprecated': json.loads(param.deprecated.lower()) if param.deprecated else False, 'modifier': 'strong', 'history': param.history } if isinstance(param.param_type, (Integer, Float, String, Array)): data['description'].append( self.create_param_descriptor(param.param_type, OrderedDict())) data.update(self.extract_type(param)) data.update(self.param_origin_change(param.name)) return self.param_named(**data)
def test_ReleaseInteriorVehicleDataModule(self): item = Function(name='ReleaseInteriorVehicleDataModule', function_id=None, message_type=EnumElement(name='request'), params={ 'moduleType': Param(name='moduleType', param_type=Enum(name='ModuleType')) }) expected = self.expected_template.copy() expected['kind'] = 'request' expected['function_id'] = 'RELEASE_INTERIOR_VEHICLE_DATA_MODULE' expected['class_name'] = 'ReleaseInteriorVehicleDataModule' expected['extends_class'] = 'RPCRequest' expected['imports'] = [ 'android.support.annotation.NonNull', '', 'com.smartdevicelink.protocol.enums.FunctionID', 'com.smartdevicelink.proxy.RPCRequest', '', 'java.util.Hashtable' ] expected['params'] = (self.producer.params(deprecated=None, key='KEY_MODULE_TYPE', last='moduleType', mandatory=True, origin='moduleType', return_type='ModuleType', since=None, title='ModuleType', description=None, SuppressWarnings=None, param_doc=None, name=None), ) actual = self.producer.transform(item) self.comparison(expected, actual)
def test_DeleteCommand(self): item = Function(name='DeleteCommand', function_id=None, message_type=EnumElement(name='request'), params={ 'cmdID': Param(name='cmdID', param_type=Integer(max_value=2000000000, min_value=0)) }) expected = self.expected_template.copy() expected['kind'] = 'request' expected['function_id'] = 'DELETE_COMMAND' expected['class_name'] = 'DeleteCommand' expected['extends_class'] = 'RPCRequest' expected['imports'] = [ 'android.support.annotation.NonNull', '', 'com.smartdevicelink.protocol.enums.FunctionID', 'com.smartdevicelink.proxy.RPCRequest', '', 'java.util.Hashtable' ] expected['params'] = (self.producer.params(deprecated=None, key='KEY_CMD_ID', last='cmdID', mandatory=True, origin='cmdID', return_type='Integer', since=None, title='CmdID', description=None, SuppressWarnings=None, param_doc=None, name=None), ) actual = self.producer.transform(item) self.comparison(expected, actual)
def test_SoftButton(self): members = OrderedDict() members['image'] = Param(name='image', param_type=Struct(name='Image'), description=['Optional image']) members['value'] = Param(name='value', param_type=String()) item = Struct(name='SoftButton', members=members) expected = OrderedDict() expected['file_name'] = 'SoftButton' expected['name'] = 'SoftButton' expected['file_name'] = 'SoftButton' expected['imports'] = { self.producer.imports(what='Image', wherefrom='./Image.js'), self.producer.imports(what='RpcStruct', wherefrom='../RpcStruct.js') } expected['methods'] = (self.producer.methods( description=['Optional image'], external='Image', key='KEY_IMAGE', method_title='Image', param_name='image', type='Image', param_values={}, deprecated=None, history=None, since=None), self.producer.methods(description=[], external=None, key='KEY_VALUE', method_title='ValueParam', param_name='value', type='String', param_values={}, deprecated=None, history=None, since=None)) expected['params'] = (self.producer.params(key='KEY_IMAGE', value="'image'"), self.producer.params(key='KEY_VALUE', value="'value'")) expected['since'] = None expected['history'] = None expected['deprecated'] = None expected['extend'] = 'RpcStruct' result = self.producer.transform(item) self.assertDictEqual(expected, result)
def test_CreateInteractionChoiceSet(self): """ generator/transformers/common_producer.py 67% generator/transformers/functions_producer.py 63% """ params = OrderedDict() params['choiceSet'] = Param( name='choiceSet', param_type=Array(element_type=Struct(name='Choice'))) item = Function( name='CreateInteractionChoiceSet', function_id=EnumElement(name='CreateInteractionChoiceSetID'), message_type=EnumElement(name='request'), params=params) expected = OrderedDict() expected['origin'] = 'CreateInteractionChoiceSet' expected['name'] = 'SDLCreateInteractionChoiceSet' expected['extends_class'] = 'SDLRPCRequest' expected['imports'] = { '.m': {'SDLChoice'}, '.h': { 'struct': {'SDLChoice'}, 'enum': {'SDLRPCRequest'} } } expected['params'] = (self.producer.param_named( constructor_argument='choiceSet', constructor_argument_override=None, constructor_prefix='ChoiceSet', deprecated=False, description=[], for_name='objects', mandatory=True, method_suffix='ChoiceSet', modifier='strong', of_class='SDLChoice.class', origin='choiceSet', since=None, type_native='NSArray<SDLChoice *> *', type_sdl='NSArray<SDLChoice *> *'), ) argument = [ self.producer.argument_named(variable='choiceSet', deprecated=False, constructor_argument='choiceSet', origin='choiceSet') ] expected['constructors'] = (self.producer.constructor_named( all=argument, arguments=argument, deprecated=False, self=True, init='ChoiceSet:(NSArray<SDLChoice *> *)choiceSet'), ) actual = self.producer.transform(item) self.assertDictEqual(expected, actual)
def test_TouchEvent(self): """ generator/transformers/common_producer.py 69% generator/transformers/structs_producer.py 100% """ item = Struct(name='TouchEvent', members={ 'id': Param(name='id', param_type=Integer(max_value=9, min_value=0)) }) expected = OrderedDict() expected['origin'] = 'TouchEvent' expected['name'] = 'SDLTouchEvent' expected['extends_class'] = 'SDLRPCStruct' expected['imports'] = { '.h': { 'enum': ['SDLRPCStruct'], 'struct': [] }, '.m': [ 'NSMutableDictionary+Store', 'SDLRPCParameterNames', 'SDLTouchEvent' ] } expected['history'] = None expected['params'] = (self.producer.param_named( history=None, constructor_argument='idParam', constructor_argument_override=None, constructor_prefix='IdParam', deprecated=False, description=['{"num_min_value": 0, "num_max_value": 9}'], for_name='object', mandatory=True, method_suffix='IdParam', modifier='strong', of_class='NSNumber.class', origin='idParam', since=None, type_native='UInt8', type_sdl='NSNumber<SDLUInt> *'), ) argument = [ self.producer.argument_named(variable='idParam', deprecated=False, constructor_argument='@(idParam)', origin='idParam') ] expected['constructors'] = (self.producer.constructor_named( all=argument, arguments=argument, self='', init='IdParam:(UInt8)idParam'), ) actual = self.producer.transform(item) self.assertDictEqual(expected, actual)
def _parse_function_param(self, element, prefix): """Parse element as function parameter. :param element: an instance of Element (from ElementTree) :param prefix: empty string :return: an instance of model.Param """ params, subelements, attrib = self._parse_param_base_item( element, prefix) default_value = None default_value_string = self._extract_attrib(attrib, "defvalue") if default_value_string is not None: param_type = params["param_type"] if isinstance(param_type, Boolean): default_value = self._get_bool_from_string( default_value_string) elif isinstance(param_type, Integer): try: default_value = int(default_value_string) except: raise ParseError("Invalid value for integer: '{}'".format( default_value_string)) elif isinstance(param_type, Float): try: default_value = float(default_value_string) except: raise ParseError("Invalid value for float: '{}'".format( default_value_string)) elif isinstance(param_type, String): default_value = default_value_string elif isinstance(param_type, (Enum, EnumSubset)): if isinstance(param_type, EnumSubset): allowed_elements = param_type.allowed_elements else: allowed_elements = param_type.elements if default_value_string not in allowed_elements: raise ParseError( "Default value '{}' for parameter '{}' is not a member of {}" .format(default_value_string, params["name"], type(param_type.__name__))) default_value = allowed_elements[default_value_string] else: raise ParseError("Default value specified for " + type(param_type).__name__) params["default_value"] = default_value if len(attrib) != 0: raise ParseError("Unexpected attributes in parameter '{}'".format( params["name"])) if len(subelements) != 0: raise ParseError("Unexpected subelements in parameter '{}'".format( params["name"])) return Param(**params)
def test_OnHMIStatus(self): """ generator/transformers/common_producer.py 66% generator/transformers/functions_producer.py 65% """ item = Function(name='OnHMIStatus', function_id=EnumElement(name='OnHMIStatusID'), message_type=EnumElement(name='notification'), params={ 'hmiLevel': Param(name='hmiLevel', param_type=Enum(name='HMILevel')) }) expected = OrderedDict() expected['origin'] = 'OnHMIStatus' expected['name'] = 'SDLOnHMIStatus' expected['extends_class'] = 'SDLRPCNotification' expected['imports'] = { ".h": { 'enum': {'SDLRPCNotification'}, 'struct': set() }, ".m": set() } expected['params'] = (self.producer.param_named( constructor_argument='hmiLevel', constructor_argument_override=None, constructor_prefix='HmiLevel', deprecated=False, description=[], for_name='enum', mandatory=True, method_suffix='HmiLevel', modifier='strong', of_class='', origin='hmiLevel', since=None, type_native='SDLHMILevel ', type_sdl='SDLHMILevel '), ) arguments = [ self.producer.argument_named(variable='hmiLevel', deprecated=False, origin='hmiLevel', constructor_argument='hmiLevel') ] expected['constructors'] = (self.producer.constructor_named( all=arguments, arguments=arguments, deprecated=False, self=True, init='HmiLevel:(SDLHMILevel)hmiLevel'), ) actual = self.producer.transform(item) self.assertDictEqual(expected, actual)
def test_SetDisplayLayout(self): """ generator/transformers/common_producer.py 66% generator/transformers/functions_producer.py 63% """ params = OrderedDict() params['displayLayout'] = Param(name='displayLayout', param_type=String(max_length=500, min_length=1)) item = Function(name='SetDisplayLayout', function_id=EnumElement(name='SetDisplayLayoutID'), message_type=EnumElement(name='request'), params=params, history=[ Function(name='SetDisplayLayout', function_id=EnumElement(name='SetDisplayLayoutID'), message_type=EnumElement(name='request'), params={}, history=None, since='3.0.0', until='6.0.0') ], since='6.0.0', until=None, deprecated='true') expected = OrderedDict() expected['origin'] = 'SetDisplayLayout' expected['name'] = 'SDLSetDisplayLayout' expected['extends_class'] = 'SDLRPCRequest' expected['imports'] = { '.h': { 'enum': ['SDLRPCRequest'], 'struct': []}, '.m': [ 'NSMutableDictionary+Store', 'SDLRPCFunctionNames', 'SDLRPCParameterNames', 'SDLSetDisplayLayout' ] } expected['history'] = '3.0.0' expected['since'] = '6.0.0' expected['deprecated'] = True expected['params'] = ( self.producer.param_named( history=None, constructor_argument='displayLayout', constructor_argument_override=None, constructor_prefix='DisplayLayout', deprecated=False, description=['{"string_min_length": 1, "string_max_length": 500}'], for_name='object', mandatory=True, method_suffix='DisplayLayout', modifier='strong', of_class='NSString.class', origin='displayLayout', since=None, type_native='NSString *', type_sdl='NSString *'),) argument = [ self.producer.argument_named(variable='displayLayout', deprecated=False, constructor_argument='displayLayout', origin='displayLayout')] expected['constructors'] = (self.producer.constructor_named( all=argument, arguments=argument, self=True, init='DisplayLayout:(NSString *)displayLayout'),) actual = self.producer.transform(item) self.assertDictEqual(expected, actual)
def test_RegisterAppInterfaceResponse(self): params = OrderedDict() params['language'] = Param(name='language', param_type=Enum(name='Language')) params['success'] = Param(name='success', param_type=Boolean()) item = Function(name='RegisterAppInterface', function_id=None, message_type=EnumElement(name='response'), params=params) expected = self.expected_template.copy() expected['kind'] = 'response' expected['function_id'] = 'REGISTER_APP_INTERFACE' expected['class_name'] = 'RegisterAppInterfaceResponse' expected['extends_class'] = 'RPCResponse' expected['history'] = None expected['imports'] = [ 'androidx.annotation.NonNull', '', 'com.smartdevicelink.protocol.enums.FunctionID', 'com.smartdevicelink.proxy.RPCResponse', 'com.smartdevicelink.proxy.rpc.enums.Language', 'com.smartdevicelink.proxy.rpc.enums.Result', '', 'java.util.Hashtable' ] expected['params'] = (self.producer.params(deprecated=None, key='KEY_LANGUAGE', last='language', mandatory=True, origin='language', return_type='Language', since=None, title='Language', description=None, SuppressWarnings=None, param_doc=None, name=None), ) actual = self.producer.transform(item) self.comparison(expected, actual)
def test_PutFileRequest(self): params = OrderedDict() params['fileType'] = Param( name='fileType', param_type=Enum( name='FileType', description=['Enumeration listing'], elements={'AUDIO_MP3': EnumElement(name='AUDIO_MP3')}), description=['Selected file type.']) item = Function(name='PutFile', function_id=Enum(name='PutFileID'), description=['\n Used to'], message_type=EnumElement(name='request'), params=params) expected = OrderedDict() expected['file_name'] = 'PutFile' expected['name'] = 'PutFile' expected['imports'] = { self.producer.imports(what='FileType', wherefrom='../enums/FileType.js'), self.producer.imports(what='RpcRequest', wherefrom='../RpcRequest.js'), self.producer.imports(what='FunctionID', wherefrom='../enums/FunctionID.js') } expected['methods'] = (self.producer.methods( key='KEY_FILE_TYPE', method_title='FileType', external='FileType', description=['Selected file type.'], param_name='type', type='FileType', param_values={}, since=None, history=None, deprecated=None), ) expected['params'] = (self.producer.params(key='KEY_FILE_TYPE', value="'fileType'"), ) expected['description'] = ['Used to'] expected['since'] = None expected['history'] = None expected['deprecated'] = None expected['script'] = self.producer.get_file_content( 'templates/scripts/PutFileRequest.js') expected['func'] = 'PutFile' expected['extend'] = 'RpcRequest' result = self.producer.transform(item) self.assertDictEqual(expected, result)
def test_CreateInteractionChoiceSetRequest(self): params = OrderedDict() params['choiceSet'] = Param( name='choiceSet', param_type=Array(element_type=Struct( name='Choice', description=['A choice is an option given to ' ]))) item = Function(name='CreateInteractionChoiceSet', function_id=Enum(name='CreateInteractionChoiceSetID'), description=['creates interaction'], message_type=EnumElement(name='request'), params=params) expected = OrderedDict() expected['file_name'] = 'CreateInteractionChoiceSet' expected['name'] = 'CreateInteractionChoiceSet' expected['imports'] = { self.producer.imports(what='Choice', wherefrom='../structs/Choice.js'), self.producer.imports(what='RpcRequest', wherefrom='../RpcRequest.js'), self.producer.imports(what='FunctionID', wherefrom='../enums/FunctionID.js') } expected['methods'] = (self.producer.methods( key='KEY_CHOICE_SET', method_title='ChoiceSet', external='Choice', description=['A choice is an option given to'], param_name='set', type='Choice[]', param_values={}, since=None, history=None, deprecated=None), ) expected['params'] = (self.producer.params(key='KEY_CHOICE_SET', value="'choiceSet'"), ) expected['description'] = ['creates interaction'] expected['since'] = None expected['history'] = None expected['deprecated'] = None expected['func'] = 'CreateInteractionChoiceSet' expected['extend'] = 'RpcRequest' result = self.producer.transform(item) self.assertDictEqual(expected, result)
def test_SingleTireStatus(self): item = Struct(name='SingleTireStatus', members={ 'tpms': Param(name='tpms', param_type=Enum(name='TPMS')) }) expected = { 'package_name': 'com.smartdevicelink.proxy.rpc', 'imports': ['android.support.annotation.NonNull', '', 'com.smartdevicelink.proxy.RPCStruct', '', 'java.util.Hashtable'], 'class_name': 'SingleTireStatus', 'extends_class': 'RPCStruct', 'since': None, 'deprecated': None, 'params': ( self.producer.params(deprecated=None, key='KEY_TPMS', last='tpms', mandatory=True, origin='tpms', return_type='TPMS', since=None, title='Tpms', description=None, param_doc=None, name=None),) } actual = self.producer.transform(item) self.comparison(expected, actual)
def test_LocationDetails(self): item = Struct(name='LocationDetails', members={ 'searchAddress': Param(name='searchAddress', param_type=Struct(name='OASISAddress')) }) expected = { 'package_name': 'com.smartdevicelink.proxy.rpc', 'imports': ['android.support.annotation.NonNull', '', 'com.smartdevicelink.proxy.RPCStruct', '', 'java.util.Hashtable'], 'class_name': 'LocationDetails', 'extends_class': 'RPCStruct', 'since': None, 'deprecated': None, 'params': ( self.producer.params(deprecated=None, key='KEY_SEARCH_ADDRESS', last='searchAddress', mandatory=True, origin='searchAddress', return_type='OASISAddress', since=None, title='SearchAddress', description=None, param_doc=None, name=None),) } actual = self.producer.transform(item) self.comparison(expected, actual)
def test_OASISAddress(self): item = Struct(name='OASISAddress', members={ 'countryName': Param(name='countryName', param_type=String(max_length=200)) }) expected = { 'package_name': 'com.smartdevicelink.proxy.rpc', 'imports': ['android.support.annotation.NonNull', '', 'com.smartdevicelink.proxy.RPCStruct', '', 'java.util.Hashtable'], 'class_name': 'OASISAddress', 'extends_class': 'RPCStruct', 'since': None, 'deprecated': None, 'params': ( self.producer.params(deprecated=None, key='KEY_COUNTRY_NAME', last='countryName', mandatory=True, origin='countryName', return_type='String', since=None, title='CountryName', description=None, param_doc=None, name=None),) } actual = self.producer.transform(item) self.comparison(expected, actual)
def _parse_struct_param(self, element, prefix): """Parse element as structure parameter. :param element: an instance of Element (from ElementTree) :param prefix: empty string :return: an instance of model.param """ params, subelements, attrib = self._parse_param_base_item( element, prefix) if len(attrib) != 0: raise ParseError("Unknown attribute(s) {0} in param {1}".format( attrib, params["name"])) if len(subelements) != 0: raise ParseError("Unknown subelements in param '{}'".format( params["name"])) return Param(**params)
def test_SoftButton(self): item = Struct(name='SoftButton', members={ 'image': Param(name='image', param_type=Struct(name='Image'), description=['Optional image']), }, description=['\n Describes different audio type configurations for PerformAudioPassThru.\n ']) expected = { 'package_name': 'com.smartdevicelink.proxy.rpc', 'imports': ['android.support.annotation.NonNull', '', 'com.smartdevicelink.proxy.RPCStruct', '', 'java.util.Hashtable'], 'class_name': 'SoftButton', 'extends_class': 'RPCStruct', 'since': None, 'deprecated': None, 'description': ['Describes different audio type configurations for ' 'PerformAudioPassThru.'], 'params': (self.producer.params(deprecated=None, description=['Optional image'], key='KEY_IMAGE', last='image', mandatory=True, origin='image', return_type='Image', since=None, title='Image', param_doc=None, name=None),) } actual = self.producer.transform(item) self.comparison(expected, actual)
def test_CloudAppProperties(self): item = Struct(name='CloudAppProperties', members={ 'nicknames': Param(name='nicknames', param_type=Array(element_type=String(max_length=100, min_length=0), max_size=100, min_size=0)), }) expected = { 'class_name': 'CloudAppProperties', 'extends_class': 'RPCStruct', 'package_name': 'com.smartdevicelink.proxy.rpc', 'imports': ['android.support.annotation.NonNull', '', 'com.smartdevicelink.proxy.RPCStruct', '', 'java.util.Hashtable', 'java.util.List'], 'deprecated': None, 'since': None, 'params': (self.producer.params(deprecated=None, key='KEY_NICKNAMES', last='nicknames', mandatory=True, origin='nicknames', return_type='List<String>', name=None, since=None, title='Nicknames', description=None, param_doc=None),), } actual = self.producer.transform(item) self.comparison(expected, actual)
def test_OnEncodedSyncPDataNotification(self): params = OrderedDict() params['URL'] = Param(name='URL', param_type=String(), description=['\n If ']) item = Function(name='OnEncodedSyncPData', function_id=Enum(name='OnEncodedSyncPDataID'), description=['\n Callback including \n'], message_type=EnumElement(name='notification'), params=params) expected = OrderedDict() expected['file_name'] = 'OnEncodedSyncPData' expected['name'] = 'OnEncodedSyncPData' expected['imports'] = { self.producer.imports(what='RpcNotification', wherefrom='../RpcNotification.js'), self.producer.imports(what='FunctionID', wherefrom='../enums/FunctionID.js') } expected['methods'] = (self.producer.methods(key='KEY_URL', method_title='URL', external=None, description=['If'], param_name='url', type='String', param_values={}, since=None, history=None, deprecated=None), ) expected['params'] = (self.producer.params(key='KEY_URL', value="'URL'"), ) expected['description'] = ['Callback including'] expected['since'] = None expected['history'] = None expected['deprecated'] = None expected['func'] = 'OnEncodedSyncPData' expected['extend'] = 'RpcNotification' result = self.producer.transform(item) self.assertDictEqual(expected, result)
def test_OnEncodedSyncPDataNotification(self): item = Function(name='OnEncodedSyncPData', function_id=None, description=['\n Callback including \n'], message_type=EnumElement(name='notification'), params={ 'URL': Param(name='URL', param_type=String(), description=['\n If ']) }) expected = self.expected_template.copy() expected['kind'] = 'notification' expected['function_id'] = 'ON_ENCODED_SYNC_PDATA' expected['class_name'] = 'OnEncodedSyncPData' expected['extends_class'] = 'RPCNotification' expected['history'] = None expected['imports'] = [ 'androidx.annotation.NonNull', '', 'com.smartdevicelink.protocol.enums.FunctionID', 'com.smartdevicelink.proxy.RPCNotification', '', 'java.util.Hashtable' ] expected['description'] = ['Callback including'] expected['params'] = (self.producer.params(deprecated=None, description=['If'], key='KEY_URL', last='URL', title='URL', SuppressWarnings=None, mandatory=True, origin='URL', return_type='String', since=None, param_doc=None, name=None), ) actual = self.producer.transform(item) self.comparison(expected, actual)
def test_GetVehicleDataResponse(self): params = OrderedDict() params['speed'] = Param(name='speed', param_type=Float(max_value=700.0, min_value=0.0)) item = Function(name='GetVehicleData', function_id=None, message_type=EnumElement(name='response'), params=params) expected = self.expected_template.copy() expected['kind'] = 'response' expected['function_id'] = 'GET_VEHICLE_DATA' expected['class_name'] = 'GetVehicleDataResponse' expected['extends_class'] = 'RPCResponse' expected['history'] = None expected['imports'] = [ 'androidx.annotation.NonNull', '', 'com.smartdevicelink.protocol.enums.FunctionID', 'com.smartdevicelink.proxy.RPCResponse', 'com.smartdevicelink.proxy.rpc.enums.Result', 'com.smartdevicelink.util.SdlDataTypeConverter', '', 'java.util.Hashtable' ] expected['params'] = (self.producer.params(deprecated=None, key='KEY_SPEED', description=None, last='speed', mandatory=True, SuppressWarnings=None, origin='speed', return_type='Float', since=None, title='Speed', param_doc=None, name=None), ) actual = self.producer.transform(item) self.comparison(expected, actual)
def test_CloudAppProperties(self): """ generator/transformers/common_producer.py 64% generator/transformers/structs_producer.py 100% """ members = OrderedDict() members['appID'] = Param(name='appID', param_type=String()) members['value'] = Param(name='value', param_type=String()) item = Struct(name='CloudAppProperties', members=members) expected = OrderedDict() expected['origin'] = 'CloudAppProperties' expected['name'] = 'SDLCloudAppProperties' expected['extends_class'] = 'SDLRPCStruct' expected['imports'] = { '.m': set(), '.h': { 'enum': {'SDLRPCStruct'}, 'struct': set() } } expected['params'] = ( self.producer.param_named( constructor_argument='appID', constructor_argument_override=None, constructor_prefix='AppID', deprecated=False, description=[ '{"default_value": null, "max_length": null, "min_length": null}' ], for_name='object', mandatory=True, method_suffix='AppID', modifier='strong', of_class='NSString.class', origin='appID', since=None, type_native='NSString *', type_sdl='NSString *'), self.producer.param_named( constructor_argument='valueParam', constructor_argument_override=None, constructor_prefix='ValueParam', deprecated=False, description=[ '{"default_value": null, "max_length": null, "min_length": null}' ], for_name='object', mandatory=True, method_suffix='ValueParam', modifier='strong', of_class='NSString.class', origin='valueParam', since=None, type_native='NSString *', type_sdl='NSString *')) argument = [ self.producer.argument_named(variable='appID', deprecated=False, constructor_argument='appID', origin='appID'), self.producer.argument_named(variable='valueParam', deprecated=False, constructor_argument='valueParam', origin='valueParam') ] expected['constructors'] = (self.producer.constructor_named( all=argument, arguments=argument, deprecated=False, self='', init='AppID:(NSString *)appID valueParam:(NSString *)valueParam'), ) actual = self.producer.transform(item) self.assertDictEqual(expected, actual)
def test_full_generation(self): """Test full generation using SDLPRC SmartSchema generator. Creates output files which is captured by the mock and compare them with sample files with correct code. This test requires valid test_expected_sdlrpc.h and test_expected_sdlrpc.cc in the same as this module. """ self.maxDiff = None expected_h_file_content = Path(__file__).parents[0].joinpath('test_expected_sdlrpc.h').read_text() expected_cc_file_content = Path(__file__).parents[0].joinpath('test_expected_sdlrpc.cc').read_text() generator = SmartFactorySDLRPC.CodeGenerator() message_type_elements = collections.OrderedDict() message_type_elements[u"request"] = EnumElement(name=u"request") message_type_elements[u"response"] = EnumElement( name=u"response") message_type_elements[u"notification"] = EnumElement( name=u"notification") message_type = Enum(name=u"messageType", elements=message_type_elements) elements1 = collections.OrderedDict() elements1[u"name1"] = EnumElement( name=u"name1", design_description=DESIGN_DESCRIPTION, todos=TODOS, value=u"1") elements1[u"name2"] = EnumElement( name="name2", description=DESCRIPTION, issues=ISSUES, internal_name=u"internal_name2") enum1 = Enum(name=u"Enum1", todos=TODOS, elements=elements1) elements2 = collections.OrderedDict() elements2[u"xxx"] = EnumElement(name=u"xxx", internal_name=u"val_1") elements2[u"yyy"] = EnumElement(name=u"yyy", internal_name=u"val_2", value=u"100") elements2[u"zzz"] = EnumElement(name=u"val_3") enum2 = Enum(name=u"E2", elements=elements2) elements3 = collections.OrderedDict() elements3["1"] = EnumElement(name="xxx", internal_name="_1") elements3["2"] = EnumElement(name="xxx", internal_name="_2") elements3["3"] = EnumElement(name="xxx", internal_name="_3") enum3 = Enum(name="Enum_new2", elements=elements3) elements4 = collections.OrderedDict() elements4["name1"] = EnumElement(name="xxx", internal_name="_11") elements4["name2"] = EnumElement(name="xxx", internal_name="_22") enum4 = Enum(name="Enum_new4", elements=elements4) enums = collections.OrderedDict() enums["Enum1"] = enum1 enums["Enum2"] = enum2 enums["Enum3"] = enum3 enums["Enum4"] = enum4 enums["messageType"] = message_type params1 = collections.OrderedDict() params1["1"] = Param( name="param1", design_description=DESIGN_DESCRIPTION, description=DESCRIPTION, issues=ISSUES, todos=TODOS, param_type=enum4, default_value=elements4["name1"]) params1["2"] = Param( name="param2", param_type=EnumSubset( name="sub1", enum=enum1, allowed_elements={"e1": elements1["name1"]}), default_value=elements1["name1"]) functions = collections.OrderedDict() functions["Function1"] = Function( name="Function1", function_id=elements1["name1"], message_type=message_type_elements["request"], params=params1) functions["Function2"] = Function( name="Function2", function_id=elements2["xxx"], message_type=message_type_elements["response"]) functions["Function3"] = Function( name="Function2", function_id=elements2["yyy"], message_type=message_type_elements["notification"]) members1 = collections.OrderedDict() members1["m1"] = Param(name="intParam", param_type=Integer(max_value=2)) members1["m11"] = Param(name="doubleParam", param_type=Float(min_value=0.333), is_mandatory=False) members1["m222"] = Param(name="boolParam", param_type=Boolean()) members1["m2"] = Param(name="structParam", param_type=Struct(name="Struct2")) members1["aaa"] = Param(name="enumParam", param_type=enum1) members1["bbb"] = Param(name="enumParam1", param_type=enum1) members1["xxx"] = Param( name="enumSubset1", param_type=EnumSubset( name="sub", enum=enum1, allowed_elements={"e1": elements1["name1"]}), is_mandatory=False) members1["1"] = Param( name="arrayOfInt", param_type=Array(min_size=0, max_size=20, element_type=Boolean()), is_mandatory=False) members1["2"] = Param( name="arrayOfEnum1", param_type=Array(min_size=0, max_size=20, element_type=enum1), is_mandatory=False) members1["3"] = Param( name="arrayOfEnum3", param_type=Array(min_size=10, max_size=40, element_type=enum3), is_mandatory=True) members1["4"] = Param( name="arrayOfEnum4", param_type=Array( min_size=10, max_size=41, element_type=EnumSubset( name="sub1", enum=enum1, allowed_elements={"e1": elements1["name1"]}))) members1["5"] = Param( name="arrayOfEnum5", param_type=Array( min_size=10, max_size=42, element_type=EnumSubset( name="sub2", enum=enum1, allowed_elements={"e1": elements1["name2"]}))) members1["6"] = Param( name="arrayOfEnum6", param_type=Array( min_size=10, max_size=43, element_type=EnumSubset( name="sub3", enum=enum4, allowed_elements={"e1": elements4["name2"]}))) structs = collections.OrderedDict() structs["Struct1"] = Struct( name="Struct1", design_description=DESIGN_DESCRIPTION, issues=ISSUES, members=members1) structs["Struct2"] = Struct(name="Struct2", issues=ISSUES) interface = Interface(enums=enums, structs=structs, functions=functions, params={"param1": "value1", "param2": "value2"}) os.path.exists = MagicMock(return_value=True) uuid.uuid1 = MagicMock( return_value=uuid.UUID("12345678123456781234567812345678")) codecs.open = MagicMock() generator.generate(interface=interface, filename="Test.xml", namespace="XXX::YYY::ZZZ", destination_dir="/some/test/dir") os.path.exists.assert_has_calls([call('/some/test/dir')]) open_result = codecs.open mock_calls = open_result.mock_calls self.assertEqual(mock_calls[0], call('/some/test/dir/Test.h', mode='w', encoding='utf-8'), "Invalid header file creation") self.assertEqual(mock_calls[4], call('/some/test/dir/Test_schema.h', mode='w', encoding='utf-8'), "Invalid source file creation") try: self.assertSequenceEqual(str(mock_calls[2])[27:-2].replace("\\n", "\n"), expected_h_file_content, "Invalid header file content") self.assertSequenceEqual(str(mock_calls[6])[27:-2].replace("\\n", "\n"), expected_cc_file_content, "Invalid source file content") except AssertionError as message: print(message)
def test_RegisterAppInterfaceResponse(self): """ generator/transformers/common_producer.py 82% generator/transformers/functions_producer.py 63% """ params = OrderedDict() params['success'] = Param(name='success', param_type=Boolean(), description=[' True if '], is_mandatory=False) params['language'] = Param( name='language', is_mandatory=False, param_type=Enum(name='Language', elements={ 'EN-US': EnumElement(name='EN-US', description=['English - US']) }), description=['The currently']) params['supportedDiagModes'] = Param( name='supportedDiagModes', is_mandatory=False, description=['\n Specifies the'], param_type=Array(element_type=Integer(max_value=255, min_value=0), max_size=100, min_size=1)) params['hmiZoneCapabilities'] = Param( name='hmiZoneCapabilities', is_mandatory=False, param_type=Array(element_type=Enum(name='HmiZoneCapabilities'), max_size=100, min_size=1)) item = Function(name='RegisterAppInterface', function_id=EnumElement(name='RegisterAppInterfaceID'), description=['The response '], message_type=EnumElement(name='response'), params=params) expected = OrderedDict() expected['origin'] = 'RegisterAppInterface' expected['name'] = 'SDLRegisterAppInterfaceResponse' expected['extends_class'] = 'SDLRPCResponse' expected['imports'] = { '.h': { 'enum': {'SDLRPCResponse', 'SDLLanguage'}, 'struct': set() }, '.m': {'SDLLanguage'} } expected['description'] = ['The response'] expected['params'] = ( self.producer.param_named(constructor_argument='language', constructor_argument_override=None, constructor_prefix='Language', deprecated=False, description=['The currently'], for_name='enum', mandatory=False, method_suffix='Language', modifier='strong', of_class='', origin='language', since=None, type_native='SDLLanguage ', type_sdl='SDLLanguage '), self.producer.param_named( constructor_argument='supportedDiagModes', constructor_argument_override=None, constructor_prefix='SupportedDiagModes', deprecated=False, description=['Specifies the'], for_name='objects', mandatory=False, method_suffix='SupportedDiagModes', modifier='strong', of_class='NSNumber.class', origin='supportedDiagModes', since=None, type_native='NSArray<NSNumber<SDLUInt> *> *', type_sdl='NSArray<NSNumber<SDLUInt> *> *'), self.producer.param_named( constructor_argument='hmiZoneCapabilities', constructor_argument_override=None, constructor_prefix='HmiZoneCapabilities', deprecated=False, description=[], for_name='enums', mandatory=False, method_suffix='HmiZoneCapabilities', modifier='strong', of_class='', origin='hmiZoneCapabilities', since=None, type_native='NSArray<SDLHmiZoneCapabilities> *', type_sdl='NSArray<SDLHmiZoneCapabilities> *')) arguments = [ self.producer.argument_named(variable='language', deprecated=False, origin='language', constructor_argument='language'), self.producer.argument_named( variable='supportedDiagModes', deprecated=False, origin='supportedDiagModes', constructor_argument='supportedDiagModes'), self.producer.argument_named( variable='hmiZoneCapabilities', deprecated=False, origin='hmiZoneCapabilities', constructor_argument='hmiZoneCapabilities') ] expected['constructors'] = (self.producer.constructor_named( all=arguments, arguments=arguments, deprecated=False, init= 'Language:(nullable SDLLanguage)language supportedDiagModes:(nullable NSArray<NSNumber<SDLUInt> *>' ' *)supportedDiagModes hmiZoneCapabilities:(nullable NSArray<SDLHmiZoneCapabilities> *)' 'hmiZoneCapabilities', self=''), ) actual = self.producer.transform(item) self.assertDictEqual(expected, actual)
def test_CreateWindow(self): """ generator/transformers/common_producer.py 82% generator/transformers/functions_producer.py 63% """ params = OrderedDict() params['windowID'] = Param(name='windowID', param_type=Integer()) params['cmdID'] = Param(name='cmdID', param_type=Integer(max_value=2000000000, min_value=0)) params['position'] = Param(name='position', param_type=Integer(default_value=1000, max_value=1000, min_value=0)) params['speed'] = Param(name='speed', param_type=Float(max_value=700.0, min_value=0.0)) params['offset'] = Param(name='offset', param_type=Integer(max_value=100000000000, min_value=0)) params['duplicateUpdatesFromWindowID'] = Param( name='duplicateUpdatesFromWindowID', param_type=Integer(), is_mandatory=False) item = Function(name='CreateWindow', function_id=EnumElement(name='CreateWindowID'), message_type=EnumElement(name='request'), params=params) expected = OrderedDict() expected['origin'] = 'CreateWindow' expected['name'] = 'SDLCreateWindow' expected['extends_class'] = 'SDLRPCRequest' expected['imports'] = { '.m': set(), '.h': { 'struct': set(), 'enum': {'SDLRPCRequest'} } } expected['params'] = ( self.producer.param_named( constructor_argument='windowID', constructor_argument_override=None, constructor_prefix='WindowID', deprecated=False, description=[ '{"default_value": null, "max_value": null, "min_value": null}' ], for_name='object', mandatory=True, method_suffix='WindowID', modifier='strong', of_class='NSNumber.class', origin='windowID', since=None, type_native='UInt32', type_sdl='NSNumber<SDLInt> *'), self.producer.param_named( constructor_argument='cmdID', constructor_argument_override=None, constructor_prefix='CmdID', deprecated=False, description=[ '{"default_value": null, "max_value": 2000000000, "min_value": 0}' ], for_name='object', mandatory=True, method_suffix='CmdID', modifier='strong', of_class='NSNumber.class', origin='cmdID', since=None, type_native='UInt32', type_sdl='NSNumber<SDLUInt> *'), self.producer.param_named( constructor_argument='position', constructor_argument_override=None, constructor_prefix='Position', deprecated=False, description=[ '{"default_value": 1000, "max_value": 1000, "min_value": 0}' ], for_name='object', mandatory=True, method_suffix='Position', modifier='strong', of_class='NSNumber.class', origin='position', since=None, type_native='UInt16', type_sdl='NSNumber<SDLUInt> *'), self.producer.param_named( constructor_argument='speed', constructor_argument_override=None, constructor_prefix='Speed', deprecated=False, description=[ '{"default_value": null, "max_value": 700.0, "min_value": 0.0}' ], for_name='object', mandatory=True, method_suffix='Speed', modifier='strong', of_class='NSNumber.class', origin='speed', since=None, type_native='float', type_sdl='NSNumber<SDLFloat> *'), self.producer.param_named( constructor_argument='offset', constructor_argument_override=None, constructor_prefix='Offset', deprecated=False, description=[ '{"default_value": null, "max_value": 100000000000, "min_value": 0}' ], for_name='object', mandatory=True, method_suffix='Offset', modifier='strong', of_class='NSNumber.class', origin='offset', since=None, type_native='UInt64', type_sdl='NSNumber<SDLUInt> *'), self.producer.param_named( constructor_argument='duplicateUpdatesFromWindowID', constructor_argument_override=None, constructor_prefix='DuplicateUpdatesFromWindowID', deprecated=False, description=[ '{"default_value": null, "max_value": null, "min_value": null}' ], for_name='object', mandatory=False, method_suffix='DuplicateUpdatesFromWindowID', modifier='strong', of_class='NSNumber.class', origin='duplicateUpdatesFromWindowID', since=None, type_native='NSNumber<SDLInt> *', type_sdl='NSNumber<SDLInt> *')) not_mandatory_arguments = [ self.producer.argument_named(variable='windowID', deprecated=False, origin='windowID', constructor_argument='@(windowID)'), self.producer.argument_named(variable='cmdID', deprecated=False, origin='cmdID', constructor_argument='@(cmdID)'), self.producer.argument_named(variable='position', deprecated=False, origin='position', constructor_argument='@(position)'), self.producer.argument_named(variable='speed', deprecated=False, origin='speed', constructor_argument='@(speed)'), self.producer.argument_named(variable='offset', deprecated=False, origin='offset', constructor_argument='@(offset)') ] mandatory_arguments = [ self.producer.argument_named( variable='duplicateUpdatesFromWindowID', deprecated=False, origin='duplicateUpdatesFromWindowID', constructor_argument='duplicateUpdatesFromWindowID') ] expected['constructors'] = ( self.producer.constructor_named( all=not_mandatory_arguments, arguments=not_mandatory_arguments, deprecated=False, self=True, init= 'WindowID:(UInt32)windowID cmdID:(UInt32)cmdID position:(UInt16)position speed:(float)speed ' 'offset:(UInt64)offset'), self.producer.constructor_named( all=not_mandatory_arguments + mandatory_arguments, arguments=mandatory_arguments, deprecated=False, self= 'WindowID:windowID cmdID:cmdID position:position speed:speed offset:offset', init= 'WindowID:(UInt32)windowID cmdID:(UInt32)cmdID position:(UInt16)position speed:(float)speed ' 'offset:(UInt64)offset duplicateUpdatesFromWindowID:(nullable NSNumber<SDLInt> *)' 'duplicateUpdatesFromWindowID')) actual = self.producer.transform(item) self.assertDictEqual(expected, actual)