44b9f8c0761dabf02e78525d3e4d407fffe543db
[releng.git] / utils / test / testapi / opnfv_testapi / resources / result_handlers.py
1 ##############################################################################
2 # Copyright (c) 2015 Orange
3 # guyrodrigue.koffi@orange.com / koffirodrigue@gmail.com
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9 from datetime import datetime
10 from datetime import timedelta
11 import httplib
12
13 from bson import objectid
14 from tornado import web
15
16 from opnfv_testapi.resources import handlers
17 from opnfv_testapi.resources import result_models
18 from opnfv_testapi.tornado_swagger import swagger
19
20
21 class GenericResultHandler(handlers.GenericApiHandler):
22     def __init__(self, application, request, **kwargs):
23         super(GenericResultHandler, self).__init__(application,
24                                                    request,
25                                                    **kwargs)
26         self.table = self.db_results
27         self.table_cls = result_models.TestResult
28
29     def get_int(self, key, value):
30         try:
31             value = int(value)
32         except:
33             raise web.HTTPError(httplib.BAD_REQUEST,
34                                 '{} must be int'.format(key))
35         return value
36
37     def set_query(self):
38         query = dict()
39         for k in self.request.query_arguments.keys():
40             v = self.get_query_argument(k)
41             if k == 'project' or k == 'pod' or k == 'case':
42                 query[k + '_name'] = v
43             elif k == 'period':
44                 v = self.get_int(k, v)
45                 if v > 0:
46                     period = datetime.now() - timedelta(days=v)
47                     obj = {"$gte": str(period)}
48                     query['start_date'] = obj
49             elif k == 'trust_indicator':
50                 query[k + '.current'] = float(v)
51             elif k != 'last':
52                 query[k] = v
53         return query
54
55
56 class ResultsCLHandler(GenericResultHandler):
57     @swagger.operation(nickname="queryTestResults")
58     def get(self):
59         """
60             @description: Retrieve result(s) for a test project
61                           on a specific pod.
62             @notes: Retrieve result(s) for a test project on a specific pod.
63                 Available filters for this request are :
64                  - project : project name
65                  - case : case name
66                  - pod : pod name
67                  - version : platform version (Arno-R1, ...)
68                  - installer (fuel, ...)
69                  - build_tag : Jenkins build tag name
70                  - period : x (x last days)
71                  - scenario : the test scenario (previously version)
72                  - criteria : the global criteria status passed or failed
73                  - trust_indicator : evaluate the stability of the test case
74                    to avoid running systematically long and stable test case
75
76                 GET /results/project=functest&case=vPing&version=Arno-R1 \
77                 &pod=pod_name&period=15
78             @return 200: all test results consist with query,
79                          empty list if no result is found
80             @rtype: L{TestResults}
81             @param pod: pod name
82             @type pod: L{string}
83             @in pod: query
84             @required pod: False
85             @param project: project name
86             @type project: L{string}
87             @in project: query
88             @required project: False
89             @param case: case name
90             @type case: L{string}
91             @in case: query
92             @required case: False
93             @param version: i.e. Colorado
94             @type version: L{string}
95             @in version: query
96             @required version: False
97             @param installer: fuel/apex/joid/compass
98             @type installer: L{string}
99             @in installer: query
100             @required installer: False
101             @param build_tag: i.e. v3.0
102             @type build_tag: L{string}
103             @in build_tag: query
104             @required build_tag: False
105             @param scenario: i.e. odl
106             @type scenario: L{string}
107             @in scenario: query
108             @required scenario: False
109             @param criteria: i.e. passed
110             @type criteria: L{string}
111             @in criteria: query
112             @required criteria: False
113             @param period: last days
114             @type period: L{string}
115             @in period: query
116             @required period: False
117             @param last: last records stored until now
118             @type last: L{string}
119             @in last: query
120             @required last: False
121             @param trust_indicator: must be float
122             @type trust_indicator: L{float}
123             @in trust_indicator: query
124             @required trust_indicator: False
125         """
126         last = self.get_query_argument('last', 0)
127         if last is not None:
128             last = self.get_int('last', last)
129
130         self._list(self.set_query(), sort=[('start_date', -1)], last=last)
131
132     @swagger.operation(nickname="createTestResult")
133     def post(self):
134         """
135             @description: create a test result
136             @param body: result to be created
137             @type body: L{ResultCreateRequest}
138             @in body: body
139             @rtype: L{CreateResponse}
140             @return 200: result is created.
141             @raise 404: pod/project/testcase not exist
142             @raise 400: body/pod_name/project_name/case_name not provided
143         """
144         def pod_query(data):
145             return {'name': data.pod_name}
146
147         def pod_error(data):
148             message = 'Could not find pod [{}]'.format(data.pod_name)
149             return httplib.NOT_FOUND, message
150
151         def project_query(data):
152             return {'name': data.project_name}
153
154         def project_error(data):
155             message = 'Could not find project [{}]'.format(data.project_name)
156             return httplib.NOT_FOUND, message
157
158         def testcase_query(data):
159             return {'project_name': data.project_name, 'name': data.case_name}
160
161         def testcase_error(data):
162             message = 'Could not find testcase [{}] in project [{}]'\
163                 .format(data.case_name, data.project_name)
164             return httplib.NOT_FOUND, message
165
166         miss_checks = ['pod_name', 'project_name', 'case_name']
167         db_checks = [('pods', True, pod_query, pod_error),
168                      ('projects', True, project_query, project_error),
169                      ('testcases', True, testcase_query, testcase_error)]
170         self._create(miss_checks, db_checks)
171
172
173 class ResultsGURHandler(GenericResultHandler):
174     @swagger.operation(nickname='getTestResultById')
175     def get(self, result_id):
176         """
177             @description: get a single result by result_id
178             @rtype: L{TestResult}
179             @return 200: test result exist
180             @raise 404: test result not exist
181         """
182         query = dict()
183         query["_id"] = objectid.ObjectId(result_id)
184         self._get_one(query)
185
186     @swagger.operation(nickname="updateTestResultById")
187     def put(self, result_id):
188         """
189             @description: update a single result by _id
190             @param body: fields to be updated
191             @type body: L{ResultUpdateRequest}
192             @in body: body
193             @rtype: L{Result}
194             @return 200: update success
195             @raise 404: result not exist
196             @raise 403: nothing to update
197         """
198         query = {'_id': objectid.ObjectId(result_id)}
199         db_keys = []
200         self._update(query, db_keys)