Commit 8e725585 authored by sharanjan's avatar sharanjan

ariyasuthan backend

parent 6e3c83d6
![DrawToCode](docs/Draw2CodeLogo.png)
DrawToCode receives an UML diagram from [Draw.io](https://www.draw.io/) and
makes code from it.
## Getting Started
We don't have the intent to cover all Draw.io features and all programming
languages, to know what you can
use, go to the [Wiki](https://github.com/CoffeeOverflow/DrawToCode/wiki/Technical-Stuff).
### Programming Languages Accepted
* Python
* Java
### Prerequisites
* Python 3.6.7+
Install required packages by:
```bash
pip install -r requirements.txt
```
### Usage
```bash
python main.py --help
```
#### Example
```
python main.py --xml_file=./examples/orcs.xml --code_path=./tmp/orc/ --language=python
```
## Running the Tests
```bash
pytest test/
```
#### Show Coverage
```bash
pytest --cov=src/ test/
```
<mxfile host="www.draw.io" modified="2019-12-10T21:36:53.869Z" agent="Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0" etag="ZljxbVePsDXASHQnVbqm" version="12.3.9" type="device" pages="1"><diagram id="a3amV8sVZWnodPZqNoU5" name="Page-1">7Zhdb5swFIZ/DZeLwIYmuWxIt0VLpU6ptOSqcsENVg2OjNOQ/fqZYsKHoaUTHdnWmwq/2MZ+z9NjnxjQDZMvHO2Ca+ZjagDTTww4NwCYOLb8mwrHTHDMSSZsOfEzySqEFfmJlWgqdU98HFc6CsaoILuq6LEowp6oaIhzdqh2e2C0+tUd2mJNWHmI6uoP4osg35ZZ6F8x2Qb5ly1TvQlR3lkJcYB8dihJ8MqALmdMZE9h4mKaepf7ko373PL2tDCOI9FlwHRBrVtncX83XR6/x4/J/fLb3Sc1yxOie7Vhd7lQ6xXH3ATO9pGP03lMA84OARF4tUNe+vYgoy61QIRUtiz5qGbEXOCkdanWyQAJDmYhFvwou6gBECrPFDRgotqHIgRW7mtQsv9CaUhFfXuaujBGPihv3uAT0Hxah/QG8Rjzwd2ynKpblj20W1Bza44EcimKY/m/PLRfdbqG98vW/Lplrsykg1vlgHOzytGs0kzCkX+ZZn7Z8lLkiFf1BSdErFMLR8BRzY1yNH2eJ+XGMW9EcvXZKCdvbvIJ00Yx7LmVj8tWh33tlKmFQO6A7bmHX8/VAvEtFq/lKj2kpZA5DRHLNY4pEuSputymMKov3DAiN9KajGyrRkK2TTWqfFzVJgJmdSJYRyrzQZvomarTtn8ftIseQDsxUyamBFALMzmgVpnOkfMinz1yBjpyBj8464Gz8X/LGezImf3BWQ+cTfrkbDSuHIJmR9AKuDYl7N4dNLsjaC13oQ/Q3gSapWe09fVSg01eSkUVr1hw9ohdRhmXSsQi2XP2QCitSYiSbZQyKkGQ5RecpVdcIkv2S/UiJL6ffqbxgly9Qhs9lBN2ze+pfke2G7gB73VFtqZaABqLiX8mAnad+KEjAPqoUloKju65djxIsu1apWSUnk22nfSUbW34Z7Mt6KNOaTyeO9fDYLCCePxXHuznh5psFr9DZ92LH/Ph1S8=</diagram></mxfile>
\ No newline at end of file
<mxfile host="www.draw.io" modified="2019-12-10T21:40:31.767Z" agent="Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0" etag="NCuLqCVERDolwC8xPb6h" version="12.3.9" pages="1"><diagram id="a3amV8sVZWnodPZqNoU5" name="Page-1">7Vbfb5swEP5reMwEeKTNY5t0WbdWapVI654iB1/BmsHIOAT218/ENr+zTlOn9mEvie8739n3fceBg5ZJuRY4i+85Aeb4LikdtHJ8/zL4qH5roNJA4F5qIBKUaMhrgQ39CQZ0DXqgBPLeRsk5kzTrgyFPUwhlD8NC8GN/2zNn/VMzHMEI2ISYjdFvlMjYluW2+GegUWxP9lzjSbDdbIA8xoQfOxC6cdBScC71KimXwGruLC867tMZb3MxAan8k4DFLfO2we1+t7irHvMf5f7u625m1CkwO5iCHX/OVL5rQgu1jOrlli+VrE6dX/v2wrosoo7tBEzkUP84ydTi5KCpBPGMQ2jg32Y70Scrq4ngh5RAXZar3MeYSthkdTK0OqomVFgsE6Ysr4nu0mSYK0BIKDuQoW0NPAEpKrXFei+MhNXAPrYd4VmZ4043zA2GTRNGTepWJ7UwUk3LFs+uZbXzHu+vFuusmHHXK3YzfyTbln/BBX4Nqka8TLB3liq0GFDlvjVVaIKqh0rGPH13ZPnorcmaGgcDkiAlV/VcVVbIcJ7TsM+Lql1UT13je03oBz+w9qo0DGurslZJ5VNnrcMCY7VBtWFj9O2AjGb46GnP+UGE8PIjJbGIQL40MceSdiQLJhSzmACGJS36152S0ZzwwNWoPD+J0LATdJkmqvsyGCRq3ko2kTdIpHkYJTp1VVP23zfa/N812sU7bzT0v9FepdGU2X486e3tFyi6+QU=</diagram></mxfile>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<mxfile host="www.draw.io" modified="2019-12-17T14:16:11.947Z" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0" etag="_5Xtbm0DHwJIwc00ywYI" version="12.4.2" type="device" pages="1">
<diagram id="AbfsHDoHPodMjdIZsk2k" name="Page-1">
<mxGraphModel dx="1422" dy="791" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="T5OoOEsfuNDpL02fCPJh-1" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;b&gt;Context&lt;/b&gt;&lt;br&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ strategy: Strategy&lt;br&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ doSomeBusinessLogic(): void&lt;br&gt;&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="20" y="340" width="210" height="100" as="geometry"/>
</mxCell>
<mxCell id="T5OoOEsfuNDpL02fCPJh-3" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;i&gt;&amp;lt;&amp;lt;Interface&amp;gt;&amp;gt;&lt;/i&gt;&lt;br&gt;&lt;b&gt;Strategy&lt;/b&gt;&lt;br&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ doAlgorithm(data: ArrayList&amp;lt;String&amp;gt;): ArrayList&amp;lt;String&amp;gt;&lt;br&gt;&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="300" y="345" width="320" height="90" as="geometry"/>
</mxCell>
<mxCell id="T5OoOEsfuNDpL02fCPJh-5" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;b&gt;ConcreteStrategyA&lt;/b&gt;&lt;br&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ doAlgorithm(data: ArrayList&amp;lt;String&amp;gt;): ArrayList&amp;lt;String&amp;gt;&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="130" y="536" width="320" height="64" as="geometry"/>
</mxCell>
<mxCell id="T5OoOEsfuNDpL02fCPJh-6" value="" style="endArrow=block;dashed=1;endFill=0;endSize=12;html=1;exitX=0.5;exitY=0;exitDx=0;exitDy=0;entryX=0.5;entryY=1;entryDx=0;entryDy=0;" edge="1" parent="1" source="T5OoOEsfuNDpL02fCPJh-5" target="T5OoOEsfuNDpL02fCPJh-3">
<mxGeometry width="160" relative="1" as="geometry">
<mxPoint x="210" y="550" as="sourcePoint"/>
<mxPoint x="370" y="550" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="T5OoOEsfuNDpL02fCPJh-7" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;b&gt;ConcreteStrategyB&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ doAlgorithm(data: ArrayList&amp;lt;String&amp;gt;): ArrayList&amp;lt;String&amp;gt;&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="470" y="536" width="320" height="64" as="geometry"/>
</mxCell>
<mxCell id="T5OoOEsfuNDpL02fCPJh-8" value="" style="endArrow=block;dashed=1;endFill=0;endSize=12;html=1;exitX=0.5;exitY=0;exitDx=0;exitDy=0;entryX=0.5;entryY=1;entryDx=0;entryDy=0;" edge="1" parent="1" source="T5OoOEsfuNDpL02fCPJh-7" target="T5OoOEsfuNDpL02fCPJh-3">
<mxGeometry width="160" relative="1" as="geometry">
<mxPoint x="290" y="546" as="sourcePoint"/>
<mxPoint x="470" y="440" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="T5OoOEsfuNDpL02fCPJh-10" value="" style="endArrow=open;endFill=1;endSize=12;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;exitX=1;exitY=0.5;exitDx=0;exitDy=0;" edge="1" parent="1" source="T5OoOEsfuNDpL02fCPJh-1" target="T5OoOEsfuNDpL02fCPJh-3">
<mxGeometry width="160" relative="1" as="geometry">
<mxPoint x="30" y="630" as="sourcePoint"/>
<mxPoint x="190" y="630" as="targetPoint"/>
</mxGeometry>
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>
import click
from src.dataToCode.write_files import write_files
from src.xmlToData.drawIoXmlParser import DrawIoXmlParser
# @click.command()
# @click.option('--xml_file', required=True, prompt=True, type=click.File(mode='r'),
# help='The XML file path')
# @click.option('--code_path', required=True, prompt=True, type=click.Path(exists=True),
# help='The path of the code to be written')
# @click.option('--language', required=True, prompt=True,
# type=click.Choice(['python', 'java'], case_sensitive=False),
# help='The programming language of the code to be written')
def run(xml_file, code_path, language):
"""Program that writes code of an UML class diagram"""
draw_io_xml_parser = DrawIoXmlParser(xml_file)
list_of_classes, list_of_interfaces = draw_io_xml_parser.read_xml()
objects = list_of_classes + list_of_interfaces
write_files(objects, code_path, language)
# if __name__ == '__main__':
# run()
from types import resolve_bases
from flask import Flask,jsonify,request,render_template
from werkzeug.utils import secure_filename
app=Flask(__name__,template_folder='templates')
from main import run
import os
# import xmltodict
UPLOAD_FOLDER =r"C:\Users\Ariyasuthan\Music\GenCode\upload"
ALLOWED_EXTENSIONS = set(['xml'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/')
def home():
return render_template('home.html')
@app.route('/',methods=['POST'])
def upload():
if request.method=='POST':
file = request.files['xml']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
return jsonify({'result':'success'})
else:
return jsonify({'result': 'invalid method'}), 400
@app.route('/submit/',methods=['GET','POST'])
def convert():
path=r'C:\Users\Ariyasuthan\Music\GenCode\examples'
# os.chdir(path)
for file in os.listdir(path):
if file.endswith(".xml"):
file_path = f"{path}\{file}"
run(file_path,'tmp\orc','python')
# return render_template('home.html')
# @app.route('/view/')
# def view_python_script():
# Folder path
path=r'C:\Users\Ariyasuthan\Music\GenCode\tmp\orc'
os.chdir(path)
content=""
for file in os.listdir():
if file.endswith(".py"):
file_path = f"{path}\{file}"
with open(file_path, "r") as f:
content =content+ f.read()
content=content+"-----------------------------------------------"+"\n"
f = open("python.txt", "a")
f.write(content)
f.close()
print(content)
response={"file":content}
return response
if __name__=="__main__":
app.run(port=3001,debug=True)
from src.dataToCode.dataClasses.visibility import Visibility
class Attribute:
def __init__(self, name: str, type_: str,
visibility: Visibility = Visibility.private):
self.name = name
self.type_ = type_
self.visibility = visibility
def __eq__(self, other: "Attribute"):
cond1 = self.name == other.name
cond2 = self.type_ == other.type_
cond3 = self.visibility == other.visibility
if cond1 and cond2 and cond3:
result = True
else:
result = False
return result
from src.dataToCode.dataClasses.attribute import Attribute
from src.dataToCode.dataClasses.method import Method
from src.dataToCode.dataClasses.interface import Interface
from src.dataToCode.dataClasses.visibility import Visibility
from src.dataToCode.dataClasses.modifier import Modifier
from typing import List
class ClassData:
def __init__(self, name: str,
fields: List[Attribute] = [],
methods: List[Method] = [],
inheritances: List['ClassData'] = [],
implementations: List[Interface] = [],
visibility: Visibility = Visibility.public,
modifier: Modifier = Modifier.none):
self.name = name
self.fields = fields
self.methods = methods
self.inheritances = inheritances
self.implementations = implementations
self.visibility = visibility
self.modifier = modifier
def __eq__(self, other: "ClassData"):
cond1 = self.name == other.name
cond2 = self.fields == other.fields
cond3 = self.methods == other.methods
cond4 = self.inheritances == other.inheritances
cond5 = self.implementations == other.implementations
cond6 = self.visibility == other.visibility
cond7 = self.modifier == other.modifier
if cond1 and cond2 and cond3 and cond4 and cond5 and cond6 and cond7:
return True
else:
return False
from src.dataToCode.dataClasses.visibility import Visibility
from typing import List
from src.dataToCode.dataClasses.method import Method
class Interface:
def __init__(self, name: str,
methods: List[Method],
visibility: Visibility = Visibility.public,
interfaces: List['Interface'] = []):
self.name = name
self.methods = methods
self.interfaces = interfaces
self.visibility = visibility
def __eq__(self, other: "Interface"):
cond1 = self.name == other.name
cond2 = self.methods == other.methods
cond3 = self.interfaces == other.interfaces
cond4 = self.visibility == other.visibility
if cond1 and cond2 and cond3 and cond4:
return True
else:
return False
from src.dataToCode.dataClasses.visibility import Visibility
from src.dataToCode.dataClasses.modifier import Modifier
from src.dataToCode.dataClasses.attribute import Attribute
from typing import List
class Method:
def __init__(self, name: str,
return_type: str = "void",
parameters: List[Attribute] = [],
visibility: Visibility = Visibility.public,
modifier: Modifier = Modifier.none):
self.name = name
self.return_type = return_type
self.parameters = parameters
self.visibility = visibility
self.modifier = modifier
def __eq__(self, other: "Method"):
cond1 = self.name == other.name
cond2 = self.return_type == other.return_type
cond3 = self.visibility == other.visibility
cond4 = self.modifier == other.modifier
cond5 = len(self.parameters) == len(other.parameters)
if not(cond1 and cond2 and cond3 and cond4 and cond5):
return False
for x, y in zip(self.parameters, other.parameters):
if x != y:
return False
return True
from enum import Enum
class Modifier(Enum):
static = "static"
abstract = "abstract"
override = "override"
none = ""
from enum import Enum
class Visibility(Enum):
public = "public"
private = "private"
protected = "protected"
package = "package"
from src.dataToCode.languages.classToCode import ClassToCode
from src.dataToCode.dataClasses.classData import ClassData
from src.dataToCode.dataClasses.modifier import Modifier
from src.dataToCode.languages.ToJava.methodToJava import MethodToJava
from src.dataToCode.languages.ToJava.interfaceToJava import InterfaceToJava
from src.dataToCode.languages.ToJava.inheritanceToJava import InheritanceToJava
class ClassToJava(ClassToCode):
def __init__(self, class_data: ClassData):
self.class_data = class_data
self.method_to_code = MethodToJava(self.class_data.methods, False)
self.inheritance_to_code = InheritanceToJava(self.class_data.inheritances)
def convert(self) -> str:
return (f"import java.util.*;\n\n{self.__formatted_class_header()}\n"
f"{self.__formatted_fields()}"
f"{self.method_to_code.get_formatted_methods()}\n"
f"}}")
def __formatted_class_header(self):
return (f"{self.class_data.visibility.name} {self.class_data.modifier.value}"
f"{'' if self.class_data.modifier is Modifier.none else ' '}"
f"class {self.class_data.name}{self.inheritance_to_code.get_formatted()}"
f"{InterfaceToJava.codeImplementedInterfaces(self.class_data.implementations)}"
f" {{\n")
def __formatted_fields(self):
if len(self.class_data.fields) > 0:
class_fields = [f"\t{fields.visibility.value} {fields.type_} {fields.name};"
for fields in self.class_data.fields]
return '\n'.join(class_fields) + \
("\n\n" if self.class_data.methods else "")
else:
return ""
from src.dataToCode.languages.fileNameToCode import FileNameToCode
from src.dataToCode.dataClasses.classData import ClassData
from src.dataToCode.dataClasses.interface import Interface
from typing import Union
class FileNameToJava(FileNameToCode):
def __init__(self, object_data: Union[ClassData, Interface]):
self.name = object_data.name
def get_file_name(self) -> str:
return f"{self.name}.java"
from src.dataToCode.languages.inheritanceToCode import InheritanceToCode
from src.dataToCode.dataClasses.classData import ClassData
class InheritanceToJava(InheritanceToCode):
def __init__(self, inheritances: [ClassData]):
self.inheritances = inheritances
def get_formatted(self) -> str:
if self.inheritances:
return f" extends {self.__formatted_names()}"
else:
return ''
def __formatted_names(self) -> str:
inheritance_list = [f"{class_data.name}"
for class_data in self.inheritances]
return ', '.join(inheritance_list)
from src.dataToCode.languages.interfaceToCode import InterfaceToCode
from src.dataToCode.dataClasses.interface import Interface
from src.dataToCode.languages.ToJava.methodToJava import MethodToJava
from typing import List
class InterfaceToJava(InterfaceToCode):
def __init__(self, interface: Interface):
self.interface = interface
self.method_to_code = MethodToJava(self.interface.methods, True)
def convert(self) -> str:
return (f"import java.util.*;\n\n"
f"{self.interface.visibility.name} interface {self.interface.name}"
f"{self.codeImplementedInterfaces(self.interface.interfaces)} {{\n\n"
f"{self.method_to_code.get_formatted_methods()}\n"
f"}}")
@staticmethod
def codeImplementedInterfaces(interfaces_list: List[Interface]) -> str:
if len(interfaces_list) > 0:
interfaces_names = [x.name for x in interfaces_list]
interfaces_string = ", ".join(interfaces_names)
result = f" implements {interfaces_string}"
else:
result = ""
return result
from src.dataToCode.dataClasses.classData import ClassData
from src.dataToCode.dataClasses.interface import Interface
from src.dataToCode.languages.languageInterface import LanguageInterface
from src.dataToCode.languages.ToJava.classToJava import ClassToJava
from src.dataToCode.languages.ToJava.interfaceToJava import InterfaceToJava
from src.dataToCode.languages.ToJava.fileNameToJava import FileNameToJava
from typing import Union
class LanguageJava(LanguageInterface):
def get_class_code(self, class_data: ClassData) -> str:
class_java = ClassToJava(class_data)
return class_java.convert()
def get_interface_code(self, interface: Interface) -> str:
interface_java = InterfaceToJava(interface)
return interface_java.convert()
def get_file_name(self, object_data: Union[ClassData, Interface]) -> str:
file_name_to_java = FileNameToJava(object_data)
return file_name_to_java.get_file_name()
from src.dataToCode.languages.methodModifierToCode import MethodModifierToCode
from src.dataToCode.dataClasses.method import Method
from src.dataToCode.dataClasses.modifier import Modifier
class MethodModifierToJava(MethodModifierToCode):
def __init__(self, method: Method):
self.method = method
def formatted_modifier(self) -> str:
return f"{self.__get_modifier_value() + self.__get_modifier_space()}"
def formatted_override(self) -> str:
if self.method.modifier is Modifier.override:
return f"@{self.method.modifier.value}\n\t"
else:
return ""
def __get_modifier_value(self) -> str:
if self.method.modifier is Modifier.override:
return ''
else:
return self.method.modifier.value
def __get_modifier_space(self) -> str:
if self.method.modifier in [Modifier.none, Modifier.override]:
return ''
else:
return " "
from src.dataToCode.languages.methodToCode import MethodToCode
from src.dataToCode.dataClasses.method import Method
from src.dataToCode.dataClasses.attribute import Attribute
from src.dataToCode.languages.ToJava.methodModifierToJava \
import MethodModifierToJava
from typing import List
class MethodToJava(MethodToCode):
def __init__(self, methods: List[Method], is_from_interface: bool):
self.methods = methods
self.is_from_interface = is_from_interface
def get_formatted_methods(self) -> str:
methods_str_list = [f"\t{self.__convert_method(method)}"
for method in self.methods]
return '\n\n'.join(methods_str_list)
def __convert_method(self, method: Method) -> str:
modifier_to_java = MethodModifierToJava(method)
return (f"{modifier_to_java.formatted_override()}"
f"{method.visibility.name} "
f"{modifier_to_java.formatted_modifier()}"
f"{method.return_type} {method.name}"
f"({self.__formatted_parameters(method.parameters)})"
f"{self.__formatted_body()}")
def __formatted_body(self) -> str:
if self.is_from_interface:
return ";"
else:
return " {\n\t\tthrow new UnsupportedOperationException();\n\t}"
def __formatted_parameters(self, parameters: List[Attribute]) -> str:
parameters = [f"{parameter.type_} {parameter.name}"
for parameter in parameters]
return ', '.join(parameters)
from abc import ABC, abstractmethod
class ClassToCode(ABC):
@abstractmethod
def convert(self) -> str:
pass
from abc import ABC, abstractmethod
class FileNameToCode(ABC):
@abstractmethod
def get_file_name(self) -> str:
pass
from abc import ABC, abstractmethod
class InheritanceToCode(ABC):
@abstractmethod
def get_formatted(self) -> str:
pass
from abc import ABC, abstractmethod
class InterfaceToCode(ABC):
@abstractmethod
def convert(self) -> str:
pass
from abc import ABC, abstractmethod
from src.dataToCode.dataClasses.classData import ClassData
from src.dataToCode.dataClasses.interface import Interface
from typing import Union
class LanguageInterface(ABC):
@abstractmethod
def get_class_code(self, class_data: ClassData) -> str:
pass
@abstractmethod
def get_interface_code(self, interface: Interface) -> str:
pass
@abstractmethod
def get_file_name(self, object_data: Union[ClassData, Interface]) -> str:
pass
from abc import ABC, abstractmethod
class MethodModifierToCode(ABC):
@abstractmethod
def formatted_modifier(self) -> str:
pass
@abstractmethod
def formatted_override(self) -> str:
pass
from abc import ABC, abstractmethod
class MethodToCode(ABC):
@abstractmethod
def get_formatted_methods(self) -> str:
pass
from src.dataToCode.dataClasses.classData import ClassData
from src.dataToCode.dataClasses.modifier import Modifier
from src.dataToCode.languages.classToCode import ClassToCode
from src.dataToCode.languages.toPython.initToPython import InitToPython
from src.dataToCode.languages.toPython.methodToPython import MethodToPython
from src.dataToCode.languages.toPython.fileNameToPython import FileNameToPython
class ClassToPython(ClassToCode):
def __init__(self, class_data: ClassData):
self.class_data = class_data
all_methods = self.class_data.methods
for implementation in self.class_data.implementations:
for method in implementation.methods:
if method not in all_methods:
all_methods.append(method)
all_methods = list(all_methods)
self.method_to_code = MethodToPython(all_methods, False)
self.init_to_python = InitToPython(self.class_data.fields)
def convert(self) -> str:
return (f"{self.__formatted_imports()}"
f"class {self.class_data.name}"
f"({self.__formatted_inheritances()}):\n"
f"\n{self.init_to_python.get_formatted()}\n"
f"{self.method_to_code.get_formatted_methods()}\n")
def __formatted_imports(self) -> str:
inheritances = self.class_data.inheritances + self.class_data.implementations
imports = [f"from {FileNameToPython(inheritance).get_file_name()[:-3]} import {inheritance.name}"
for inheritance in inheritances]
optional_import = self.__optional_abc_import()
space = '\n\n\n' if inheritances else '\n\n' if optional_import else ""
return optional_import + '\n'.join(imports) + space
def __optional_abc_import(self) -> str:
for method in self.class_data.methods:
if method.modifier is Modifier.abstract:
return "from abc import ABC, abstractmethod\n"
return ""
def __formatted_inheritances(self) -> str:
inheritances = self.class_data.inheritances + self.class_data.implementations
inheritances_name = [f"{inheritance.name}"
for inheritance in inheritances]
return ', '.join(inheritances_name)
from src.dataToCode.dataClasses.classData import ClassData
from src.dataToCode.dataClasses.interface import Interface
from src.dataToCode.languages.fileNameToCode import FileNameToCode
from typing import Union
import re
class FileNameToPython(FileNameToCode):
def __init__(self, data: Union[ClassData, Interface]):
self.data = data
def get_file_name(self) -> str:
words = re.findall("[A-Z][^A-Z]*", self.data.name)
formatted_name = '_'.join(words)
return formatted_name.lower() + '.py'
from typing import List
from src.dataToCode.dataClasses.attribute import Attribute
from src.dataToCode.languages.toPython.visibilityToPython import visibility_to_python
class InitToPython:
def __init__(self, class_fields: List[Attribute]):
self.class_fields = class_fields
def get_formatted(self) -> str:
pass_ = '\t\tpass'
return (f"\tdef __init__(self" + self.__formatted_parameters() + "):\n"
f"{self.__formatted_assignments() if self.class_fields else pass_}\n")
def __formatted_parameters(self) -> str:
fields_name = [f"{field.name}"
for field in self.class_fields]
return f", {', '.join(fields_name)}" if self.class_fields else ""
def __formatted_assignments(self) -> str:
class_fields = [f"\t\tself.{visibility_to_python[field.visibility]}"
f"{field.name} = {field.name}"
for field in self.class_fields]
return '\n'.join(class_fields)
from src.dataToCode.dataClasses.interface import Interface
from src.dataToCode.languages.interfaceToCode import InterfaceToCode
from src.dataToCode.languages.toPython.methodToPython import MethodToPython
from src.dataToCode.languages.toPython.fileNameToPython import FileNameToPython
class InterfaceToPython(InterfaceToCode):
def __init__(self, interface: Interface):
self.interface = interface
self.method_to_code = MethodToPython(self.interface.methods, True)
def convert(self) -> str:
return (f"{self.__formatted_imports()}"
f"class {self.interface.name}"
f"({self.__formatted_inheritances()}):\n"
f"\n{self.method_to_code.get_formatted_methods()}\n")
def __formatted_imports(self) -> str:
imports = [f"from {FileNameToPython(inheritance).get_file_name()[:-3]} import {inheritance.name}"
for inheritance in self.interface.interfaces]
space = '\n\n\n' if self.interface.interfaces else '\n\n'
return "from abc import ABC, abstractmethod\n" + '\n'.join(imports) + space
def __formatted_inheritances(self) -> str:
inheritances_name = [f"{interface.name}"
for interface in self.interface.interfaces]
abstract_import = "ABC, " if self.interface.interfaces else "ABC"
return abstract_import + ', '.join(inheritances_name)
from src.dataToCode.dataClasses.classData import ClassData
from src.dataToCode.dataClasses.interface import Interface
from src.dataToCode.languages.languageInterface import LanguageInterface
from src.dataToCode.languages.toPython.classToPython import ClassToPython
from src.dataToCode.languages.toPython.interfaceToPython import InterfaceToPython
from src.dataToCode.languages.toPython.fileNameToPython import FileNameToPython
from typing import Union
class LanguagePython(LanguageInterface):
def get_class_code(self, class_data: ClassData) -> str:
class_python = ClassToPython(class_data)
return class_python.convert()
def get_interface_code(self, interface: Interface) -> str:
interface_python = InterfaceToPython(interface)
return interface_python.convert()
def get_file_name(self, object_data: Union[ClassData, Interface]) -> str:
file_name_to_python = FileNameToPython(object_data)
return file_name_to_python.get_file_name()
from typing import List
from src.dataToCode.dataClasses.attribute import Attribute
from src.dataToCode.languages.toPython.visibilityToPython import visibility_to_python
from src.dataToCode.languages.methodToCode import MethodToCode
from src.dataToCode.dataClasses.method import Method
from src.dataToCode.dataClasses.modifier import Modifier
class MethodToPython(MethodToCode):
def __init__(self, methods: List[Method], is_from_interface: bool):
self.methods = methods
self.is_from_interface = is_from_interface
def get_formatted_methods(self) -> str:
methods_str_list = [f"\t{self.__convert_method(method)}"
for method in self.methods]
return '\n\n'.join(methods_str_list)
def __convert_method(self, method: Method) -> str:
return (f"{self.__formatted_modifier(method)}"
f"def {visibility_to_python[method.visibility]}"
f"{method.name}("
f"{'self' if method.modifier is not Modifier.static else ''}"
f"{', ' if method.parameters and method.modifier is not Modifier.static else ''}"
f"{self.__formatted_parameters(method.parameters)}):"
f"{self.__formatted_body()}")
def __formatted_body(self) -> str:
return "\n\t\tpass"
def __formatted_parameters(self, parameters: List[Attribute]) -> str:
parameters = [f"{parameter.name}"
for parameter in parameters]
return ', '.join(parameters)
def __formatted_modifier(self, method: Method) -> str:
if method.modifier is Modifier.abstract or self.is_from_interface:
return "@abstractmethod\n\t"
elif method.modifier is Modifier.static:
return "@staticmethod\n\t"
else:
return ""
from src.dataToCode.dataClasses.visibility import Visibility
visibility_to_python = {Visibility.private: "__",
Visibility.protected: "_",
Visibility.public: "",
Visibility.package: ""}
import os
from src.dataToCode.dataClasses.classData import ClassData
from src.dataToCode.dataClasses.interface import Interface
from src.dataToCode.languages.ToJava.languageJava import LanguageJava
from src.dataToCode.languages.toPython.languagePython import LanguagePython
from src.dataToCode.languages.languageInterface import LanguageInterface
from typing import List, Union
def select_language(language: str) -> LanguageInterface:
language_writer: LanguageInterface
if language == "python":
language_writer = LanguagePython()
elif language == "java":
language_writer = LanguageJava()
else:
raise ValueError("This language is not implemented")
return language_writer
def write_files(objects: List[Union[ClassData, Interface]],
path: str, language: str) -> None:
print('\n')
language_writer = select_language(language)
for element in objects:
if type(element) == ClassData:
source_code = language_writer.get_class_code(element)
elif type(element) == Interface:
source_code = language_writer.get_interface_code(element)
else:
raise ValueError(f"{type(element)} is not acceptable "
f"Use classData or interface")
name = language_writer.get_file_name(element)
element_file_path = os.path.join(path, name)
with open(element_file_path, "w") as element_file:
element_file.write(source_code)
print(f"'{name}' created")
print('Done.')
import xml.etree.ElementTree as ET
from bs4 import BeautifulSoup as bs
from src.dataToCode.dataClasses.attribute import Attribute
from src.dataToCode.dataClasses.classData import ClassData
from src.dataToCode.dataClasses.method import Method
from src.dataToCode.dataClasses.visibility import Visibility
from src.xmlToData.regexExtractors.attributeNameExtractor import AttributeNameExtractor
from src.xmlToData.regexExtractors.methodNameExtractor import MethodNameExtractor
from src.xmlToData.regexExtractors.parametersExtractor import ParametersExtractor
from src.xmlToData.regexExtractors.returnTypeExtractor import ReturnTypeExtractor
from src.xmlToData.regexExtractors.visibilityExtractor import VisibilityExtractor
class ClassParser:
@staticmethod
def read_xml(uml_data: str):
uml_data = uml_data.replace("<br>", "")
uml_data = uml_data.replace("<br/>", "")
list_of_attributes = []
list_of_methods = []
id_to_name = {}
html = bs(uml_data, 'html.parser')
result = html.find_all('p')
class_name = ''
for i in range(len(result)):
if result[i].string is not None:
if i == 0:
class_name = result[i].b.string
id_to_name[id] = class_name
else:
visibility = VisibilityExtractor.extract_visibility(result[i].string)
type_ = ReturnTypeExtractor.extract_type(result[i].string)
if '(' in result[i].string:
name = MethodNameExtractor.extract_name(result[i].string)
list_of_parameters_string = ParametersExtractor.extract_parameters_string(result[i].string)
list_of_parameters = []
if len(list_of_parameters_string) != 0 and list_of_parameters_string[0] != '':
for parameter_string in list_of_parameters_string:
parameter_name = AttributeNameExtractor.extract_name(parameter_string)
parameter_type = ReturnTypeExtractor.extract_type(parameter_string)
parameter = Attribute(parameter_name, parameter_type)
list_of_parameters.append(parameter)
method = Method(name, type_, list_of_parameters, visibility)
list_of_methods.append(method)
else:
name = AttributeNameExtractor.extract_name(result[i].string)
attribute = Attribute(name, type_, visibility)
list_of_attributes.append(attribute)
return ClassData(class_name, list_of_attributes, list_of_methods)
import xml.etree.ElementTree as ET
from typing import Tuple, Dict
from src.xmlToData.classParser import ClassParser
from src.xmlToData.interfaceParser import InterfaceParser
class DrawIoXmlParser:
def __init__(self, filename: str) -> object:
self.filename = filename
@staticmethod
def extract_value_from_cells(root) -> Tuple[list, list, Dict[str, list], Dict[str, list]]:
list_of_xml_classes = []
list_of_ids = []
superclass_to_subclasses = {}
implements_dict = {}
for cell in root.iter('mxCell'):
if cell.get('id') not in ['0', '1']:
if cell.get('value') == 'Extends':
subclass = cell.get('source')
superclass = cell.get('target')
try:
superclass_to_subclasses[superclass].append(subclass)
except KeyError:
superclass_to_subclasses[superclass] = [subclass]
elif "endArrow=block;dashed=1" in cell.get('style'): # implements arrow
source_class = cell.get('source')
target_class = cell.get('target') # interface
try:
implements_dict[target_class].append(source_class)
except KeyError:
implements_dict[target_class] = [source_class]
elif "<b>" in cell.get('value'):
list_of_ids.append(cell.get('id'))
list_of_xml_classes.append(cell.get('value'))
return list_of_xml_classes, list_of_ids, superclass_to_subclasses, implements_dict
def read_xml(self):
xml = ET.parse(self.filename)
root = xml.getroot()
list_of_xml_classes, ids_list, extends_dict, implements_dict = self.extract_value_from_cells(root)
list_of_classes = []
list_of_interfaces = []
ids_to_names = {}
for uml_data, class_id in zip(list_of_xml_classes, ids_list):
if "Interface" in uml_data:
interface_ = InterfaceParser.read_xml(uml_data)
list_of_interfaces.append(interface_)
ids_to_names[class_id] = interface_.name
else:
class_ = ClassParser.read_xml(uml_data)
list_of_classes.append(class_)
ids_to_names[class_id] = class_.name
for superclass_id, subclasses in extends_dict.items():
superclass_name = ids_to_names[superclass_id]
for subclass_id in subclasses:
subclass_name = ids_to_names[subclass_id]
for class_ in list_of_classes:
if class_.name == subclass_name:
list_of_inheritances = class_.inheritances.copy()
for superclass_ in list_of_classes:
if superclass_name == superclass_.name:
list_of_inheritances.append(superclass_)
class_.inheritances = list_of_inheritances.copy()
for interface_id, subclasses in implements_dict.items():
interface_name = ids_to_names[interface_id]
for class_id in subclasses:
class_name = ids_to_names[class_id]
for class_ in list_of_classes:
if class_.name == class_name:
list_of_interfaces_implemented = class_.implementations.copy()
for interface_ in list_of_interfaces:
if interface_name == interface_.name:
list_of_interfaces_implemented.append(interface_)
class_.implementations = list_of_interfaces_implemented.copy()
return list_of_classes, list_of_interfaces
import xml.etree.ElementTree as ET
from bs4 import BeautifulSoup as bs
from src.dataToCode.dataClasses.attribute import Attribute
from src.dataToCode.dataClasses.classData import ClassData
from src.dataToCode.dataClasses.interface import Interface
from src.dataToCode.dataClasses.method import Method
from src.dataToCode.dataClasses.visibility import Visibility
from src.xmlToData.regexExtractors.attributeNameExtractor import AttributeNameExtractor
from src.xmlToData.regexExtractors.methodNameExtractor import MethodNameExtractor
from src.xmlToData.regexExtractors.parametersExtractor import ParametersExtractor
from src.xmlToData.regexExtractors.returnTypeExtractor import ReturnTypeExtractor
from src.xmlToData.regexExtractors.visibilityExtractor import VisibilityExtractor
class InterfaceParser:
@staticmethod
def read_xml(uml_data: str):
list_of_methods = []
list_of_methods_string_literals = []
html = bs(uml_data, 'html.parser')
result = html.find_all('p')
if result[0].b is None:
interface_name = result[1].b.string
else:
interface_name = result[0].b.string
list_of_methods_string_literals += str(result[-1]).split("<br>")
if len(list_of_methods_string_literals) == 1:
list_of_methods_string_literals = str(result[-1]).split("<br/>")
list_of_methods_string_literals[0] = \
list_of_methods_string_literals[0].replace("<p style=\"margin: 0px ; margin-left: 4px\">", "")
list_of_methods_string_literals[-1] = \
list_of_methods_string_literals[-1].replace("</p>", "")
for xml_string in list_of_methods_string_literals:
if xml_string != "":
visibility = VisibilityExtractor.extract_visibility(xml_string)
type_ = ReturnTypeExtractor.extract_type(xml_string)
name = MethodNameExtractor.extract_name(xml_string)
list_of_parameters_string = ParametersExtractor.extract_parameters_string(xml_string)
list_of_parameters = []
if len(list_of_parameters_string) != 0 and list_of_parameters_string[0] != '':
for parameter_string in list_of_parameters_string:
parameter_name = AttributeNameExtractor.extract_name(parameter_string)
parameter_type = ReturnTypeExtractor.extract_type(parameter_string)
parameter = Attribute(parameter_name, parameter_type)
list_of_parameters.append(parameter)
method = Method(name, type_, list_of_parameters, visibility)
list_of_methods.append(method)
return Interface(interface_name, list_of_methods)
import re
class AttributeNameExtractor:
@staticmethod
def extract_name(xml_string) -> str:
regex = re.compile(r"\w+\(*.*:")
name = str(regex.findall(xml_string))[2:-3].strip()
return name
import re
class MethodNameExtractor:
@staticmethod
def extract_name(xml_string) -> str:
regex = re.compile(r"\w+\s*\(")
name = str(regex.findall(xml_string))[2:-3].strip()
return name
import re
class ParametersExtractor:
@staticmethod
def extract_parameters_string(xml_string) -> list:
regex = re.compile(r"\(.*\)")
name = str(regex.findall(xml_string))
unformatted_parameters_string_list = name[3:-3].split(",")
formatted_parameters_string_list = []
for parameter in unformatted_parameters_string_list:
formatted_parameters_string_list.append(parameter.strip())
return formatted_parameters_string_list
import re
class ReturnTypeExtractor:
@staticmethod
def extract_type(xml_string) -> str:
xml_string = xml_string.replace('&lt;', '<')
xml_string = xml_string.replace('&gt;', '>')
regex = re.compile(r"\)*:\s*\w+\<*\w*\>*")
list_of_types = regex.findall(xml_string)
if ')' in list_of_types[-1]:
return list_of_types[-1].split(':')[1].lstrip()
return list_of_types[-1][1:].lstrip()
import re
from src.dataToCode.dataClasses.visibility import Visibility
class VisibilityExtractor:
@staticmethod
def extract_visibility(xml_string) -> Visibility:
types_of_visibilities = {"+": Visibility.public, "-": Visibility.private, "#": Visibility.protected}
regex = re.compile(r"^\s*.")
visibility = str(regex.findall(xml_string))[2:-2]
return types_of_visibilities[visibility.strip()]
<?xml version="1.0" encoding="UTF-8"?>
<mxfile host="www.draw.io" modified="2019-12-08T23:29:10.928Z" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36" version="12.3.8" etag="um7o77m_xlbTrl6i7Fqb" pages="1">
<diagram id="BE0ewzgIN-xuJWGC_8RZ">
<mxGraphModel dx="1024" dy="604" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="2" value="" style="endArrow=block;dashed=1;endFill=0;endSize=12;html=1;" edge="1" source="5" target="10" parent="1">
<mxGeometry width="160" relative="1" as="geometry">
<mxPoint x="253" y="270" as="sourcePoint"/>
<mxPoint x="182" y="330" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="3" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;b&gt;Homem&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ field: Type&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ method(): Type&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="570" y="470" width="160" height="90" as="geometry"/>
</mxCell>
<mxCell id="4" value="Extends" style="endArrow=block;endSize=16;endFill=0;html=1;entryX=0.655;entryY=1.002;entryDx=0;entryDy=0;exitX=0.25;exitY=0;exitDx=0;exitDy=0;entryPerimeter=0;" edge="1" source="3" target="6" parent="1">
<mxGeometry width="160" relative="1" as="geometry">
<mxPoint x="200" y="450" as="sourcePoint"/>
<mxPoint x="360" y="450" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="5" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;b&gt;Mulher&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ field: Type&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ method(): Type&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="300" y="494" width="160" height="90" as="geometry"/>
</mxCell>
<mxCell id="6" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;b&gt;Humano&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ field: Type&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ method(): Type&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="510" y="110" width="160" height="90" as="geometry"/>
</mxCell>
<mxCell id="7" value="Extends" style="endArrow=block;endSize=16;endFill=0;html=1;" edge="1" source="5" target="6" parent="1">
<mxGeometry width="160" relative="1" as="geometry">
<mxPoint x="150" y="540" as="sourcePoint"/>
<mxPoint x="310" y="540" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="8" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;b&gt;Sapiens&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ field: Type&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ method(): Type&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="300" y="180" width="160" height="90" as="geometry"/>
</mxCell>
<mxCell id="9" value="Extends" style="endArrow=block;endSize=16;endFill=0;html=1;entryX=0.5;entryY=1;entryDx=0;entryDy=0;" edge="1" source="5" target="8" parent="1">
<mxGeometry width="160" relative="1" as="geometry">
<mxPoint x="60" y="610" as="sourcePoint"/>
<mxPoint x="220" y="610" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="10" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;i&gt;&amp;lt;&amp;lt;Interface&amp;gt;&amp;gt;&lt;/i&gt;&lt;br&gt;&lt;b&gt;Teste&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ method1(par: int): Type&lt;br&gt;+ method2(par: float, par2: int): int&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="30" y="250" width="200" height="96" as="geometry"/>
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>
This diff is collapsed.
<?xml version="1.0" encoding="UTF-8"?>
<mxfile host="www.draw.io" modified="2019-12-04T01:47:24.931Z" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36 OPR/65.0.3467.48" etag="pO5IWHfNDOWBtVNYYGwo" version="12.3.6" type="device" pages="1">
<diagram id="g6LhOGGpRN36sjTzVXP1" name="Page-1">
<mxGraphModel dx="1422" dy="795" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="2" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;b&gt;Humano&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ idade: int&lt;/p&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;- anos: float&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ get_idade(nome: string, altura: double): int&lt;/p&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;- get_anos(): float&lt;/p&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;&lt;br&gt;&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" parent="1" vertex="1">
<mxGeometry x="160" y="250" width="230" height="110" as="geometry"/>
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>
<?xml version="1.0" encoding="UTF-8"?>
<mxfile host="www.draw.io" modified="2019-12-08T17:48:18.926Z" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36" version="12.3.8" etag="vI5-ryoCUclEbwjNhLZe" pages="1">
<diagram id="eQ7T-b2wzXqvDFbT9Z2O">
<mxGraphModel dx="1024" dy="604" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="2" value="" style="endArrow=block;dashed=1;endFill=0;endSize=12;html=1;exitX=0.5;exitY=0;exitDx=0;exitDy=0;entryX=0.5;entryY=1;entryDx=0;entryDy=0;" edge="1" source="3" target="4" parent="1">
<mxGeometry width="160" relative="1" as="geometry">
<mxPoint x="253" y="270" as="sourcePoint"/>
<mxPoint x="413" y="270" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="3" value="&lt;p style=&quot;margin:0px;margin-top:4px;text-align:center;&quot;&gt;&lt;b&gt;Class&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;/&gt;&lt;p style=&quot;margin:0px;margin-left:4px;&quot;&gt;+ field: Type&lt;/p&gt;&lt;hr size=&quot;1&quot;/&gt;&lt;p style=&quot;margin:0px;margin-left:4px;&quot;&gt;+ method(): Type&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="215" y="360" width="160" height="90" as="geometry"/>
</mxCell>
<mxCell id="4" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;i&gt;&amp;lt;&amp;lt;Interface&amp;gt;&amp;gt;&lt;/i&gt;&lt;/p&gt;&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;i&gt;&lt;b&gt;Teste&lt;/b&gt;&lt;/i&gt;&lt;br&gt;&lt;/p&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ field1: Type&lt;br&gt;+ field2: Type&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ method1(Type): Type&lt;br&gt;+ method2(Type, Type): Type&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="170" y="120" width="190" height="140" as="geometry"/>
</mxCell>
<mxCell id="5" value="Extends" style="endArrow=block;endSize=16;endFill=0;html=1;entryX=0.25;entryY=1;entryDx=0;entryDy=0;exitX=0.25;exitY=0;exitDx=0;exitDy=0;" edge="1" source="3" target="4" parent="1">
<mxGeometry width="160" relative="1" as="geometry">
<mxPoint x="200" y="450" as="sourcePoint"/>
<mxPoint x="360" y="450" as="targetPoint"/>
</mxGeometry>
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>
<?xml version="1.0" encoding="UTF-8"?>
<mxfile host="www.draw.io" modified="2019-12-07T03:43:31.733Z" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36 OPR/65.0.3467.62" etag="lsqnB_xh8s1wgKrGwybE" version="12.3.8" type="device" pages="1">
<diagram id="x-2iUQGIe-bETlHNBhCO" name="Page-1">
<mxGraphModel dx="1422" dy="795" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="-cuIEp4vuOl5B3aBU6dm-1" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;i&gt;&amp;lt;&amp;lt;Interface&amp;gt;&amp;gt;&lt;/i&gt;&lt;br&gt;&lt;b&gt;CalculoDeSalario&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ calcular_salario_1(funcionario: Funcionario): float&lt;br&gt;+ calcular_salario_2(funcionario: Funcionario, carga_horaria: int): float&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="190" y="170" width="390" height="130" as="geometry"/>
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>
<?xml version="1.0" encoding="UTF-8"?>
<mxfile host="www.draw.io" modified="2019-12-04T15:53:24.073Z" agent="Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0" etag="BaVnQZvkymO3y9uEfkWL" version="12.3.6" type="device" pages="1">
<diagram id="g6LhOGGpRN36sjTzVXP1" name="Page-1">
<mxGraphModel dx="1046" dy="609" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="1wNa7OV5EON6lKZaAW-1-7" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;b&gt;Humano&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ idade: int&lt;/p&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;- anos: float&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ get_idade(nome: string, altura: double): int&lt;/p&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;- get_anos(): float&lt;/p&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;&lt;br&gt;&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry y="130" width="230" height="110" as="geometry"/>
</mxCell>
<mxCell id="1wNa7OV5EON6lKZaAW-1-8" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;b&gt;Pessoa&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;- nome: string&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ get_nome(): string&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="420" y="140" width="160" height="90" as="geometry"/>
</mxCell>
<mxCell id="1wNa7OV5EON6lKZaAW-1-9" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;b&gt;Alien&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;# qntde_dedos: List&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="300" width="160" height="60" as="geometry"/>
</mxCell>
<mxCell id="1wNa7OV5EON6lKZaAW-1-11" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;b&gt;Animal&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;# andar(): void&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="390" y="360" width="160" height="90" as="geometry"/>
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>
<!doctype html>
<head><title>Test</title>
<meta charset=utf-8> </head>
<body>
<h1>Generate Code</h1>
<form method="POST" enctype="multipart/form-data" action="/upload">
<input type="file" name="file" multiple="">
<button> <a href="/submit/">Submit</a></button>
</form>
<h1>View Code</h1>
<button> <a href="/view/">Click me</a></button>
</body>
\ No newline at end of file
<!doctype html>
<html>
<head>
<title>Code</title>
</head>
<body>
<h1>Code</h1>
<div id="content">
{{details|safe }}
</div>
</body>
</html>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<mxfile host="www.draw.io" modified="2019-12-17T14:16:11.947Z" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0" etag="_5Xtbm0DHwJIwc00ywYI" version="12.4.2" type="device" pages="1">
<diagram id="AbfsHDoHPodMjdIZsk2k" name="Page-1">
<mxGraphModel dx="1422" dy="791" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="T5OoOEsfuNDpL02fCPJh-1" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;b&gt;Context&lt;/b&gt;&lt;br&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ strategy: Strategy&lt;br&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ doSomeBusinessLogic(): void&lt;br&gt;&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="20" y="340" width="210" height="100" as="geometry"/>
</mxCell>
<mxCell id="T5OoOEsfuNDpL02fCPJh-3" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;i&gt;&amp;lt;&amp;lt;Interface&amp;gt;&amp;gt;&lt;/i&gt;&lt;br&gt;&lt;b&gt;Strategy&lt;/b&gt;&lt;br&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ doAlgorithm(data: ArrayList&amp;lt;String&amp;gt;): ArrayList&amp;lt;String&amp;gt;&lt;br&gt;&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="300" y="345" width="320" height="90" as="geometry"/>
</mxCell>
<mxCell id="T5OoOEsfuNDpL02fCPJh-5" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;b&gt;ConcreteStrategyA&lt;/b&gt;&lt;br&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ doAlgorithm(data: ArrayList&amp;lt;String&amp;gt;): ArrayList&amp;lt;String&amp;gt;&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="130" y="536" width="320" height="64" as="geometry"/>
</mxCell>
<mxCell id="T5OoOEsfuNDpL02fCPJh-6" value="" style="endArrow=block;dashed=1;endFill=0;endSize=12;html=1;exitX=0.5;exitY=0;exitDx=0;exitDy=0;entryX=0.5;entryY=1;entryDx=0;entryDy=0;" edge="1" parent="1" source="T5OoOEsfuNDpL02fCPJh-5" target="T5OoOEsfuNDpL02fCPJh-3">
<mxGeometry width="160" relative="1" as="geometry">
<mxPoint x="210" y="550" as="sourcePoint"/>
<mxPoint x="370" y="550" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="T5OoOEsfuNDpL02fCPJh-7" value="&lt;p style=&quot;margin: 0px ; margin-top: 4px ; text-align: center&quot;&gt;&lt;b&gt;ConcreteStrategyB&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;&gt;&lt;p style=&quot;margin: 0px ; margin-left: 4px&quot;&gt;+ doAlgorithm(data: ArrayList&amp;lt;String&amp;gt;): ArrayList&amp;lt;String&amp;gt;&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=12;fontFamily=Helvetica;html=1;" vertex="1" parent="1">
<mxGeometry x="470" y="536" width="320" height="64" as="geometry"/>
</mxCell>
<mxCell id="T5OoOEsfuNDpL02fCPJh-8" value="" style="endArrow=block;dashed=1;endFill=0;endSize=12;html=1;exitX=0.5;exitY=0;exitDx=0;exitDy=0;entryX=0.5;entryY=1;entryDx=0;entryDy=0;" edge="1" parent="1" source="T5OoOEsfuNDpL02fCPJh-7" target="T5OoOEsfuNDpL02fCPJh-3">
<mxGeometry width="160" relative="1" as="geometry">
<mxPoint x="290" y="546" as="sourcePoint"/>
<mxPoint x="470" y="440" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="T5OoOEsfuNDpL02fCPJh-10" value="" style="endArrow=open;endFill=1;endSize=12;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;exitX=1;exitY=0.5;exitDx=0;exitDy=0;" edge="1" parent="1" source="T5OoOEsfuNDpL02fCPJh-1" target="T5OoOEsfuNDpL02fCPJh-3">
<mxGeometry width="160" relative="1" as="geometry">
<mxPoint x="30" y="630" as="sourcePoint"/>
<mxPoint x="190" y="630" as="targetPoint"/>
</mxGeometry>
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>
import java.util.*;
public class Dog {
public String name;
private int age;
public void bark() {
throw new UnsupportedOperationException();
}
private bool growUp(int byAge) {
throw new UnsupportedOperationException();
}
}
\ No newline at end of file
import java.util.*;
public class Orc extends Monster implements IWalk, IAttack {
public void attack(int damage, Entity entity, Bonus bonus) {
throw new UnsupportedOperationException();
}
protected static void cry() {
throw new UnsupportedOperationException();
}
}
\ No newline at end of file
from abc import ABC, abstractmethod
class Example(ABC):
@abstractmethod
def do(self):
pass
from abc import ABC, abstractmethod
from i_foo import IFoo
class Example(ABC, IFoo):
@abstractmethod
def foo(self, a, b):
pass
@abstractmethod
def do(self):
pass
class Dog():
def __init__(self, name, age):
self.name = name
self.__age = age
def bark(self):
pass
def __grow_up(self, by_age):
pass
from monster import Monster
from i_walk import IWalk
from i_attack import IAttack
class Orc(Monster, IWalk, IAttack):
def __init__(self):
pass
def attack(self, damage, entity, bonus):
pass
@staticmethod
def _cry():
pass
from abc import ABC, abstractmethod
from i_do_many_things import IDoManyThings
class WeirdGodClass(IDoManyThings):
def __init__(self, mail_reader, configs, network_adapter, test_runner):
self.mail_reader = mail_reader
self.__configs = configs
self.network_adapter = network_adapter
self._test_runner = test_runner
def initialize(self):
pass
@abstractmethod
def initialize_2(self):
pass
@staticmethod
def _do_things(how_much, flag1, flag2):
pass
def __no_one_will_ever_use_this(self, trash, trash_can):
pass
from abc import ABC, abstractmethod
class Test4():
def __init__(self, m):
self.m = m
@abstractmethod
def v(self):
pass
from src.dataToCode.dataClasses.attribute import Attribute
import pytest
from src.dataToCode.dataClasses.visibility import Visibility
testdata = [
(["a", "int", Visibility.public], ["b", "float", Visibility.private], False),
(["a", "int", Visibility.public], ["b", "float", Visibility.public], False),
(["a", "int", Visibility.public], ["b", "int", Visibility.private], False),
(["a", "int", Visibility.public], ["b", "int", Visibility.public], False),
(["a", "int", Visibility.public], ["a", "float", Visibility.private], False),
(["a", "int", Visibility.public], ["a", "float", Visibility.public], False),
(["a", "int", Visibility.public], ["a", "int", Visibility.private], False),
(["a", "int", Visibility.public], ["a", "int", Visibility.public], True),
]
@pytest.mark.parametrize("a,b,expected", testdata)
def test_attribute_equal(a, b, expected):
a = Attribute(a[0], a[1], a[2])
b = Attribute(b[0], b[1], b[2])
output = (a == b)
assert output == expected
from src.dataToCode.dataClasses.attribute import Attribute
import pytest
from src.dataToCode.dataClasses.visibility import Visibility
from src.dataToCode.dataClasses.method import Method
from src.dataToCode.dataClasses.classData import ClassData
def test_class_equal():
method1 = Method("a")
method2 = Method("a")
a = ClassData("a", methods=[method1])
b = ClassData("a", methods=[method2])
output = a==b
assert output == True
def test_class_data_not_equal_name():
method1 = Method("a")
method2 = Method("a")
a = ClassData("a", methods=[method1])
b = ClassData("b", methods=[method2])
output = a==b
assert output == False
def test_class_data_diffent_method_number():
method1 = Method("a")
method2 = Method("a")
method3 = Method("b")
a = ClassData("a", methods=[method1])
b = ClassData("a", methods=[method2, method3])
output = a==b
assert output == False
def test_class_data_equal_method():
method1 = Method("a")
method2 = Method("a")
method3 = Method("b")
method4 = Method("b")
a = ClassData("a", methods=[method1, method4])
b = ClassData("a", methods=[method2, method3])
output = a==b
assert output == True
def test_class_data_not_equal_method():
method1 = Method("a")
method2 = Method("a")
method3 = Method("b")
method4 = Method("c")
a = ClassData("a", methods=[method1, method4])
b = ClassData("a", methods=[method2, method3])
output = a==b
assert output == False
def test_class_data_methods_unordered():
method1 = Method("a")
method2 = Method("a")
method3 = Method("b")
method4 = Method("b")
a = ClassData("a", methods=[method1, method4])
b = ClassData("a", methods=[method3, method2])
output = a==b
assert output == False
from src.dataToCode.dataClasses.attribute import Attribute
import pytest
from src.dataToCode.dataClasses.visibility import Visibility
from src.dataToCode.dataClasses.method import Method
from src.dataToCode.dataClasses.interface import Interface
def test_interface_equal():
method1 = Method("a")
method2 = Method("a")
a = Interface("a", methods=[method1])
b = Interface("a", methods=[method2])
output = a==b
assert output == True
def test_interface_not_equal_name():
method1 = Method("a")
method2 = Method("a")
a = Interface("a", methods=[method1])
b = Interface("b", methods=[method2])
output = a==b
assert output == False
def test_interface_diffent_method_number():
method1 = Method("a")
method2 = Method("a")
method3 = Method("b")
a = Interface("a", methods=[method1])
b = Interface("a", methods=[method2, method3])
output = a==b
assert output == False
def test_interface_equal_method():
method1 = Method("a")
method2 = Method("a")
method3 = Method("b")
method4 = Method("b")
a = Interface("a", methods=[method1, method4])
b = Interface("a", methods=[method2, method3])
output = a==b
assert output == True
def test_interface_not_equal_method():
method1 = Method("a")
method2 = Method("a")
method3 = Method("b")
method4 = Method("c")
a = Interface("a", methods=[method1, method4])
b = Interface("a", methods=[method2, method3])
output = a==b
assert output == False
def test_interface_methods_unordered():
method1 = Method("a")
method2 = Method("a")
method3 = Method("b")
method4 = Method("b")
a = Interface("a", methods=[method1, method4])
b = Interface("a", methods=[method3, method2])
output = a==b
assert output == False
from src.dataToCode.dataClasses.attribute import Attribute
import pytest
from src.dataToCode.dataClasses.visibility import Visibility
from src.dataToCode.dataClasses.method import Method
def test_method_equal():
a = Method("a")
b = Method("a")
output = (a == b)
assert output == True
def test_method_not_equal_name():
a = Method("a")
b = Method("b")
output = (a == b)
assert output == False
def test_method_diffent_param_number():
a = Method("a")
parameter = Attribute("a", "int")
b = Method("a", parameters=[parameter])
output = (a == b)
assert output == False
def test_method_equal_param():
parameter1 = Attribute("a", "int")
parameter2 = Attribute("a", "int")
a = Method("a", parameters=[parameter1])
b = Method("a", parameters=[parameter2])
output = (a == b)
assert output == True
def test_method_not_equal_param():
parameter1 = Attribute("b", "int")
parameter2 = Attribute("a", "int")
a = Method("a", parameters=[parameter1])
b = Method("a", parameters=[parameter2])
output = (a == b)
assert output == False
def test_method_equal_params():
parameter1 = Attribute("a", "int")
parameter2 = Attribute("a", "int")
parameter3 = Attribute("b", "int")
parameter4 = Attribute("b", "int")
a = Method("a", parameters=[parameter1, parameter3])
b = Method("a", parameters=[parameter2, parameter4])
output = (a == b)
assert output == True
def test_method_not_equal_params():
parameter1 = Attribute("a", "int")
parameter2 = Attribute("a", "int")
parameter3 = Attribute("b", "int")
parameter4 = Attribute("c", "int")
a = Method("a", parameters=[parameter1, parameter3])
b = Method("a", parameters=[parameter2, parameter4])
output = (a == b)
assert output == False
def test_method_params_unordered():
parameter1 = Attribute("a", "int")
parameter2 = Attribute("a", "int")
parameter3 = Attribute("b", "int")
parameter4 = Attribute("b", "int")
a = Method("a", parameters=[parameter1, parameter3])
b = Method("a", parameters=[parameter4, parameter2])
output = (a == b)
assert output == False
import pytest
from src.dataToCode.languages.ToJava.inheritanceToJava import InheritanceToJava
from src.dataToCode.dataClasses.classData import ClassData
def test_no_inheritance_equals_empty_string():
assert InheritanceToJava([]).get_formatted() == ''
@pytest.mark.parametrize("inheritance_name", ["name", "Car", "generic_class",
"long_long_long_long_long_long_long"])
def test_single_inheritance_with_letters_only_and_no_space(inheritance_name):
inheritance = ClassData(inheritance_name)
inheritance_to_code = InheritanceToJava([inheritance])
assert inheritance_to_code.get_formatted() == ' extends ' + inheritance_name
@pytest.mark.parametrize("name_one, name_two", [("Client", "Father"),
("generic_class", "not_too_long")])
def test_double_inheritance_with_letters_only_and_no_space(name_one, name_two):
inheritance_one = ClassData(name_one)
inheritance_two = ClassData(name_two)
inheritance_to_code = InheritanceToJava([inheritance_one, inheritance_two])
assert inheritance_to_code.get_formatted() == ' extends ' + name_one + ", " + name_two
from src.dataToCode.dataClasses.interface import Interface
from src.dataToCode.languages.ToJava.interfaceToJava import InterfaceToJava
from src.dataToCode.dataClasses.method import Method
def test_convert_interface():
method = Method("example")
interface = Interface("interface_example", [method])
interface_java = InterfaceToJava(interface)
output = interface_java.convert()
expected = "import java.util.*;\n\npublic interface interface_example {\n\n\tpublic void example();\n}"
assert output == expected
def test_convert_interface_wit_implement_interface():
method = Method("example")
interface1 = Interface("interface1", [method])
interface2 = Interface("interface2", [method], interfaces=[interface1])
interface_java2 = InterfaceToJava(interface2)
output = interface_java2.convert()
expected = (f"import java.util.*;\n\npublic interface interface2 "
f"implements interface1 {{\n\n\tpublic void example();\n}}")
assert output == expected
def test_convert_interface_wit_implement_interfacee():
method = Method("example")
interface1 = Interface("interface1", [method])
interface3 = Interface("interface3", [method])
interface2 = Interface("interface2", [method], interfaces=[interface1,
interface3])
interface_java2 = InterfaceToJava(interface2)
output = interface_java2.convert()
expected = (f"import java.util.*;\n\npublic interface interface2 "
f"implements interface1, interface3 {{\n\n\tpublic void example();\n}}")
assert output == expected
import pytest
from src.dataToCode.languages.ToJava.methodToJava import MethodToJava
from src.dataToCode.dataClasses.method import Method
from src.dataToCode.dataClasses.visibility import Visibility
from src.dataToCode.dataClasses.attribute import Attribute
from src.dataToCode.dataClasses.modifier import Modifier
from typing import List
def test_formatted_method():
method = Method("example")
method_to_java = MethodToJava([method], True)
assert method_to_java.get_formatted_methods() == "\tpublic void example();"
def test_formatted_methods():
method1 = Method("example")
method2 = Method("example2")
method_to_java = MethodToJava([method1, method2], True)
assert method_to_java.get_formatted_methods() == (f"\tpublic void example();"
f"\n\n\tpublic void"
f" example2();")
visibility_data = [
(Visibility.public, "\tpublic void example();"),
(Visibility.private, "\tprivate void example();"),
(Visibility.package, "\tpackage void example();"),
(Visibility.protected, "\tprotected void example();"),
]
@pytest.mark.parametrize("visibility, expected", visibility_data)
def test_formatted_method_visibility(visibility, expected):
method = Method("example", visibility=visibility)
method_to_java = MethodToJava([method], True)
assert method_to_java.get_formatted_methods() == expected
type_data = [
("int", "\tpublic int example();"),
("float", "\tpublic float example();"),
]
@pytest.mark.parametrize("type_name, expected", type_data)
def test_formatted_method_type(type_name, expected):
method = Method("example", return_type=type_name)
method_to_java = MethodToJava([method], True)
assert method_to_java.get_formatted_methods() == expected
parameter_data = [
([["a", "int"]], "\tpublic void example(int a);"),
([["a", "int"], ["b", "float"]], "\tpublic void example(int a, float b);"),
]
@pytest.mark.parametrize("parameters, expected", parameter_data)
def test_formatted_method_parameters(parameters, expected):
parameter_list: List[Attribute] = []
for parameter in parameters:
name, return_type = parameter
new_parameter = Attribute(name, return_type)
parameter_list.append(new_parameter)
method = Method("example", parameters=parameter_list)
method_to_java = MethodToJava([method], True)
assert method_to_java.get_formatted_methods() == expected
body_data = [
(True, "\tpublic void example();"),
(False, (f"\tpublic void example()"
f" {{\n\t\tthrow new UnsupportedOperationException();\n\t}}")),
]
@pytest.mark.parametrize("is_from_interface, expected", body_data)
def test_formatted_method_body(is_from_interface, expected):
method = Method("example")
method_to_java = MethodToJava([method], is_from_interface)
assert method_to_java.get_formatted_methods() == expected
modifier_data = [
(Modifier.abstract, "\tpublic abstract void example();"),
(Modifier.override, "\t@override\n\tpublic void example();"),
(Modifier.static, "\tpublic static void example();"),
]
@pytest.mark.parametrize("modifier, expected", modifier_data)
def test_formatted_method_modifier(modifier, expected):
method = Method("example", modifier=modifier)
method_to_java = MethodToJava([method], True)
print(method_to_java.get_formatted_methods())
assert method_to_java.get_formatted_methods() == expected
import pytest
from src.dataToCode.languages.ToJava.fileNameToJava import FileNameToJava
from src.dataToCode.dataClasses.classData import ClassData
from src.dataToCode.dataClasses.interface import Interface
from src.dataToCode.dataClasses.method import Method
def test_single_name_class():
class_data = ClassData("Name")
file_name_java = FileNameToJava(class_data)
assert "Name.java" == file_name_java.get_file_name()
def test_single_name_interface():
method = Method("test")
interface_data = Interface("StrongName", methods=[method])
file_name_java = FileNameToJava(interface_data)
assert "StrongName.java" == file_name_java.get_file_name()
import java.util.*;
public class ConcreteStrategyA implements Strategy {
public ArrayList<String> doAlgorithm(ArrayList<String> data) {
throw new UnsupportedOperationException();
}
}
\ No newline at end of file
import java.util.*;
public class ConcreteStrategyB implements Strategy {
public ArrayList<String> doAlgorithm(ArrayList<String> data) {
throw new UnsupportedOperationException();
}
}
\ No newline at end of file
import java.util.*;
public class Context {
public Strategy strategy;
public void doSomeBusinessLogic() {
throw new UnsupportedOperationException();
}
}
\ No newline at end of file
import java.util.*;
public interface Strategy {
public ArrayList<String> doAlgorithm(ArrayList<String> data);
}
\ No newline at end of file
import pytest
import os
import filecmp
import subprocess
from src.dataToCode.dataClasses.attribute import Attribute
from src.dataToCode.dataClasses.classData import ClassData
from src.dataToCode.dataClasses.interface import Interface
from src.dataToCode.dataClasses.method import Method
from src.dataToCode.write_files import write_files
from src.dataToCode.dataClasses.visibility import Visibility
from src.dataToCode.dataClasses.modifier import Modifier
def test_strategy_example_java(tmpdir):
def create_do_algorithm():
attribute = Attribute("data", "ArrayList<String>")
method = Method("doAlgorithm", parameters=[attribute],
return_type="ArrayList<String>")
return method
def create_strategy():
method = create_do_algorithm()
strategy = Interface("Strategy", methods=[method])
return strategy
def create_context():
attribute = Attribute("strategy", "Strategy",
visibility=Visibility.public)
method = Method("doSomeBusinessLogic")
context = ClassData("Context", methods=[method], fields=[attribute])
return context
def create_concrete_a():
method = create_do_algorithm()
strategy = create_strategy()
concrete_a = ClassData("ConcreteStrategyA", methods=[method],
implementations=[strategy])
return concrete_a
def create_concrete_b():
method = create_do_algorithm()
strategy = create_strategy()
concrete_b = ClassData("ConcreteStrategyB", methods=[method],
implementations=[strategy])
return concrete_b
objects = [create_strategy(), create_context(), create_concrete_a(),
create_concrete_b()]
write_files(objects, tmpdir, "java")
files_path = ["Strategy.java", "Context.java", "ConcreteStrategyA.java",
"ConcreteStrategyB.java"]
strategy_path = os.path.abspath(os.path.join(__file__,
"../strategy_example"))
generated_path = [os.path.join(tmpdir, x) for x in files_path]
truth_path = [os.path.join(strategy_path, x) for x in files_path]
for truth_file_path, generated_file_path in zip(truth_path,
generated_path):
print(filecmp.cmp(truth_file_path, generated_file_path))
assert filecmp.cmp(truth_file_path, generated_file_path)
def test_strategy_xml(tmpdir):
main_path = os.path.abspath(os.path.join(__file__,"..", "..", "..", "..", "..", "main.py"))
xml_path = os.path.abspath(os.path.join(__file__,"..", "..", "..", "..", "strategy.xml"))
subprocess.run(["python3", main_path,
f"--xml_file={xml_path}", f"--code_path={tmpdir}",
"--language=java"])
files_path = ["Strategy.java", "Context.java",
"ConcreteStrategyA.java",
"ConcreteStrategyB.java"]
strategy_path = os.path.abspath(os.path.join(__file__,
"../strategy_example"))
generated_path = [os.path.join(tmpdir, x) for x in files_path]
truth_path = [os.path.join(strategy_path, x) for x in files_path]
for truth_file_path, generated_file_path in zip(truth_path,
generated_path):
assert filecmp.cmp(truth_file_path, generated_file_path)
def test_ultimate_example_java(tmpdir):
def create_spell():
method = Method("doEffect")
interface = Interface("ISpell", methods=[method])
return interface
def create_food():
method = Method("getNutrients", return_type="String")
interface = Interface("IFood", methods=[method])
return interface
def create_weapon():
name = Attribute("name", "String", visibility=Visibility.public)
age = Attribute("age", "int", visibility=Visibility.private)
attribute = Attribute("attribute", "Attribute",
visibility=Visibility.protected)
getAttribute = Method("getAttribute", return_type="Attribute")
setAttribute = Method("setAttribute", return_type="void",
parameters=[attribute])
weapon = ClassData("Weapon", methods=[getAttribute, setAttribute],
fields=[name, age, attribute])
return weapon
def create_attribute():
field1 = Attribute("value", "float", visibility=Visibility.public)
field2 = Attribute("multiplier", "float", visibility=Visibility.public)
attribute = ClassData("Attribute", fields=[field1, field2])
return attribute
def create_walk():
method = Method("walk")
interface = Interface("IWalk", methods=[method])
return interface
def create_attack():
damage = Attribute("damage", "int", visibility=Visibility.public)
method = Method("attack", parameters=[damage])
interface = Interface("IAttack", methods=[method])
return interface
def create_orc():
name = Attribute("name", "String", visibility=Visibility.public)
age = Attribute("age", "int", visibility=Visibility.private)
weapon = Attribute("weapon", "Weapon", visibility=Visibility.private)
damage = Attribute("damage", "int", visibility=Visibility.public)
hours = Attribute("hours", "int", visibility=Visibility.public)
walk = create_walk()
attack_interface = create_attack()
attack_method = Method("attack", parameters=[damage])
sleep = Method("sleep", parameters=[hours],
visibility=Visibility.private)
walk_method = Method("walk", parameters=[])
orc = ClassData("Orc", methods=[attack_method, walk_method, sleep],
fields=[name, age, weapon],
implementations=[attack_interface, walk])
return orc
def create_high_orc():
damage = Attribute("damage", "int", visibility=Visibility.public)
hours = Attribute("hours", "int", visibility=Visibility.public)
spell = Attribute("spell", "ISpell", visibility=Visibility.protected)
attack = Method("attack", parameters=[damage],
modifier=Modifier.override)
sleep = Method("sleep", parameters=[hours],
visibility=Visibility.private,
modifier=Modifier.override)
orc = create_orc()
high_orc = ClassData("HighOrc", methods=[attack, sleep],
fields=[spell], inheritances=[orc])
return high_orc
def create_fat_orc():
food = Attribute("food", "IFood", visibility=Visibility.public)
eat = Method("eat", parameters=[food])
orc = create_orc()
fat_orc = ClassData("FatOrc", methods=[eat],
inheritances=[orc])
return fat_orc
def create_obese_orc():
food = Attribute("food", "IFood", visibility=Visibility.public)
heart_attack = Attribute("heartAttackChance", "int",
visibility=Visibility.public)
eat = Method("eat", parameters=[food], modifier=Modifier.override)
fat_orc = create_fat_orc()
obese_orc = ClassData("ObeseOrc", methods=[eat],
fields=[heart_attack], inheritances=[fat_orc])
return obese_orc
objects = [create_spell(), create_food(), create_weapon(),
create_attribute(), create_attack(), create_walk(),
create_orc(), create_high_orc(), create_fat_orc(),
create_obese_orc()]
write_files(objects, tmpdir, "java")
ultimate_path = os.path.abspath(os.path.join(__file__,
"../ultimate_example"))
all_files_path = os.listdir(ultimate_path)
files_path = []
for file_path in all_files_path:
if file_path.endswith(".java"):
files_path.append(file_path)
generated_path = [os.path.join(tmpdir, x) for x in files_path]
truth_path = [os.path.join(ultimate_path, x) for x in files_path]
for truth_file_path, generated_file_path in zip(truth_path,
generated_path):
assert filecmp.cmp(truth_file_path, generated_file_path)
import java.util.*;
public class Attribute {
public float value;
public float multiplier;
}
\ No newline at end of file
import java.util.*;
public class FatOrc extends Orc {
public void eat(IFood food) {
throw new UnsupportedOperationException();
}
}
\ No newline at end of file
import java.util.*;
public class HighOrc extends Orc {
protected ISpell spell;
@override
public void attack(int damage) {
throw new UnsupportedOperationException();
}
@override
private void sleep(int hours) {
throw new UnsupportedOperationException();
}
}
\ No newline at end of file
import java.util.*;
public interface IAttack {
public void attack(int damage);
}
\ No newline at end of file
import java.util.*;
public interface IFood {
public String getNutrients();
}
\ No newline at end of file
import java.util.*;
public interface ISpell {
public void doEffect();
}
\ No newline at end of file
import java.util.*;
public interface IWalk {
public void walk();
}
\ No newline at end of file
import java.util.*;
public class ObeseOrc extends FatOrc {
public int heartAttackChance;
@override
public void eat(IFood food) {
throw new UnsupportedOperationException();
}
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment