-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
224 lines (182 loc) · 7.01 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
from flask import Flask, render_template, request, jsonify, send_file, send_from_directory
from flask_socketio import SocketIO, emit
import subprocess
import webbrowser
import os
import select
import json
import re
app = Flask(__name__)
socketio = SocketIO(app)
process = None
@app.route('/')
def index():
return render_template('index.html')
@app.route('/help')
def help():
return render_template('help.html')
@app.route('/test_report.html')
def get_test_report():
return send_file('work-dir/test_report.html')
@app.route('/empty.html')
def get_empty():
return send_file('templates/empty.html')
@app.route('/progress.html')
def get_progress():
return send_file('templates/progress.html')
@app.route('/icons/<path:filename>')
def get_icon(filename):
return send_from_directory('static/icon', filename)
@socketio.on('run_java')
def handle_run_java(json):
"""
pro spusteni konfigurace primo na java nastroji. nepterzite ukazuje vystup logovani a po jejim dokonceni je mozne zobrazit vystupni report
"""
global process
if process and process.poll() is None:
emit('output', {'data': 'Process is already running.'})
return
yaml_content = json.get('yaml_content')
if not yaml_content:
emit('finished', {'status': 'error',
'message': 'Missing YAML content!'})
return
with open('tmp-config.yaml', 'w') as yaml_file:
yaml_file.write(yaml_content)
try:
process = subprocess.Popen(['java', '-jar', '../NATT.jar', '-c', '../tmp-config.yaml'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, cwd='./work-dir')
emit('output', {
'data': '<span class="green-text">NATT testing tool is running now</span>'})
streams = [process.stdout, process.stderr]
while True:
ready_streams, _, _ = select.select(streams, [], [])
for stream in ready_streams:
output = stream.readline()
if output:
if stream is process.stdout:
emit('output', {'data': output.rstrip()})
else:
emit('output', {
'data': '<span class="red-text">' + output.rstrip() + '</span>'})
if process.poll() is not None:
break
exit_code = process.wait()
if exit_code == 0:
emit('finished', {'status': 'success'})
else:
emit('finished', {
'status': 'error', 'message': f'Program ends with status code: {exit_code}'})
except Exception as e:
if process is not None:
emit('finished', {'status': 'error', 'message': str(e)})
finally:
if process:
process.stdout.close()
process.stderr.close()
process.terminate()
@socketio.on('stop_java')
def handle_stop_java():
"""
zastaveni spustene aplikace
"""
global process
if process:
process.terminate() # posle signal SIGTERM
process = None
emit('stopped', {
'message': 'The testing process has been terminated by editor ...'})
@socketio.on('validate')
def handle_validation(json):
yaml_content = json.get('yaml_content')
if not yaml_content:
emit('validate-response', {'status': 'error',
'message': 'Missing YAML content!'})
return
with open('tmp-config.yaml', 'w') as yaml_file:
yaml_file.write(yaml_content)
try:
val_process = subprocess.Popen(['java', '-jar', '../NATT.jar', '-c', '../tmp-config.yaml', '-v'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, cwd='./work-dir')
stdout, stderr = val_process.communicate()
if val_process.returncode == 0:
emit('validate-response', {'status': 'success',
'message': 'Configuration is valid'})
else:
emit('validate-response', {'status': 'error', 'message': stderr})
except Exception as e:
emit('validate-response', {'status': 'error', 'message': str(e)})
finally:
if process:
process.stdout.close()
process.stderr.close()
process.terminate()
@app.route('/get-snippets', methods=['POST'])
def get_snippets():
try:
# Define the path to the NATT.jar and working directory
jar_path = '../NATT.jar'
work_dir = './work-dir'
# Execute the command to run NATT.jar and capture the output
result = subprocess.run(
['java', '-jar', jar_path, '-kd'],
cwd=work_dir,
text=True,
capture_output=True
)
# Check if the command was successful
if result.returncode != 0:
return jsonify({"error": f"Error executing command: {result.stderr}"}), 500
# Extract the keyword list from the command output
keyword_list_match = re.search(
r'Documentation for registered keywords:\s*\[(.*)\]', result.stdout, re.S)
if not keyword_list_match:
return jsonify({"error": "Failed to find the keyword list in the output."}), 500
keyword_list_string = f'[{keyword_list_match.group(1)}]'
# Parse the keyword list JSON
try:
keyword_list = json.loads(keyword_list_string)
except json.JSONDecodeError as parse_error:
return jsonify({"error": f"Error parsing JSON: {str(parse_error)}"}), 500
# Create the keyword snippets
keyword_snippets = []
for keyword in keyword_list:
snippet = generate_snippet(keyword=keyword)
keyword_snippets.append(snippet)
# Return the generated snippets as JSON
return jsonify({"snippets": keyword_snippets})
except Exception as e:
return jsonify({"error": str(e)}), 500
def get_example_value(param_type):
return {
"STRING": '"example"',
"LONG": "100",
"DOUBLE": "10.5",
"BOOLEAN": "true",
"LIST": "[]"
}.get(param_type, "example value")
def generate_snippet(keyword):
has_single_parameter = len(keyword["parameters"]) == 1
snippet = {
"caption": keyword["name"],
"snippet": (
f'{keyword["name"]}: ' + (
get_example_value(keyword["types"][0])
if has_single_parameter
else '\n' + '\n'.join([
f' {param}: {get_example_value(keyword["types"][i])}'
for i, param in enumerate(keyword["parameters"])
])
)
),
"meta": keyword["kwGroup"],
"description": keyword["description"],
"params": ",".join(f"{param}:{type_}" for param, type_ in zip(keyword["parameters"], keyword["types"]))
}
return snippet
def showPage():
webbrowser.open_new("http://127.0.0.1:5000")
if __name__ == '__main__':
if not os.environ.get("WERKZEUG_RUN_MAIN"):
webbrowser.open_new('http://127.0.0.1:2000/')
app.run(host="127.0.0.1", port=2000)