Beispiel #1
0
    def _writeMethod(self, file: int, method: PyutMethod):
        """
        Writing a method in file : name(param, param, ...).

        Args:
            file:       File descriptor
            method:     method object
        """
        name:       str = method.getName()
        visibility: str = self.__visibility[str(method.getVisibility())]
        returnType: str = str(method.getReturns())
        if returnType == "":
            returnType = "void"

        write(file, f'{self.__tab}{visibility} {returnType} {name}('.encode())

        # for all param
        nbParam = len(method.getParams())
        self.logger.info(f'# params: {nbParam}')
        for param in method.getParams():
            # writing param
            self._writeParam(file, param)

            # comma between param
            nbParam = nbParam - 1
            if nbParam > 0:
                write(file, ' , '.encode())

        write(file, f') {{\n{self.__tab}}}\n\n'.encode())
Beispiel #2
0
    def _writeMethodComment(self, file: int, method: PyutMethod, tab=""):
        """
        Write method comment with doxygen organization.

        Args:
            file:   file descriptor
            method: pyutMethod
            tab:    tab character(s) to use

        """
        write(file, f'{tab}/**\n'.encode())
        write(file, f'{tab} * method {method.getName()}\n'.encode())
        write(file, f'{tab} * More info here.\n'.encode())

        for param in method.getParams():
            write(
                file,
                f'{tab} * @param {param.getName()} : {str(param.getType())}\n'.
                encode())

        if str(method.getReturns()) != '':
            write(file,
                  f'{tab} * @return {str(method.getReturns())}\n'.encode())

        write(file, f'{tab} */\n'.encode())
Beispiel #3
0
    def testStringMethodWithParameters(self):

        pyutMethod: PyutMethod = self._pyutMethod

        PyutMethod.setStringMode(PyutGloballyDisplayParameters.WITH_PARAMETERS)

        self.assertEqual(PyutGloballyDisplayParameters.WITH_PARAMETERS,
                         pyutMethod.getStringMode(),
                         'Did not get set correctly')
    def testCreatePropertiesReadOnly(self):

        propName: str = 'fontSize'
        setterParams: List[str] = []

        setter, getter = self.reverseEngineer._createProperties(
            propName=propName, setterParams=setterParams)
        PyutMethod.setStringMode(PyutGloballyDisplayParameters.WITH_PARAMETERS)

        self.assertIsNone(setter)
        self.assertIsNotNone(getter)
Beispiel #5
0
    def showParams(self, val):
        """
        Choose whether to show the params in the classes or not.

        @param val
        @since 1.17
        @author L. Burgbacher <*****@*****.**>
        """
        if val:
            PyutMethod.setStringMode(WITH_PARAMS)
        else:
            PyutMethod.setStringMode(WITHOUT_PARAMS)
Beispiel #6
0
    def showParams(self, theNewValue: bool):
        """
        Globally choose whether to show the method parameters in classes

        Args:
            theNewValue:
        """
        if theNewValue is True:
            PyutMethod.setStringMode(
                PyutGloballyDisplayParameters.WITH_PARAMETERS)
        else:
            PyutMethod.setStringMode(
                PyutGloballyDisplayParameters.WITHOUT_PARAMETERS)
Beispiel #7
0
    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')
Beispiel #8
0
    def _getMethods(self, Class):
        """
        To extract methods from interface.
        """
        # class methods for this current class
        allMethods = []
        for Method in Class.getElementsByTagName("Method"):

            # method name
            aMethod = PyutMethod(Method.getAttribute('name'))

            # method visibility
            aMethod.setVisibility(Method.getAttribute('visibility'))

            # for method return type
            Return = Method.getElementsByTagName("Return")[0]
            aMethod.setReturns(Return.getAttribute('type'))

            # for methods param
            allParams = []
            for Param in Method.getElementsByTagName("Param"):
                allParams.append(self._getParam(Param))

            # setting the params for this method
            aMethod.setParams(allParams)
            # adding this method in all class methods
            allMethods.append(aMethod)

        return allMethods
    def _generatePyutClasses(self):

        for className in self._classNames():
            pyutClass: PyutClass = PyutClass(name=className)

            pyutClass = self._addFields(pyutClass)

            for methodName in self._methodNames(className):
                pyutMethod: PyutMethod = PyutMethod(name=methodName)
                if methodName[0:2] == "__":
                    pyutMethod.setVisibility(PyutVisibilityEnum.PRIVATE)
                elif methodName[0] == "_":
                    pyutMethod.setVisibility(PyutVisibilityEnum.PROTECTED)
                else:
                    pyutMethod.setVisibility(PyutVisibilityEnum.PUBLIC)
                pyutMethod = self._addParameters(pyutMethod)
                pyutMethod.sourceCode = self.visitor.methodCode[methodName]

                pyutClass.addMethod(pyutMethod)
            setterProperties: PyutPythonVisitor.Parameters = self.visitor.setterProperties
            getterProperties: PyutPythonVisitor.Parameters = self.visitor.getterProperties
            for propName in self.visitor.propertyNames:

                setterParams: List[str] = setterProperties[propName]
                getterParams: List[str] = getterProperties[propName]
                self.logger.info(f'Processing - {propName=} {setterParams=} {getterParams=}')
                setter, getter = self._createProperties(propName=propName, setterParams=setterParams)
                pyutClass.addMethod(setter)
                pyutClass.addMethod(getter)

            self._pyutClasses[className] = pyutClass
        self.logger.info(f'Generated {len(self._pyutClasses)} classes')
    def generatePyutMethods(self,
                            clmethods: List[classmethod]) -> List[PyutMethod]:

        methods: List[PyutMethod] = []
        for me in clmethods:
            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, "", 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.setVisibility("-")
                elif func_name[0] == "_":
                    meth.setVisibility("#")

        return methods
Beispiel #11
0
    def _generatePyutClasses(self):

        for className in self._classNames():
            pyutClass: PyutClass = PyutClass(name=className)

            pyutClass = self._addFields(pyutClass)

            for methodName in self._methodNames(className):
                pyutMethod: PyutMethod = PyutMethod(name=methodName)
                if methodName[0:2] == "__":
                    pyutMethod.setVisibility(PyutVisibilityEnum.PRIVATE)
                elif methodName[0] == "_":
                    pyutMethod.setVisibility(PyutVisibilityEnum.PROTECTED)
                else:
                    pyutMethod.setVisibility(PyutVisibilityEnum.PUBLIC)
                pyutMethod = self._addParameters(pyutMethod)
                pyutMethod.sourceCode = self.visitor.methodCode[methodName]

                pyutClass.addMethod(pyutMethod)

            setterProperties: Parameters = self.visitor.setterProperties
            getterProperties: Parameters = self.visitor.getterProperties

            pyutClass = self._generatePropertiesAsMethods(
                pyutClass, getterProperties, setterProperties)

            if className in self.visitor.dataClassNames:
                self._createDataClassPropertiesAsFields(
                    pyutClass, self.visitor.dataClassProperties)

            self._pyutClasses[className] = pyutClass
        self.logger.info(f'Generated {len(self._pyutClasses)} classes')
    def _addParameters(self, pyutMethod: PyutMethod) -> PyutMethod:

        methodName: str = pyutMethod.name
        if methodName in self.visitor.parameters:
            parameters: PyutPythonVisitor.Parameters = self.visitor.parameters[methodName]
            for parameter in parameters:
                self.logger.debug(f'parameter: {parameter}')
                paramNameType = parameter.split(':')
                #
                # TODO: account for default values
                #
                if len(paramNameType) == 2:         # Somebody is good and did typing
                    pyutType: PyutType = PyutType(paramNameType[1])
                    pyutParam: PyutParam = PyutParam(name=paramNameType[0], theParameterType=pyutType)
                    pyutMethod.addParam(pyutParam)

        return pyutMethod
Beispiel #13
0
    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
Beispiel #14
0
    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'
        ])
        return pyutMethod
    def testCreatePropertiesNormal(self):

        PyutMethod.displayParameters = PyutGloballyDisplayParameters.WITH_PARAMETERS

        propName: str = 'fontSize'
        setterParams: List[str] = ['newSize:int']

        setter, getter = self.reverseEngineer._createProperties(
            propName=propName, setterParams=setterParams)
        PyutMethod.setStringMode(PyutGloballyDisplayParameters.WITH_PARAMETERS)

        self.logger.info(
            f'setter={setter.__str__()} getter={getter.__str__()}')

        self.assertEqual('+fontSize(newSize: int): ', setter.getString(),
                         'Incorrect setter generated')
        self.assertEqual('+fontSize(): int', getter.getString(),
                         'Incorrect getter generated')
Beispiel #16
0
    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}`')
Beispiel #17
0
    def _addParameters(self, pyutMethod: PyutMethod) -> PyutMethod:

        methodName: MethodName = MethodName(pyutMethod.name)
        if methodName in self.visitor.parameters:
            multiParameterNames: MultiParameterNames = self.visitor.parameters[
                methodName]

            pyutParameters: PyutParameters = self._generateParameters(
                multiParameterNames)
            pyutMethod.parameters = pyutParameters

        return pyutMethod
Beispiel #18
0
    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
Beispiel #19
0
    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
Beispiel #20
0
    def generateASingleMethodsCode(self, pyutMethod: PyutMethod, writePass: bool = True) -> List[str]:
        """
        Generate the Python code for the input method

        Args:
            pyutMethod:    The PyutMethod for which we will generate code
            writePass:  If `True` write `pass` in the code

        Returns:
            A list that is the generated code
        """
        methodCode:  List[str] = []

        currentCode: str = self._generateMethodDefinitionStanza(pyutMethod)
        # Add parameters (parameter, parameter, parameter, ...)
        params = pyutMethod.getParams()
        currentCode = self._generateParametersCode(currentCode, params)
        currentCode = f'{currentCode})'

        returnType: PyutType = pyutMethod.getReturns()
        if returnType is not None and returnType.value != '':
            currentCode = f'{currentCode} -> {returnType.value}'

        currentCode = f'{currentCode}:\n'

        # Add to the method code
        methodCode.append(currentCode)

        # Add comments
        methodCode.append(self.__indentStr('"""\n'))
        methodCode = self._generateMethodComments(methodCode, pyutMethod)
        methodCode.append(self.__indentStr('"""\n'))

        if writePass:
            methodCode.append(self.__indentStr('pass\n'))

        methodCode.append('\n')
        return methodCode
Beispiel #21
0
    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
Beispiel #22
0
    def __drawMethodSignature(self, dc: DC, pyutMethod: PyutMethod,
                              pyutClass: PyutClass, x: float, y: float,
                              h: float):
        """
        If preference is not set at individual class level defer to global; Otherwise,
        respect the class level preference

        Args:
            dc:
            pyutMethod:
            pyutClass:
            x:
            y:
            h:
        """
        if pyutClass.displayParameters == PyutDisplayParameters.UNSPECIFIED:
            dc.DrawText(str(pyutMethod), x + MARGIN, y + h)
        elif pyutClass.displayParameters == PyutDisplayParameters.DISPLAY:
            dc.DrawText(pyutMethod.methodWithParameters(), x + MARGIN, y + h)
        elif pyutClass.displayParameters == PyutDisplayParameters.DO_NOT_DISPLAY:
            dc.DrawText(pyutMethod.methodWithoutParameters(), x + MARGIN,
                        y + h)
        else:
            assert False, 'Internal error unknown pyutMethod parameter display type'
Beispiel #23
0
    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)
Beispiel #24
0
    def _getMethods(self, Class):
        """
        Extract a method from a Xmi file from Class part.

        Args:
            Class:  An XML Class

        Returns:  A PyutMethod
        """
        # class methods for this current class
        allMethods = []

        for Method in Class.getElementsByTagName("Foundation.Core.Operation"):

            self.logger.debug(f'_getMethods - Method: {Method}')
            # name = Method.getElementsByTagName("Foundation.Core.ModelElement.name")[0].firstChild
            methodElements: NodeList = Method.getElementsByTagName(
                "Foundation.Core.ModelElement.name")

            self.logger.debug(
                f'_getMethods - {methodElements=}  {methodElements.length=}  type(methodElements): {type(methodElements)}'
            )
            if methodElements.length == 0:
                continue
            elt = methodElements.item(0)
            self.logger.debug(f'_getMethods - elt: {elt}')
            name = elt.firstChild

            if name.nodeType == name.TEXT_NODE:
                aMethod = PyutMethod(name.data)
                self.logger.debug(f'Method name: {name.data}')
                # method visibility
                visibility = Method.getElementsByTagName(
                    "Foundation.Core.ModelElement.visibility")[0]
                # aMethod.setVisibility(self._xmiVisibility2PyutVisibility (visibility.getAttribute('xmi.value')))
                visStr: str = visibility.getAttribute('xmi.value')
                vis: PyutVisibilityEnum = self._xmiVisibility2PyutVisibility(
                    visStr)
                self.logger.debug(f'Method visibility: {vis}')
                aMethod.setVisibility(vis)
                allParams = []
                for Param in Method.getElementsByTagName(
                        "Foundation.Core.Parameter"):
                    pyutParam = self._getParam(Param, aMethod)
                    if pyutParam is not None:
                        allParams.append(pyutParam)

                aMethod.setParams(allParams)

                # adding this method in all class methods
                allMethods.append(aMethod)

        return allMethods
Beispiel #25
0
    def _onMethodAdd(self, event: CommandEvent):
        """
        Add a new method in the list.
        Args:
            event:
        """
        # Add fields in PyutClass copy object
        method: PyutMethod = PyutMethod(PyutMethod.DEFAULT_METHOD_NAME)
        ret = self._invokeEditMethodDialog(method)
        if ret == OK:
            self._pyutModelCopy.methods.append(method)
            # Add fields in dialog list
            self._lstMethodList.Append(method.getString())

            # Tell window that its data has been modified
            fileHandling = self._mediator.getFileHandling()
            project = fileHandling.getCurrentProject()
            if project is not None:
                project.setModified()
Beispiel #26
0
    def generateMethodsCode(self, pyutClass: PyutClass) -> MethodsCodeType:
        """
        Return a dictionary of method code for a given class

        Args:
            pyutClass:  The data model class for which we have to generate a bunch fo code for

        Returns:
            A bunch of code that is the code for this class; The map key is the method name the
            value is a list of the method code
        """
        clsMethods = cast(PyutToPython.MethodsCodeType, {})
        for pyutMethod in pyutClass.methods:
            # Separation
            txt = ""
            lstCodeMethod = [txt]

            # Get code
            subCode:       List[str] = self.generateASingleMethodsCode(pyutMethod)
            lstCodeMethod += self.indent(subCode)

            clsMethods[pyutMethod.getName()] = lstCodeMethod

        # Add fields
        if len(pyutClass.fields) > 0:
            # Create method __init__ if it does not exist
            if PyutToPython.SPECIAL_PYTHON_CONSTRUCTOR not in clsMethods:
                # Separation
                lstCodeMethod = []

                subCode = self.generateASingleMethodsCode(PyutMethod(PyutToPython.SPECIAL_PYTHON_CONSTRUCTOR), False)

                for el in self.indent(subCode):
                    lstCodeMethod.append(str(el))

                clsMethods[PyutToPython.SPECIAL_PYTHON_CONSTRUCTOR] = lstCodeMethod

            clsInit = clsMethods[PyutToPython.SPECIAL_PYTHON_CONSTRUCTOR]
            for pyutField in pyutClass.fields:
                clsInit.append(self.__indentStr(self.__indentStr(self.generateFieldPythonCode(pyutField))))
            clsInit.append('\n')

        return clsMethods
Beispiel #27
0
    def createTestMethod(cls, name: str, visibility: PyutVisibilityEnum,
                         returnType: PyutType) -> PyutMethod:

        pyutMethod: PyutMethod = PyutMethod()

        pyutMethod.name = name
        pyutMethod.visibility = visibility
        pyutMethod.returnType = returnType

        pyutParam: PyutParam = PyutParam(
            name=f'param{TestCommandCommon.methodParamNumber}',
            parameterType=PyutType(
                f'Type{TestCommandCommon.methodTypeNumber}'),
            defaultValue='')

        pyutMethod.addParam(pyutParam)

        TestCommandCommon.methodParamNumber += 1
        TestCommandCommon.methodTypeNumber += 1

        return pyutMethod
    def deserialize(self, serializedData):
        """
        deserialize the data needed by the destroyed OglLinkedObject.

        Args:
            serializedData: serialized data needed by the command.
        """
        from org.pyut.model.PyutMethod import PyutMethod
        from org.pyut.model.PyutParam import PyutParam
        from org.pyut.model.PyutField import PyutField

        from org.pyut.model.PyutStereotype import PyutStereotype
        from org.pyut.model.PyutModifier import PyutModifier

        # deserialize the data common to all OglObjects
        DelOglLinkedObjectCommand.deserialize(self, serializedData)

        # deserialize properties of the OglClass (first level)
        classDescription = getTokenValue("classDescription", serializedData)
        classStereotypeName = getTokenValue("classStereotypeName",
                                            serializedData)
        classShowStereotype = eval(
            getTokenValue("classShowStereotype", serializedData))
        classShowMethods = eval(
            getTokenValue("classShowMethods", serializedData))
        classShowFields = eval(getTokenValue("classShowFields",
                                             serializedData))

        methods = eval(getTokenValue("methods", serializedData))
        fields = eval(getTokenValue("fields", serializedData))

        # set up the first level properties of the pyutClass
        pyutClass: PyutClass = self._shape.getPyutObject()
        pyutClass.description = classDescription

        if cmp(classStereotypeName, ""):
            pyutStereo = PyutStereotype(classStereotypeName)
            pyutClass.setStereotype(pyutStereo)

        pyutClass.setShowStereotype(classShowStereotype)
        pyutClass.showMethods = classShowMethods
        pyutClass.showFields = classShowFields

        for field in fields:

            fieldName = field[0]
            fieldType = field[1]
            fieldDefaultValue = field[2]
            fieldVisibility = field[3]
            pyutClass.addField(
                PyutField(fieldName, fieldType, fieldDefaultValue,
                          fieldVisibility))

        methodsList = []
        # deserialize methods of the pyutClass
        for methodProfile in methods:

            # construction of a method
            methodName = methodProfile[0]
            methodVisibility = methodProfile[1]
            methodReturns = methodProfile[2]
            method = PyutMethod(methodName, methodVisibility, methodReturns)

            # deserialize method's params so we get a tuple (name, Type, defaultValue)
            params = eval(methodProfile[3])
            for param in params:
                paramName = param[0]

                # construction of the type of the param
                paramType = param[1]
                # pyutType = PyutType(paramType)   Not used
                paramDefaultValue = param[2]

                # creates and add the param to the method
                method.addParam(
                    PyutParam(paramName, paramType, paramDefaultValue))

            # deserialize method's modifiers so we get a list of names
            # that we have to transform into a list of PyutModifiers.
            modifiersNames = eval(methodProfile[4])
            modifiers = []
            for modifierName in modifiersNames:
                modifiers.append(PyutModifier(modifierName))

            # add the modifiers to the method
            method.setModifiers(modifiers)
            # add the method to the list of methods
            methodsList.append(method)

        # add all the methods to the list
        pyutClass.methods = methodsList
Beispiel #29
0
    def read(self, umlObject, file):
        """
        Read data from file

        format:
        ```Python
        class name
        <<stereotype_optional>>
        +method([param[:type]]*)[:type_return]
        +field[:type][=value_initial]
        ```

        for example:

        ParentClass
        +strMethod(strParam : str = bogus) : str
        +intMethod(intParam = 1) : int
        +floatField : float = 1.0
        +booleanField : bool = True

        Args:
            umlObject:
            file:
        """
        className: str = file.readline().strip()
        pyutClass: PyutClass = umlObject.getPyutObject()
        pyutClass.setName(className)

        # process stereotype if present
        nextStereoType: str = file.readline().strip()
        if nextStereoType[0:2] == "<<":
            pyutClass.setStereotype(nextStereoType[2:-2].strip())
            nextStereoType = file.readline().strip()

        methods = []
        fields = []
        pyutClass.methods = methods
        pyutClass.fields = fields

        # process methods and fields
        visValues: List[str] = PyutVisibilityEnum.values()
        while True:
            if nextStereoType == "":
                break

            # search visibility

            if nextStereoType[0] in visValues:
                visStr = nextStereoType[0]
                vis: PyutVisibilityEnum = PyutVisibilityEnum.toEnum(visStr)
                nextStereoType = nextStereoType[1:]
            else:
                vis: PyutVisibilityEnum = PyutVisibilityEnum.PUBLIC

            pos = nextStereoType.find("(")
            params = []
            if pos != -1:
                # process method
                name = nextStereoType[0:pos].strip()
                nextStereoType = nextStereoType[pos + 1:]
                pos = nextStereoType.find(")")

                # TODO return typ should be PyutType
                returnType: str = ""
                if pos != -1:
                    params = self._findParams(nextStereoType[:pos])
                    nextStereoType = nextStereoType[pos + 1:]
                    pos = nextStereoType.find(":")

                    if pos != -1:
                        returnType = nextStereoType[pos + 1:].strip()
                    else:
                        returnType = ""
                method = PyutMethod(name, vis, returnType)

                method.setParams([PyutParam(x[0], x[1]) for x in params])
                methods.append(method)
            else:
                # process field
                field = self._findParams(nextStereoType)[0]
                if field:
                    fields.append(PyutField(field[0], field[1],
                                            visibility=vis))

            nextStereoType = file.readline().strip()
Beispiel #30
0
 def setUp(self):
     self.logger: Logger = TestPyutMethod.clsLogger
     self._pyutMethod: PyutMethod = PyutMethod()