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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
|
##############################################################################
# Copyright (c) 2015 Orange
# guyrodrigue.koffi@orange.com / koffirodrigue@gmail.com
# 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
##############################################################################
import json
from tornado.web import RequestHandler, asynchronous, HTTPError
from tornado import gen
from datetime import datetime, timedelta
from models import TestProject, TestCase, TestResult
from resources.pod_models import Pod
from common.constants import DEFAULT_REPRESENTATION, HTTP_BAD_REQUEST, \
HTTP_NOT_FOUND, HTTP_FORBIDDEN
from common.config import prepare_put_request
from dashboard.dashboard_utils import get_dashboard_cases, \
check_dashboard_ready_project, check_dashboard_ready_case, \
get_dashboard_result
class GenericApiHandler(RequestHandler):
"""
The purpose of this class is to take benefit of inheritance and prepare
a set of common functions for
the handlers
"""
def initialize(self):
""" Prepares the database for the entire class """
self.db = self.settings["db"]
def prepare(self):
if not (self.request.method == "GET"):
if self.request.headers.get("Content-Type") is not None:
if self.request.headers["Content-Type"].startswith(
DEFAULT_REPRESENTATION):
try:
self.json_args = json.loads(self.request.body)
except (ValueError, KeyError, TypeError) as error:
raise HTTPError(HTTP_BAD_REQUEST,
"Bad Json format [{}]".
format(error))
else:
self.json_args = None
def finish_request(self, json_object):
self.write(json.dumps(json_object))
self.set_header("Content-Type", DEFAULT_REPRESENTATION)
self.finish()
class VersionHandler(RequestHandler):
""" Display a message for the API version """
def get(self):
self.write("Collection of test result API, v1")
class PodHandler(GenericApiHandler):
""" Handle the requests about the POD Platforms
HTTP Methdods :
- GET : Get PODS
- POST : Create a pod
- DELETE : DELETE POD
"""
def initialize(self):
""" Prepares the database for the entire class """
super(PodHandler, self).initialize()
@asynchronous
@gen.coroutine
def get(self, pod_name=None):
"""
Get all pods or a single pod
:param pod_id:
"""
get_request = dict()
if pod_name is not None:
get_request["name"] = pod_name
res = []
cursor = self.db.pod.find(get_request)
while (yield cursor.fetch_next):
pod = Pod.pod_from_dict(cursor.next_object())
res.append(pod.format())
meta = dict()
meta["total"] = len(res)
meta["success"] = True if len(res) > 0 else False
answer = dict()
answer["pods"] = res
answer["meta"] = meta
self.finish_request(answer)
@asynchronous
@gen.coroutine
def post(self):
""" Create a POD"""
if self.json_args is None:
raise HTTPError(HTTP_BAD_REQUEST)
query = {"name": self.json_args.get("name")}
# check for existing name in db
mongo_dict = yield self.db.pod.find_one(query)
if mongo_dict is not None:
raise HTTPError(HTTP_FORBIDDEN,
"{} already exists as a pod".format(
self.json_args.get("name")))
pod = Pod.pod_from_dict(self.json_args)
pod.creation_date = datetime.now()
future = self.db.pod.insert(pod.format())
result = yield future
pod._id = result
meta = dict()
meta["success"] = True
meta["uri"] = "/pods/{}".format(pod.name)
answer = dict()
answer["pod"] = pod.format_http()
answer["meta"] = meta
self.finish_request(answer)
@asynchronous
@gen.coroutine
def delete(self, pod_name):
""" Remove a POD
# check for an existing pod to be deleted
mongo_dict = yield self.db.pod.find_one(
{'name': pod_name})
pod = TestProject.pod(mongo_dict)
if pod is None:
raise HTTPError(HTTP_NOT_FOUND,
"{} could not be found as a pod to be deleted"
.format(pod_name))
# just delete it, or maybe save it elsewhere in a future
res = yield self.db.test_projects.remove(
{'name': pod_name})
meta = dict()
meta["success"] = True
meta["deletion-data"] = res
answer = dict()
answer["meta"] = meta
self.finish_request(answer)
"""
pass
class TestProjectHandler(GenericApiHandler):
"""
TestProjectHandler Class
Handle the requests about the Test projects
HTTP Methdods :
- GET : Get all test projects and details about a specific one
- POST : Add a test project
- PUT : Edit test projects information (name and/or description)
- DELETE : Remove a test project
"""
def initialize(self):
""" Prepares the database for the entire class """
super(TestProjectHandler, self).initialize()
@asynchronous
@gen.coroutine
def get(self, project_name=None):
"""
Get Project(s) info
:param project_name:
"""
if project_name is None:
project_name = ""
get_request = dict()
if len(project_name) > 0:
get_request["name"] = project_name
res = []
cursor = self.db.test_projects.find(get_request)
while (yield cursor.fetch_next):
test_project = TestProject.testproject_from_dict(
cursor.next_object())
res.append(test_project.format_http())
meta = dict()
meta["total"] = len(res)
meta["success"] = True if len(res) > 0 else False
answer = dict()
answer["test_projects"] = res
answer["meta"] = meta
self.finish_request(answer)
@asynchronous
@gen.coroutine
def post(self):
""" Create a test project"""
if self.json_args is None:
raise HTTPError(HTTP_BAD_REQUEST)
query = {"name": self.json_args.get("name")}
# check for name in db
mongo_dict = yield self.db.test_projects.find_one(query)
if mongo_dict is not None:
raise HTTPError(HTTP_FORBIDDEN,
"{} already exists as a project".format(
self.json_args.get("name")))
test_project = TestProject.testproject_from_dict(self.json_args)
test_project.creation_date = datetime.now()
future = self.db.test_projects.insert(test_project.format())
result = yield future
test_project._id = result
self.finish_request(test_project.format_http())
@asynchronous
@gen.coroutine
def put(self, project_name):
""" Updates the name and description of a test project"""
print "PUT request for : {}".format(project_name)
query = {'name': project_name}
mongo_dict = yield self.db.test_projects.find_one(query)
test_project = TestProject.testproject_from_dict(mongo_dict)
if test_project is None:
raise HTTPError(HTTP_NOT_FOUND,
"{} could not be found".format(project_name))
new_name = self.json_args.get("name")
new_description = self.json_args.get("description")
# check for payload name parameter in db
# avoid a request if the project name has not changed in the payload
if new_name != test_project.name:
mongo_dict = yield self.db.test_projects.find_one(
{"name": new_name})
if mongo_dict is not None:
raise HTTPError(HTTP_FORBIDDEN,
"{} already exists as a project"
.format(new_name))
# new dict for changes
request = dict()
request = prepare_put_request(request,
"name",
new_name,
test_project.name)
request = prepare_put_request(request,
"description",
new_description,
test_project.description)
""" raise exception if there isn't a change """
if not request:
raise HTTPError(HTTP_FORBIDDEN,
"Nothing to update")
""" we merge the whole document """
edit_request = test_project.format()
edit_request.update(request)
""" Updating the DB """
res = yield self.db.test_projects.update({'name': project_name},
edit_request)
print res
edit_request["_id"] = str(test_project._id)
self.finish_request({"message": "success", "content": edit_request})
@asynchronous
@gen.coroutine
def delete(self, project_name):
""" Remove a test project"""
print "DELETE request for : {}".format(project_name)
# check for an existing project to be deleted
mongo_dict = yield self.db.test_projects.find_one(
{'name': project_name})
test_project = TestProject.testproject_from_dict(mongo_dict)
if test_project is None:
raise HTTPError(HTTP_NOT_FOUND,
"{} could not be found as a project to be deleted"
.format(project_name))
# just delete it, or maybe save it elsewhere in a future
res = yield self.db.test_projects.remove(
{'name': project_name})
print res
self.finish_request({"message": "success"})
class TestCasesHandler(GenericApiHandler):
"""
TestCasesHandler Class
Handle the requests about the Test cases for test projects
HTTP Methdods :
- GET : Get all test cases and details about a specific one
- POST : Add a test project
- PUT : Edit test projects information (name and/or description)
"""
def initialize(self):
""" Prepares the database for the entire class """
super(TestCasesHandler, self).initialize()
@asynchronous
@gen.coroutine
def get(self, project_name, case_name=None):
"""
Get testcases(s) info
:param project_name:
:param case_name:
"""
if case_name is None:
case_name = ""
get_request = dict()
get_request["project_name"] = project_name
if len(case_name) > 0:
get_request["name"] = case_name
res = []
cursor = self.db.test_cases.find(get_request)
print get_request
while (yield cursor.fetch_next):
test_case = TestCase.test_case_from_dict(cursor.next_object())
res.append(test_case.format_http())
meta = dict()
meta["total"] = len(res)
meta["success"] = True if len(res) > 0 else False
answer = dict()
answer["test_cases"] = res
answer["meta"] = meta
self.finish_request(answer)
@asynchronous
@gen.coroutine
def post(self, project_name):
""" Create a test case"""
print "POST Request for {}".format(project_name)
if self.json_args is None:
raise HTTPError(HTTP_BAD_REQUEST,
"Check your request payload")
# retrieve test project
mongo_dict = yield self.db.test_projects.find_one(
{"name": project_name})
if mongo_dict is None:
raise HTTPError(HTTP_FORBIDDEN,
"Could not find project {}"
.format(project_name))
# test_project = TestProject.testproject_from_dict(self.json_args)
case = TestCase.test_case_from_dict(self.json_args)
case.project_name = project_name
case.creation_date = datetime.now()
future = self.db.test_cases.insert(case.format())
result = yield future
case._id = result
self.finish_request(case.format_http())
@asynchronous
@gen.coroutine
def put(self, project_name, case_name):
"""
Updates the name and description of a test case
:raises HTTPError (HTTP_NOT_FOUND, HTTP_FORBIDDEN)
"""
print "PUT request for : {}/{}".format(project_name, case_name)
case_request = {'project_name': project_name, 'name': case_name}
# check if there is a case for the project in url parameters
mongo_dict = yield self.db.test_cases.find_one(case_request)
test_case = TestCase.test_case_from_dict(mongo_dict)
if test_case is None:
raise HTTPError(HTTP_NOT_FOUND,
"{} could not be found as a {} case to be updated"
.format(case_name, project_name))
new_name = self.json_args.get("name")
new_project_name = self.json_args.get("project_name")
new_description = self.json_args.get("description")
# check if there is not an existing test case
# with the name provided in the json payload
mongo_dict = yield self.db.test_cases.find_one(
{'project_name': new_project_name, 'name': new_name})
if mongo_dict is not None:
raise HTTPError(HTTP_FORBIDDEN,
"{} already exists as a project"
.format(new_name))
# new dict for changes
request = dict()
request = prepare_put_request(request,
"name",
new_name,
test_case.name)
request = prepare_put_request(request,
"project_name",
new_project_name,
test_case.project_name)
request = prepare_put_request(request,
"description",
new_description,
test_case.description)
# we raise an exception if there isn't a change
if not request:
raise HTTPError(HTTP_FORBIDDEN,
"Nothing to update")
# we merge the whole document """
edit_request = test_case.format()
edit_request.update(request)
""" Updating the DB """
res = yield self.db.test_cases.update(case_request, edit_request)
print res
edit_request["_id"] = str(test_case._id)
self.finish_request({"message": "success", "content": edit_request})
@asynchronous
@gen.coroutine
def delete(self, project_name, case_name):
""" Remove a test case"""
print "DELETE request for : {}/{}".format(project_name, case_name)
case_request = {'project_name': project_name, 'name': case_name}
# check for an existing case to be deleted
mongo_dict = yield self.db.test_cases.find_one(case_request)
test_project = TestProject.testproject_from_dict(mongo_dict)
if test_project is None:
raise HTTPError(HTTP_NOT_FOUND,
"{}/{} could not be found as a case to be deleted"
.format(project_name, case_name))
# just delete it, or maybe save it elsewhere in a future
res = yield self.db.test_projects.remove(case_request)
print res
self.finish_request({"message": "success"})
class TestResultsHandler(GenericApiHandler):
"""
TestResultsHandler Class
Handle the requests about the Test project's results
HTTP Methdods :
- GET : Get all test results and details about a specific one
- POST : Add a test results
- DELETE : Remove a test result
"""
def initialize(self):
""" Prepares the database for the entire class """
super(TestResultsHandler, self).initialize()
self.name = "test_result"
@asynchronous
@gen.coroutine
def get(self, result_id=None):
"""
Retrieve result(s) for a test project on a specific POD.
Available filters for this request are :
- project : project name
- case : case name
- pod : pod name
- version : platform version (Arno-R1, ...)
- installer (fuel, ...)
- build_tag : Jenkins build tag name
- period : x (x last days)
- scenario : the test scenario (previously version)
- criteria : the global criteria status passed or failed
- trust_indicator : evaluate the stability of the test case to avoid
running systematically long and stable test case
:param result_id: Get a result by ID
:raise HTTPError
GET /results/project=functest&case=vPing&version=Arno-R1 \
&pod=pod_name&period=15
=> get results with optional filters
"""
project_arg = self.get_query_argument("project", None)
case_arg = self.get_query_argument("case", None)
pod_arg = self.get_query_argument("pod", None)
version_arg = self.get_query_argument("version", None)
installer_arg = self.get_query_argument("installer", None)
build_tag_arg = self.get_query_argument("build_tag", None)
scenario_arg = self.get_query_argument("scenario", None)
criteria_arg = self.get_query_argument("criteria", None)
period_arg = self.get_query_argument("period", None)
trust_indicator_arg = self.get_query_argument("trust_indicator", None)
# prepare request
get_request = dict()
if result_id is None:
if project_arg is not None:
get_request["project_name"] = project_arg
if case_arg is not None:
get_request["case_name"] = case_arg
if pod_arg is not None:
get_request["pod_name"] = pod_arg
if version_arg is not None:
get_request["version"] = version_arg
if installer_arg is not None:
get_request["installer"] = installer_arg
if build_tag_arg is not None:
get_request["build_tag"] = build_tag_arg
if scenario_arg is not None:
get_request["scenario"] = scenario_arg
if criteria_arg is not None:
get_request["criteria_tag"] = criteria_arg
if trust_indicator_arg is not None:
get_request["trust_indicator_arg"] = trust_indicator_arg
if period_arg is not None:
try:
period_arg = int(period_arg)
except:
raise HTTPError(HTTP_BAD_REQUEST)
if period_arg > 0:
period = datetime.now() - timedelta(days=period_arg)
obj = {"$gte": str(period)}
get_request["creation_date"] = obj
else:
get_request["_id"] = result_id
print get_request
res = []
# fetching results
cursor = self.db.test_results.find(get_request)
while (yield cursor.fetch_next):
test_result = TestResult.test_result_from_dict(
cursor.next_object())
res.append(test_result.format_http())
# building meta object
meta = dict()
meta["total"] = len(res)
# final response object
answer = dict()
answer["test_results"] = res
answer["meta"] = meta
self.finish_request(answer)
@asynchronous
@gen.coroutine
def post(self):
"""
Create a new test result
:return: status of the request
:raise HTTPError
"""
# check for request payload
if self.json_args is None:
raise HTTPError(HTTP_BAD_REQUEST)
# check for missing parameters in the request payload
if self.json_args.get("project_name") is None:
raise HTTPError(HTTP_BAD_REQUEST)
if self.json_args.get("case_name") is None:
raise HTTPError(HTTP_BAD_REQUEST)
# check for pod_name instead of id,
# keeping id for current implementations
if self.json_args.get("pod_name") is None:
raise HTTPError(HTTP_BAD_REQUEST)
# TODO : replace checks with jsonschema
# check for project
mongo_dict = yield self.db.test_projects.find_one(
{"name": self.json_args.get("project_name")})
if mongo_dict is None:
raise HTTPError(HTTP_NOT_FOUND,
"Could not find project [{}] "
.format(self.json_args.get("project_name")))
# check for case
mongo_dict = yield self.db.test_cases.find_one(
{"name": self.json_args.get("case_name")})
if mongo_dict is None:
raise HTTPError(HTTP_NOT_FOUND,
"Could not find case [{}] "
.format(self.json_args.get("case_name")))
# check for pod
mongo_dict = yield self.db.pod.find_one(
{"name": self.json_args.get("pod_name")})
if mongo_dict is None:
raise HTTPError(HTTP_NOT_FOUND,
"Could not find POD [{}] "
.format(self.json_args.get("pod_name")))
# convert payload to object
test_result = TestResult.test_result_from_dict(self.json_args)
test_result.creation_date = datetime.now()
future = self.db.test_results.insert(test_result.format(),
check_keys=False)
result = yield future
test_result._id = result
self.finish_request(test_result.format_http())
class DashboardHandler(GenericApiHandler):
"""
DashboardHandler Class
Handle the requests about the Test project's results
in a dahboard ready format
HTTP Methdods :
- GET : Get all test results and details about a specific one
"""
def initialize(self):
""" Prepares the database for the entire class """
super(DashboardHandler, self).initialize()
self.name = "dashboard"
@asynchronous
@gen.coroutine
def get(self, result_id=None):
"""
Retrieve dashboard ready result(s) for a test project
Available filters for this request are :
- project : project name
- case : case name
- pod : pod name
- version : platform version (Arno-R1, ...)
- installer (fuel, ...)
- period : x (x last days)
:param result_id: Get a result by ID
:raise HTTPError
GET /dashboard?project=functest&case=vPing&version=Arno-R1 \
&pod=pod_name&period=15
=> get results with optional filters
"""
project_arg = self.get_query_argument("project", None)
case_arg = self.get_query_argument("case", None)
pod_arg = self.get_query_argument("pod", None)
version_arg = self.get_query_argument("version", None)
installer_arg = self.get_query_argument("installer", None)
period_arg = self.get_query_argument("period", None)
# prepare request
get_request = dict()
# /dashboard?project=<>&pod=<>...
if (result_id is None):
if project_arg is not None:
get_request["project_name"] = project_arg
if case_arg is not None:
get_request["case_name"] = case_arg
if pod_arg is not None:
get_request["pod_name"] = pod_arg
if version_arg is not None:
get_request["version"] = version_arg
if installer_arg is not None:
get_request["installer"] = installer_arg
if period_arg is not None:
try:
period_arg = int(period_arg)
except:
raise HTTPError(HTTP_BAD_REQUEST)
if period_arg > 0:
period = datetime.now() - timedelta(days=period_arg)
obj = {"$gte": str(period)}
get_request["creation_date"] = obj
else:
get_request["_id"] = result_id
dashboard = []
# on /dashboard retrieve the list of projects and testcases
# ready for dashboard
if project_arg is None:
raise HTTPError(HTTP_NOT_FOUND,
"error:Project name missing")
elif check_dashboard_ready_project(project_arg, "./dashboard"):
res = []
if case_arg is None:
raise HTTPError(
HTTP_NOT_FOUND,
"error:Test case missing for project " + project_arg)
# special case of status for project
if case_arg == "status":
del get_request["case_name"]
# retention time to be agreed
# last five days by default?
# TODO move to DB
period = datetime.now() - timedelta(days=5)
get_request["creation_date"] = {"$gte": period}
# fetching results
cursor = self.db.test_results.find(get_request)
while (yield cursor.fetch_next):
test_result = TestResult.test_result_from_dict(
cursor.next_object())
res.append(test_result.format_http())
if check_dashboard_ready_case(project_arg, case_arg):
dashboard = get_dashboard_result(project_arg, case_arg, res)
else:
raise HTTPError(
HTTP_NOT_FOUND,
"error:" + case_arg +
" test case not case dashboard ready on project " +
project_arg)
else:
dashboard.append(
{"error": "Project not recognized or not dashboard ready"})
dashboard.append(
{"Dashboard-ready-projects":
get_dashboard_cases("./dashboard")})
raise HTTPError(
HTTP_NOT_FOUND,
"error: no dashboard ready data for this project")
# fetching results
# cursor = self.db.test_results.find(get_request)
# while (yield cursor.fetch_next):
# test_result = TestResult.test_result_from_dict(
# cursor.next_object())
# res.append(test_result.format_http())
# building meta object
meta = dict()
# final response object
answer = dict()
answer["dashboard"] = dashboard
answer["meta"] = meta
self.finish_request(answer)
|