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 _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('')): """ 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 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 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 _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 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
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 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 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 __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 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 _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 _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')