def _createProperties( self, propName: str, setterParams: List[str]) -> Tuple[PyutMethod, PyutMethod]: getter: PyutMethod = PyutMethod(name=propName, visibility=PyutVisibilityEnum.PUBLIC) if len(setterParams) == 0: setter: PyutMethod = cast(PyutMethod, None) else: setter = PyutMethod(name=propName, visibility=PyutVisibilityEnum.PUBLIC) if setter is not None: nameType: str = setterParams[0] potentialNameType: List[str] = nameType.split(':') if len(potentialNameType) == 2: param: PyutParam = PyutParam( name=potentialNameType[0], parameterType=PyutType(value=potentialNameType[1])) setter.addParam(param) getter.returnType = PyutType(value=potentialNameType[1]) else: param = PyutParam(name=potentialNameType[0]) setter.addParam(param) return setter, getter
def _makeParameters(self) -> PyutParameters: pyutParameter1: PyutParam = PyutParam(name='intParam', parameterType=PyutType("int"), defaultValue='0') pyutParameter2: PyutParam = PyutParam(name='floatParam', parameterType=PyutType("float"), defaultValue='32.0') parameters: PyutParameters = PyutParameters( [pyutParameter1, pyutParameter2]) return parameters
def testPyutTypeReadOnly(self): """Test PyutType class""" a: PyutType = PyutType("salut") b: PyutType = PyutType("s" + "alut") self.assertTrue(a.value == b.value) try: # noinspection PyUnresolvedReferences a.setName("Salut") except AttributeError as ae: self.logger.info(f'Expected error: {ae}') pass # We should get this error else: self.fail("PyutType should not be modifiable by setName")
def deserialize(cls, serializedData: str, pyutObject: PyutClassCommon) -> PyutClassCommon: """ Args: serializedData: pyutObject: Returns: The updated PyutClass or PyutInterface """ classDescription = deTokenize("classDescription", serializedData) pyutObject.description = classDescription methods = eval(deTokenize("methods", serializedData)) pyutMethods: List[PyutMethod] = [] for methodProfile in methods: # construction of a method methodName: str = methodProfile[0] methodVisibility: PyutVisibilityEnum = PyutVisibilityEnum.toEnum( methodProfile[1]) methodReturns: PyutType = PyutType(value=methodProfile[2]) pyutMethod: PyutMethod = PyutMethod(name=methodName, visibility=methodVisibility, returns=methodReturns) # deserialize method's parameters; Get the tuple (name, Type, defaultValue) params = eval(methodProfile[3]) for param in params: paramName: str = param[0] paramType: PyutType = PyutType(param[1]) paramDefaultValue: str = param[2] # creates and add the param to the method pyutParam: PyutParam = PyutParam( name=paramName, parameterType=paramType, defaultValue=paramDefaultValue) pyutMethod.addParam(pyutParam) pyutMethods.append(pyutMethod) pyutObject.methods = pyutMethods return pyutObject
def _onFieldOk(self, event): """ Activated when button OK from dlgEditField is clicked. Args: event: Associated event """ self.fieldToEdit.setName(self._txtFieldName.GetValue().strip()) from org.pyut.model.PyutType import PyutType self.fieldToEdit.setType( PyutType(self._txtFieldType.GetValue().strip())) visStr: str = self._rdbFieldVisibility.GetStringSelection() vis: PyutVisibilityEnum = PyutVisibilityEnum.toEnum(visStr) self.fieldToEdit.setVisibility(vis) if self._txtFieldDefault.GetValue().strip() != "": self.fieldToEdit.setDefaultValue( self._txtFieldDefault.GetValue().strip()) else: self.fieldToEdit.setDefaultValue(None) # Tell window that its data has been modified fileHandling = self._ctrl.getFileHandling() project = fileHandling.getCurrentProject() if project is not None: project.setModified() # Close dialog self.EndModal(OK)
def _onFieldOk (self, event): """ Activated when button OK from dlgEditField is clicked. Args: event: Associated event """ self._fieldToEdit.setName(self._txtFieldName.GetValue().strip()) from org.pyut.model.PyutType import PyutType self._fieldToEdit.setType(PyutType(self._txtFieldType.GetValue().strip())) visStr: str = self._rdbFieldVisibility.GetStringSelection() vis: PyutVisibilityEnum = PyutVisibilityEnum.toEnum(visStr) self._fieldToEdit.setVisibility(vis) if self._txtFieldDefault.GetValue().strip() != "": self._fieldToEdit.setDefaultValue(self._txtFieldDefault.GetValue().strip()) else: self._fieldToEdit.setDefaultValue(None) self._setProjectModified() # Close dialog self.EndModal(OK)
def generatePyutMethods(self, clsMethods: List[classmethod]) -> List[PyutMethod]: methods: List[PyutMethod] = [] for me in clsMethods: funcName: str = me.__name__ meth: PyutMethod = PyutMethod(funcName) if me is not None: args = getfullargspec(me) if args[3] is None: firstDefVal = len(args[0]) else: firstDefVal = len(args[0]) - len(args[3]) for arg, i in zip(args[0], range(len(args[0]))): # don't add self, it's implied if arg != "self": if i >= firstDefVal: defVal = args[3][i - firstDefVal] if isinstance(defVal, str): defVal = f'"{defVal}"' param = PyutParam(arg, PyutType(""), str(defVal)) else: param = PyutParam(arg) meth.addParam(param) methods.append(meth) # set the visibility according to naming conventions func_name = funcName if func_name[-2:] != "__": if func_name[0:2] == "__": meth.visibility = PyutVisibilityEnum.PRIVATE elif func_name[0] == "_": meth.visibility = PyutVisibilityEnum.PROTECTED return methods
def __init__(self, name="", visibility=PyutVisibilityEnum.PUBLIC, returns: PyutType = PyutType('')): """ Args: name: The method name visibility: Its visibility public, private, protected returns: Its return value """ super().__init__(name) self.logger: Logger = getLogger(__name__) self._visibility: PyutVisibilityEnum = visibility self._modifiers: PyutMethod.PyutModifiers = cast( PyutMethod.PyutModifiers, []) self._sourceCode: PyutMethod.SourceCodeType = cast( PyutMethod.SourceCodeType, []) self._params: PyutMethod.PyutParameters = [] self._returns: PyutType = returns prefs = PyutPreferences() if prefs.showParameters is True: PyutMethod.setStringMode(WITH_PARAMS) else: PyutMethod.setStringMode(WITHOUT_PARAMS)
def __complexParseFieldToPyut(self, fieldData: str) -> PyutField: """ Can look like this: fieldData: x:int=0 Args: fieldData: Returns: """ noCommentFieldData: str = self.__stripEndOfLineComment(fieldData) fieldAndType: List[str] = noCommentFieldData.split(ReverseEngineerPython2.PYTHON_TYPE_DELIMITER) fieldName: str = fieldAndType[0] vis: PyutVisibilityEnum = self.__determineFieldVisibility(fieldName) fieldName = self.__appropriatelyCleanupName(vis=vis, fieldName=fieldName) pyutField: PyutField = PyutField(name=fieldName, visibility=vis) if len(fieldAndType) > 1: typeAndDefaultValue: List[str] = fieldAndType[1].split(ReverseEngineerPython2.PYTHON_ASSIGNMENT) pyutType: PyutType = PyutType(value=typeAndDefaultValue[0].strip()) pyutField.setType(theType=pyutType) if len(typeAndDefaultValue) > 1: pyutField.setDefaultValue(typeAndDefaultValue[1].strip()) return pyutField
def type(self, theType: PyutType): if type(theType) is str: self.logger.warning(f'Setting return type as string is deprecated. use PyutType') theType = PyutType(theType) self.logger.debug(f'theType: `{theType}`') self._type = theType
def _onMethodOk(self, event: Event): """ When button OK from dlgEditMethod is clicked. Args: event: """ self._pyutMethod.name = self._txtName.GetValue() modifiers: PyutModifiers = PyutModifiers([]) for aModifier in self._txtModifiers.GetValue().split(): modifiers.append(PyutModifier(aModifier)) self._pyutMethod.setModifiers(modifiers) returnType: PyutType = PyutType(self._txtReturn.GetValue()) self._pyutMethod.setReturns(returnType) self._pyutMethod.setParams(self._pyutMethodCopy.getParams()) if self._editInterface is False: visStr: str = self._rdbVisibility.GetStringSelection() visibility: PyutVisibilityEnum = PyutVisibilityEnum.toEnum(visStr) self._pyutMethod.setVisibility(visibility) self._pyutMethod.sourceCode = self._pyutMethodCopy.sourceCode self._setProjectModified() # Close dialog self.EndModal(OK)
def _getFields(self, xmlClass: Element) -> PyutFields: """ Extracts fields from a DOM element that represents a UML class Args: xmlClass: The DOM version of a UML class Returns: PyutFields """ pyutFields: PyutFields = cast(PyutFields, []) for element in xmlClass.getElementsByTagName(PyutXmlConstants.ELEMENT_MODEL_FIELD): xmlField: Element = cast(Element, element) pyutField: PyutField = PyutField() strVis: str = xmlField.getAttribute(PyutXmlConstants.ATTR_VISIBILITY) vis: PyutVisibilityEnum = PyutVisibilityEnum.toEnum(strVis) pyutField.setVisibility(vis) xmlParam: Element = xmlField.getElementsByTagName(PyutXmlConstants.ELEMENT_MODEL_PARAM)[0] if xmlParam.hasAttribute(PyutXmlConstants.ATTR_DEFAULT_VALUE): pyutField.setDefaultValue(xmlParam.getAttribute(PyutXmlConstants.ATTR_DEFAULT_VALUE)) pyutField.setName(xmlParam.getAttribute(PyutXmlConstants.ATTR_NAME)) pyutType: PyutType = PyutType(xmlParam.getAttribute(PyutXmlConstants.ATTR_TYPE)) pyutField.setType(pyutType) pyutFields.append(pyutField) return pyutFields
def __init__(self, name="", visibility=PyutVisibilityEnum.PUBLIC, returns: PyutType = PyutType('')): """ TODO: rename `returns` to `returnType` Args: name: The method name visibility: Its visibility public, private, protected returns: Its return value """ prefs: PyutPreferences = PyutPreferences() if name is None or name == '': name = prefs.methodName super().__init__(name) self.logger: Logger = getLogger(__name__) self._visibility: PyutVisibilityEnum = visibility self._modifiers: PyutModifiers = PyutModifiers([]) self._sourceCode: SourceCode = SourceCode([]) self._params: PyutParameters = PyutParameters([]) self._returns: PyutType = returns self._isProperty: bool = False if prefs.showParameters is True: PyutMethod.displayParameters = PyutGloballyDisplayParameters.WITH_PARAMETERS else: PyutMethod.displayParameters = PyutGloballyDisplayParameters.WITHOUT_PARAMETERS
def testGetPublicFieldPythonCode(self): pyutType: PyutType = PyutType(value='') s: str = self.pyutToPython.generateFieldPythonCode(PyutField("publicField", pyutType, None, PyutVisibilityEnum.PUBLIC)) unExpectedValue: int = -1 actualValue: int = s.find('self.publicField') self.assertNotEqual(unExpectedValue, actualValue, f'Did not code generate public method correctly: `{s}`')
def _typedParameter(self, typedParam: str) -> PyutParam: pyutParamAndType: List[str] = typedParam.split(':') paramName: str = pyutParamAndType[0] paramType: str = pyutParamAndType[1] pyutParam: PyutParam = PyutParam( name=paramName, parameterType=PyutType(value=paramType)) return pyutParam
def testSerialize(self): pyutClass: PyutClass = PyutClass(name='Implementor') implementor: OglClass = OglClass(pyutClass=pyutClass) attachmentAnchor: SelectAnchorPoint = SelectAnchorPoint( x=100, y=100, attachmentPoint=AttachmentPoint.NORTH) cOglXFaceCmd: CreateOglInterfaceCommand = CreateOglInterfaceCommand( implementor=implementor, attachmentAnchor=attachmentAnchor) # # Override the created OglInterface2 # oglInterface: OglInterface2 = cOglXFaceCmd._shape pyutInterface: PyutInterface = cOglXFaceCmd._pyutInterface floatMethod: PyutMethod = TestCommandCommon.createTestMethod( 'floatMethod', PyutVisibilityEnum.PRIVATE, PyutType('float')) intMethod: PyutMethod = TestCommandCommon.createTestMethod( 'intMethod', PyutVisibilityEnum.PROTECTED, PyutType('int')) pyutInterface.methods = [intMethod, floatMethod] oglInterface.pyutInterface = pyutInterface cOglXFaceCmd._shape = oglInterface serializedShape: str = cOglXFaceCmd.serialize() self.logger.debug(f'{serializedShape=}') self.assertIsNotNone(serializedShape, 'Something must come back') self.maxDiff = None self.logger.debug( f'{len(self._serializedCommand)=} {len(serializedShape)=}') import re fixedSerializedShape = re.sub('shapeId=[0-9]*', 'shapeId=2', serializedShape) self.logger.debug(f'{fixedSerializedShape=}') expectedValue: str = self._serializedCommand actualValue: str = fixedSerializedShape self.assertEqual(expectedValue, actualValue, 'Oops, something changed')
class TestPyutField(TestBase): clsLogger: Logger = None fieldNames: List[str] = ['field1', 'field2', 'field3'] fieldTypes: List[PyutType] = [ PyutType(value='int'), PyutType(value='bool'), PyutType(value='float') ] fieldValues: List[str] = ['22', 'False', '62.34324'] fieldVisibilities: List[PyutVisibilityEnum] = [ PyutVisibilityEnum.PRIVATE, PyutVisibilityEnum.PUBLIC, PyutVisibilityEnum.PROTECTED ] @classmethod def setUpClass(cls): TestBase.setUpLogging() TestPyutField.clsLogger = getLogger(__name__) def setUp(self): self.logger: Logger = TestPyutField.clsLogger def testDeepCopyList(self): originalFields: List[PyutField] = [] for x in range(len(TestPyutField.fieldNames)): field: PyutField = PyutField( name=TestPyutField.fieldNames[x], fieldType=TestPyutField.fieldTypes[x], defaultValue=TestPyutField.fieldValues[x], visibility=TestPyutField.fieldVisibilities[x]) originalFields.append(field) self.logger.info(f'originalFields: {originalFields}') doppleGangers: List[PyutField] = deepcopy(originalFields) self.logger.info(f'doppleGangers: {doppleGangers}') for pyutField in doppleGangers: self.assertTrue(isinstance(pyutField.type, PyutType), 'Wrong type copied') self.assertTrue( isinstance(pyutField.visibility, PyutVisibilityEnum), 'Wrong visibility type copied')
def testGetProtectedFieldPythonCode(self): pyutType: PyutType = PyutType(value='') s: str = self.pyutToPython.generateFieldPythonCode(PyutField("protectedField", pyutType, None, PyutVisibilityEnum.PROTECTED)) unExpectedValue: int = -1 actualValue: int = s.find('self._protectedField') self.assertNotEqual(unExpectedValue, actualValue, f'Did not code generate protected field correctly: `{s}`')
def testGetOneMethodCodePrivate(self): pyutType: PyutType = PyutType(value='str') publicMethod: PyutMethod = PyutMethod(name='privateMethod', visibility=PyutVisibilityEnum.PRIVATE, returns=pyutType) defCode: List[str] = self.pyutToPython.generateASingleMethodsCode(publicMethod, writePass=False) self.logger.info(f'Generated definition: {defCode}') unExpectedValue: int = -1 actualValue: int = defCode.__contains__('def __privateMethod') self.assertNotEqual(unExpectedValue, actualValue, f'Did not code generate private method correctly: `{defCode}`')
def __addClassMethod(self, className, modifiers, returnType, name, lstFields): """ Add a method to a class Parameters example: ```java static private int getName(int a, long b) - className = name of the class which own this method - static private => modifiers - int => return type - getName => name - int a, long b => lstFields => ["int a", "long b"] ``` Note : Default value can be None. (see names_values) Args: className: Name of the class to add modifiers: Method modifiers returnType: Method returnType name: Method name lstFields: List of string lstFields : Method fields """ self.__logMessage("Adding method %s for class %s" % (name, className)) self.__logMessage("(modifiers=%s; returnType=%s)" % (modifiers, returnType)) # Get class fields po: OglClass = self._classes[className] pc: PyutClass = cast(PyutClass, po.pyutObject) # TODO fix this crazy code to use constructor and catch exception on bad input # Get visibility if "private" in modifiers: visibility: PyutVisibilityEnum = PyutVisibilityEnum.PRIVATE elif "protected" in modifiers: visibility: PyutVisibilityEnum = PyutVisibilityEnum.PROTECTED elif "public" in modifiers: visibility: PyutVisibilityEnum = PyutVisibilityEnum.PUBLIC else: visibility: PyutVisibilityEnum = PyutVisibilityEnum.PUBLIC # Add method methods = pc.methods if returnType == '\n' or returnType == '' or returnType == 'void' or returnType is None: pm = PyutMethod(name, visibility) else: retType: PyutType = PyutType(returnType) pm = PyutMethod(name, visibility, retType) for (paramType, name, defaultValue) in lstFields: param = PyutParam(name, paramType, defaultValue) pm.addParam(param) methods.append(pm)
def testSerialize(self): pyutClassCommon: PyutClassCommon = PyutClassCommon() pyutClassCommon.description = 'I am a test class' floatMethod: PyutMethod = TestCommandCommon.createTestMethod( 'floatMethod', PyutVisibilityEnum.PRIVATE, PyutType('float')) finalMethod: PyutMethod = TestCommandCommon.createTestMethod( 'finalMethod', PyutVisibilityEnum.PROTECTED, PyutType('int')) pyutModifier: PyutModifier = PyutModifier(modifierTypeName='final') finalMethod.addModifier(newModifier=pyutModifier) pyutClassCommon.methods = [floatMethod, finalMethod] serializedMethods: str = MethodInformation.serialize(pyutClassCommon) self.assertNotEqual(0, len(serializedMethods), 'Something should serialize') self.logger.debug(f'{serializedMethods=}')
def testDeepCopyPyutTypes(self): fieldTypes: List[str] = ['int', 'bool', 'float'] originalTypes: List[PyutType] = [] for x in range(len(fieldTypes)): aType: PyutType = PyutType(value=fieldTypes[x]) originalTypes.append(aType) self.logger.info(f'originalTypes: {originalTypes}') doppleGangers: List[PyutType] = deepcopy(originalTypes) self.logger.info(f'doppleGangers: {doppleGangers}')
def __complexTypedAndDefaultValue(self, complexParam: str) -> PyutParam: paramNameType: List[str] = complexParam.split(':') paramName: str = paramNameType[0] paramTypeValue: List[str] = paramNameType[1].split('=') paramType: str = paramTypeValue[0] paramValue: str = paramTypeValue[1] pyutType: PyutType = PyutType(paramType) return PyutParam(name=paramName, parameterType=pyutType, defaultValue=paramValue)
def __init__(self, name: str = "", theFieldType: PyutType = PyutType(''), defaultValue: str = None, visibility: PyutVisibilityEnum = PyutVisibilityEnum.PRIVATE): """ Args: name: The name of the field theFieldType: The field type defaultValue: Its default value if any visibility: The field visibility (private, public, protected) """ super().__init__(name, theFieldType, defaultValue) self._visibility: PyutVisibilityEnum = visibility
def testGenerateParametersSimple(self): multiParameterNames: MultiParameterNames = MultiParameterNames('param') pyutParameters: List[ PyutParam] = self.reverseEngineer._generateParameters( multiParameterNames=multiParameterNames) pyutParameter: PyutParam = pyutParameters[0] self.assertEqual('param', pyutParameter.name, 'Name is incorrect') self.assertIsNone(pyutParameter.defaultValue, 'There should be no default value') self.assertEqual(PyutType(''), pyutParameter.type, 'Should not have a type')
def testGenerateParametersSimpleDefaultValue(self): multiParameterNames: MultiParameterNames = MultiParameterNames( 'param3=57.0') pyutParameters: List[ PyutParam] = self.reverseEngineer._generateParameters( multiParameterNames=multiParameterNames) pyutParameter: PyutParam = pyutParameters[0] self.assertEqual('param3', pyutParameter.name, 'Name is incorrect') self.assertEqual('57.0', pyutParameter.defaultValue) self.assertEqual(PyutType(''), pyutParameter.type, 'Should not have a type')
def _generateAMethod(self) -> PyutMethod: pyutMethod: PyutMethod = PyutMethod(name='OzzeeElGatoDiablo') pyutMethod.sourceCode = SourceCode([ 'weLeft: bool = True', 'isOzzeeAGoodGato: bool = False', 'if weLeft is True:', ' isOzzeeAGoodGato = True', 'return isOzzeeAGoodGato' ]) pyutMethod.modifiers = PyutModifiers( [PyutModifier(modifierTypeName='static'), PyutModifier('bogus')]) pyutMethod.returnType = PyutType('str') return pyutMethod
def setType(self, theType: PyutType): """ Set parameter type Args: theType: """ if type(theType) is str: self.logger.warning(f'Setting return type as string is deprecated. use PyutType') theType = PyutType(theType) self.logger.debug(f'theType: `{theType}`') self._type = theType
def _getMethods(self, xmlClass: Element) -> PyutMethods: """ Converts XML methods to `PyutMethod`s Args: xmlClass: A DOM element that is a UML Class Returns: A list of `PyutMethod`s associated with the class """ allMethods: PyutMethods = cast(PyutMethods, []) for xmlMethod in xmlClass.getElementsByTagName( PyutXmlConstants.ELEMENT_MODEL_METHOD): pyutMethod: PyutMethod = PyutMethod( xmlMethod.getAttribute(PyutXmlConstants.ATTR_NAME)) strVis: str = xmlMethod.getAttribute( PyutXmlConstants.ATTR_VISIBILITY) vis: PyutVisibilityEnum = PyutVisibilityEnum.toEnum(strVis) pyutMethod.setVisibility(visibility=vis) returnElt: Element = xmlMethod.getElementsByTagName( PyutXmlConstants.ELEMENT_MODEL_RETURN)[0] retTypeStr: str = returnElt.getAttribute( PyutXmlConstants.ATTR_TYPE) retType: PyutType = PyutType(retTypeStr) pyutMethod.setReturns(retType) # # Code supports multiple modifiers, but the dialog allows input of only one # modifiers: NodeList = xmlMethod.getElementsByTagName( PyutXmlConstants.ELEMENT_MODEL_MODIFIER) for xmlModifier in modifiers: xmlModifier: Element = cast(Element, xmlModifier) modName: str = xmlModifier.getAttribute( PyutXmlConstants.ATTR_NAME) pyutModifier: PyutModifier = PyutModifier(modName) pyutMethod.addModifier(pyutModifier) methodParameters = [] for xmlParam in xmlMethod.getElementsByTagName( PyutXmlConstants.ELEMENT_MODEL_PARAM): methodParameters.append(self._getParam(xmlParam)) pyutMethod.setParams(methodParameters) allMethods.append(pyutMethod) return allMethods
def testStringMethodWithParametersRepresentation(self): pyutMethod: PyutMethod = self._pyutMethod pyutMethod.returnType = PyutType('float') pyutMethod.parameters = self._makeParameters() PyutMethod.setStringMode(PyutGloballyDisplayParameters.WITH_PARAMETERS) defaultName: str = PyutPreferences().methodName expectedRepresentation: str = f'+{defaultName}(intParam: int = 0, floatParam: float = 32.0): float' actualRepresentation: str = pyutMethod.__str__() self.assertEqual(expectedRepresentation, actualRepresentation, 'Oops this does not match')