summaryrefslogtreecommitdiffstats
path: root/testing-scheduler/server/src/rest/router.py
blob: b9cbd9285c57a9a35e63d275abf39ac8c54ed9a5 (plain)
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
##############################################################################
# Copyright (c) 2018 HUAWEI TECHNOLOGIES CO.,LTD and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
##############################################################################

from flask import Flask
from flask import jsonify
from flask import request
from flask_cors import CORS
import os
import json
import time
import pyaml
import yaml
import traceback

import src.test_parser as test_parser


BASE_DIR = os.path.abspath(os.path.dirname(__file__))
TESTSUITE_DIR = os.path.join(BASE_DIR, "..", "..", "test", "test_case")
SERVICE_DIR = os.path.join(BASE_DIR, "..", "env", "service")
CONTEXT_FILE_DIR = os.path.join(BASE_DIR, "..", "env", "context",
                                "context.yaml")
app = Flask(__name__)
CORS(app)


###############
# 1. EXECUTE API
###########################################################################
@app.route("/")
def hello():
    return "Hello, World! This is a greet from parser." + SERVICE_DIR


@app.route("/execute/testcase", methods=['POST'])
def runTestcase():
    suiteName = request.values.get('suiteName')
    caseName = request.values.get('caseName')
    try:
        casePath = os.path.join(TESTSUITE_DIR, suiteName, caseName)
        if os.path.exists(casePath):
            workflowId = test_parser.parse(casePath)
            if workflowId is None or workflowId == '':
                return jsonify({"code": 500, "error": "Server Error."})
            return jsonify({"code": 200, "result": {"workflowId": workflowId}})
        else:
            return jsonify({"code": 300, "error": "no such test case:  %s" %
                           (os.path.join(suiteName, caseName))})
    except BaseException, e:
        return returnServerError(e)


@app.route("/story-content")
def getStoryContent():
    try:
        story_name = request.args['story']
        service_name = request.args['service']
        storyFileDir = os.path.join("/tmp", "generate_workflow.json")
        with open(storyFileDir, "r") as f:
            storyContent = f.read()
    except BaseException, e:
        return returnServerError(e)

    result = {"code": 200, "result":
              {"service": service_name, "story": story_name,
               "content": storyContent}}
    return jsonify(result)


###############
# 2. TESTCASE CRUD
###########################################################################
@app.route("/testsuite/list")
def getAllSuite():
    res = []
    id = 1
    try:
        for fileName in os.listdir(TESTSUITE_DIR):
            suiteInfo = {}
            suiteInfo["id"] = id
            suiteInfo["testsuite"] = fileName
            res.append(suiteInfo)
            id = id + 1
    except BaseException, e:
        print e
        app.logger.error(traceback.format_exc())
        return jsonify({"code": 500, "error": "Server error"})

    return jsonify({"code": 200, "result": res})


@app.route("/testsuite/content")
def getSuiteContent():
    res = []
    id = 1
    try:
        suiteName = request.values.get("suiteName")
        exSuitePath = os.path.join(TESTSUITE_DIR, suiteName)
        if os.path.exists(exSuitePath):
            for fileName in os.listdir(exSuitePath):
                tcInfo = {}
                tcInfo["id"] = id
                tcInfo["testcase"] = fileName
                res.append(tcInfo)
                id = id + 1
        else:
            return jsonify({"code": 300, "error": "no such test suite!"})
    except BaseException, e:
        print e
        app.logger.error(traceback.format_exc())
        return jsonify({"code": 500, "error": "Server error"})

    return jsonify({"code": 200, "result": res})


@app.route("/testcase/content")
def getTCContent():
    res = ""
    editorRes = ""
    try:
        suiteName = request.values.get("suiteName")
        caseName = request.values.get("caseName")
        casePath = os.path.join(suiteName, caseName)
        casePath = os.path.join(TESTSUITE_DIR, casePath)
        if os.path.exists(casePath):
            with open(casePath, "r") as f:
                fileContent = f.read()
            res = fileContent
            editorRes = test_parser.getWebTestcase(yaml.load(res))
        else:
            return jsonify({"code": 300, "error": "no such file!"})
    except BaseException, e:
        print e
        app.logger.error(traceback.format_exc())
        return jsonify({"code": 500, "error": "Server error"})

    return jsonify({"code": 200, "result":
                    {"content": res, "editorContent": editorRes}})


@app.route("/testsuite/new", methods=['POST'])
def addNewSuite():
    try:
        suiteName = request.values.get("suiteName")
        for fileName in os.listdir(TESTSUITE_DIR):
            if fileName == suiteName:
                return jsonify({"code": 300,
                                "error": "testsuite already exists!"})
        testSuitePath = os.path.join(TESTSUITE_DIR, suiteName)
        os.mkdir(testSuitePath)
    except BaseException, e:
        return returnServerError(e)

    return jsonify({"code": 200, "result": "ok"})


@app.route("/testsuite/delete", methods=['POST'])
def deleteSuite():
    try:
        suiteName = request.values.get("suiteName")
        for fileName in os.listdir(TESTSUITE_DIR):
            if fileName == suiteName:
                testSuitePath = os.path.join(TESTSUITE_DIR, fileName)
                del_file(testSuitePath)
                os.rmdir(testSuitePath)
                return jsonify({"code": 200, "result": "ok"})
    except BaseException, e:
        return returnServerError(e)

    return jsonify({"code": 300, "error": "no such testsuite!"})


def del_file(path):
    for i in os.listdir(path):
        path_file = os.path.join(path, i)
        if os.path.isfile(path_file):
            os.remove(path_file)
        else:
            del_file(path_file)


@app.route("/testcase/new", methods=['POST'])
def createTestcase():
    try:
        suiteName = request.values.get("suiteName")
        caseName = request.values.get("caseName")
        exSuitePath = os.path.join(TESTSUITE_DIR, suiteName)
        if os.path.exists(exSuitePath):
            for fileName in os.listdir(exSuitePath):
                if fileName == caseName:
                    return jsonify({"code": 301,
                                    "error": "testcase already exists!"})
            casePath = os.path.join(exSuitePath, caseName)
            with open(casePath, "w") as f:
                # the next line is a placeholder.
                print f
        else:
            return jsonify({"code": 300, "error": "no such test suite!"})
    except BaseException, e:
        return returnServerError(e)

    return jsonify({"code": 200, "result": "ok"})


@app.route("/testcase/delete", methods=['POST'])
def deleteTestcase():
    try:
        suiteName = request.values.get("suiteName")
        caseName = request.values.get("caseName")
        exSuitePath = os.path.join(TESTSUITE_DIR, suiteName)
        if os.path.exists(exSuitePath):
            for fileName in os.listdir(exSuitePath):
                if fileName == caseName:
                    casePath = os.path.join(exSuitePath, caseName)
                    os.remove(casePath)
                    return jsonify({"code": 200, "result": "ok"})
            return jsonify({"code": 301, "error": "no such test case!"})
        else:
            return jsonify({"code": 300, "error": "no such test suite!"})
    except BaseException, e:
        return returnServerError(e)


@app.route("/testcase/save", methods=["POST"])
def saveTCContent():
    try:
        suiteName = request.values.get("suiteName")
        caseName = request.values.get("caseName")
        stepList = json.loads(request.values.get("stepList"))
        subflowList = json.loads(request.values.get("subflowList"))
        mainOrdersList = json.loads(request.values.get("mainOrdersList"))
        jsonObj = {"stepList": stepList, "subflowList": subflowList,
                   "mainOrdersList": mainOrdersList}
        parseData = test_parser.parseWebTestcase(jsonObj)

        casePath = os.path.join(suiteName, caseName)
        casePath = os.path.join(TESTSUITE_DIR, casePath)
        if os.path.exists(casePath):
            with open(casePath, "w") as f:
                pyaml.dump(parseData, f, safe=True)
        else:
            return jsonify({"code": 300, "error": "no such file!"})
    except BaseException, e:
        return returnServerError(e)

    return jsonify({"code": 200, "result": "save success"})


###############
# 3.1 API FOR SERVICE
############################################################
@app.route("/service/list")
def getAllServices():
    res = []
    try:
        for fileName in os.listdir(SERVICE_DIR):
            serviceName = os.path.splitext(fileName)[0]
            res.append(serviceName)
    except BaseException, e:
        return returnServerError(e)

    return jsonify({"code": 200, "result": res})


@app.route("/service/content")
def getServiceContent():
    res = {}
    try:
        serviceName = request.values.get("serviceName")
        for fileName in os.listdir(SERVICE_DIR):
            if serviceName == os.path.splitext(fileName)[0]:
                res["actions"] = []
                filePath = os.path.join(SERVICE_DIR, fileName)
                with open(filePath, "r") as f:
                    content = yaml.load(f)
                    apisArr = content[serviceName]['apis']
                    for i in range(len(apisArr)):
                        apisArr[i].pop("method")
                        apisArr[i].pop("baseuri")
                    res["actions"] = apisArr
    except BaseException, e:
        return returnServerError(e)

    if res == {}:
        return jsonify({"code": 300, "error": "no such service!"})

    return jsonify({"code": 200, "result": res})


def paramTransform(paramDict):
    res = []
    for (key, value) in paramDict.items():
        paramJson = {}
        paramJson["name"] = key
        paramJson["description"] = value["help"]
        if "params" in value:
            paramJson["params"] = paramTransform(value["params"])
        res.append(paramJson)
    return res


@app.route("/service/action_response")
def actionResponse():
    res = {}
    try:
        serviceName = request.values.get("serviceName")
        actionName = request.values.get("actionName")
        for fileName in os.listdir(SERVICE_DIR):
            if serviceName == os.path.splitext(fileName)[0]:
                res["responseParams"] = []
                filePath = os.path.join(SERVICE_DIR, fileName)
                with open(filePath, "r") as f:
                    content = yaml.load(f)
                    apisArr = content[serviceName]['apis']
                for i in range(len(apisArr)):
                    if actionName == apisArr[i]['name'] and (
                       "response" in apisArr[i]):
                        res["responseParams"] = apisArr[i]["response"]
    except BaseException, e:
        return returnServerError(e)
    if res == {}:
        return jsonify({"code": 300, "error": "no such service!"})
    return jsonify({"code": 200, "result": res})


###############
# 3.2 API FOR ENVIRONMENT SERVICE AND CONTEXT
###########################################################################
@app.route('/env/getAllServices')
def getAllService():
    res = []
    id = 1
    try:
        for fileName in os.listdir(SERVICE_DIR):
            item = {}
            item['id'] = id
            item['name'] = os.path.splitext(fileName)[0]
            filePath = os.path.join(SERVICE_DIR, fileName)
            filemt = time.localtime(os.stat(filePath).st_mtime)
            item['time'] = time.strftime("%Y-%m-%d", filemt)
            res.append(item)
            id = id + 1
    except BaseException, e:
        return returnServerError(e)
    return jsonify({"code": 200, "result": res})


@app.route('/env/getService')
def getService():
    try:
        serviceName = request.values.get('serviceName')
        serviceFile = serviceName + '.yaml'
        servicePath = os.path.join(SERVICE_DIR, serviceFile)
        if os.path.exists(servicePath):
            with open(servicePath, "r") as f:
                serviceDict = yaml.load(f)
                serviceDict = serviceDict[serviceName]
            return jsonify({"code": 200, "result": serviceDict})
        else:
            return jsonify({"code": 300, "error": "no such service!"})
    except BaseException, e:
        return returnServerError(e)


@app.route('/env/createService', methods=['POST'])
def createService():
    try:
        name = str(request.values.get('name'))
        ip = str(request.values.get('ip'))
        port = int(request.values.get('port'))
        apis = json.loads(request.values.get('apis'))
        service = {
            name: {
                'ip': ip,
                'port': port,
                'apis': apis
            }
        }
        serviceJson = json.dumps(service, indent=True)
        print serviceJson
        app.logger.debug(service)

        serviceFile = name + '.yaml'
        servicePath = os.path.join(SERVICE_DIR, serviceFile)
        with open(servicePath, 'w') as f:
            pyaml.dump(service, f, safe=True)
    except BaseException, e:
        return returnServerError(e)
    return jsonify({"code": 200, "result": "create success!"})


@app.route('/env/editService', methods=['POST'])
def editService():
    try:
        oldName = str(request.values.get('oldName'))
        name = str(request.values.get('newName'))
        ip = str(request.values.get('ip'))
        port = int(request.values.get('port'))
        apis = json.loads(request.values.get('apis'))
        app.logger.debug(apis)
        service = {
            name: {
                'ip': ip,
                'port': port,
                'apis': apis
            }
        }
        serviceJson = json.dumps(service, indent=True)
        print serviceJson
        app.logger.debug(service)

        for fileName in os.listdir(SERVICE_DIR):
            serviceName = os.path.splitext(fileName)[0]
            if serviceName == oldName:
                filePath = os.path.join(SERVICE_DIR, fileName)
                os.remove(filePath)

        serviceFile = name + '.yaml'
        servicePath = os.path.join(SERVICE_DIR, serviceFile)
        with open(servicePath, 'w') as f:
            pyaml.dump(service, f, safe=True)
    except BaseException, e:
        return returnServerError(e)
    return jsonify({"code": 200, "result": "edit success!"})


@app.route('/env/deleteService', methods=['POST'])
def deleteService():
    try:
        name = str(request.values.get('serviceName'))

        for fileName in os.listdir(SERVICE_DIR):
            serviceName = os.path.splitext(fileName)[0]
            if serviceName == name:
                filePath = os.path.join(SERVICE_DIR, fileName)
                os.remove(filePath)
    except BaseException, e:
        return returnServerError(e)
    return jsonify({"code": 200, "result": "delete success!"})


@app.route('/env/getContext')
def getContext():
    try:
        with open(CONTEXT_FILE_DIR, "r") as f:
            fileContent = f.read()
        res = fileContent
    except BaseException, e:
        return returnServerError(e)
    return jsonify({"code": 200, "result": {"context": res}})


@app.route('/env/editContext', methods=['POST'])
def editContext():
    try:
        context = request.values.get("context")
        test = yaml.load(context)
        print test
        with open(CONTEXT_FILE_DIR, "w") as f:
            f.write(context)
    except yaml.constructor.ConstructorError, e:
        app.logger.error(traceback.format_exc())
        return jsonify({"code": 500, "error":
                        "context content error: not a .yaml file!"})
    except BaseException, e:
        return returnServerError(e)

    return jsonify({"code": 200, "result": "edit context success!"})
###########################################################################


def returnServerError(e, msg="Server Error"):
    print e
    app.logger.error(traceback.format_exc())
    return jsonify({"code": 500, "error": msg})


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5310)