unify raise exception process
[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
15 from opnfv_testapi.common import raises
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             raises.BadRequest('{} must be int'.format(key))
34         return value
35
36     def set_query(self):
37         query = dict()
38         for k in self.request.query_arguments.keys():
39             v = self.get_query_argument(k)
40             if k == 'project' or k == 'pod' or k == 'case':
41                 query[k + '_name'] = v
42             elif k == 'period':
43                 v = self.get_int(k, v)
44                 if v > 0:
45                     period = datetime.now() - timedelta(days=v)
46                     obj = {"$gte": str(period)}
47                     query['start_date'] = obj
48             elif k == 'trust_indicator':
49                 query[k + '.current'] = float(v)
50             elif k != 'last':
51                 query[k] = v
52         return query
53
54
55 class ResultsCLHandler(GenericResultHandler):
56     @swagger.operation(nickname="queryTestResults")
57     def get(self):
58         """
59             @description: Retrieve result(s) for a test project
60                           on a specific pod.
61             @notes: Retrieve result(s) for a test project on a specific pod.
62                 Available filters for this request are :
63                  - project : project name
64                  - case : case name
65                  - pod : pod name
66                  - version : platform version (Arno-R1, ...)
67                  - installer (fuel, ...)
68                  - build_tag : Jenkins build tag name
69                  - period : x (x last days)
70                  - scenario : the test scenario (previously version)
71                  - criteria : the global criteria status passed or failed
72                  - trust_indicator : evaluate the stability of the test case
73                    to avoid running systematically long and stable test case
74
75                 GET /results/project=functest&case=vPing&version=Arno-R1 \
76                 &pod=pod_name&period=15
77             @return 200: all test results consist with query,
78                          empty list if no result is found
79             @rtype: L{TestResults}
80             @param pod: pod name
81             @type pod: L{string}
82             @in pod: query
83             @required pod: False
84             @param project: project name
85             @type project: L{string}
86             @in project: query
87             @required project: False
88             @param case: case name
89             @type case: L{string}
90             @in case: query
91             @required case: False
92             @param version: i.e. Colorado
93             @type version: L{string}
94             @in version: query
95             @required version: False
96             @param installer: fuel/apex/joid/compass
97             @type installer: L{string}
98             @in installer: query
99             @required installer: False
100             @param build_tag: i.e. v3.0
101             @type build_tag: L{string}
102             @in build_tag: query
103             @required build_tag: False
104             @param scenario: i.e. odl
105             @type scenario: L{string}
106             @in scenario: query
107             @required scenario: False
108             @param criteria: i.e. passed
109             @type criteria: L{string}
110             @in criteria: query
111             @required criteria: False
112             @param period: last days
113             @type period: L{string}
114             @in period: query
115             @required period: False
116             @param last: last records stored until now
117             @type last: L{string}
118             @in last: query
119             @required last: False
120             @param trust_indicator: must be float
121             @type trust_indicator: L{float}
122             @in trust_indicator: query
123             @required trust_indicator: False
124         """
125         last = self.get_query_argument('last', 0)
126         if last is not None:
127             last = self.get_int('last', last)
128
129         self._list(self.set_query(), sort=[('start_date', -1)], last=last)
130
131     @swagger.operation(nickname="createTestResult")
132     def post(self):
133         """
134             @description: create a test result
135             @param body: result to be created
136             @type body: L{ResultCreateRequest}
137             @in body: body
138             @rtype: L{CreateResponse}
139             @return 200: result is created.
140             @raise 404: pod/project/testcase not exist
141             @raise 400: body/pod_name/project_name/case_name not provided
142         """
143         def pod_query(data):
144             return {'name': data.pod_name}
145
146         def pod_error(data):
147             message = 'Could not find pod [{}]'.format(data.pod_name)
148             return httplib.NOT_FOUND, message
149
150         def project_query(data):
151             return {'name': data.project_name}
152
153         def project_error(data):
154             message = 'Could not find project [{}]'.format(data.project_name)
155             return httplib.NOT_FOUND, message
156
157         def testcase_query(data):
158             return {'project_name': data.project_name, 'name': data.case_name}
159
160         def testcase_error(data):
161             message = 'Could not find testcase [{}] in project [{}]'\
162                 .format(data.case_name, data.project_name)
163             return httplib.NOT_FOUND, message
164
165         miss_checks = ['pod_name', 'project_name', 'case_name']
166         db_checks = [('pods', True, pod_query, pod_error),
167                      ('projects', True, project_query, project_error),
168                      ('testcases', True, testcase_query, testcase_error)]
169         self._create(miss_checks, db_checks)
170
171
172 class ResultsGURHandler(GenericResultHandler):
173     @swagger.operation(nickname='getTestResultById')
174     def get(self, result_id):
175         """
176             @description: get a single result by result_id
177             @rtype: L{TestResult}
178             @return 200: test result exist
179             @raise 404: test result not exist
180         """
181         query = dict()
182         query["_id"] = objectid.ObjectId(result_id)
183         self._get_one(query)
184
185     @swagger.operation(nickname="updateTestResultById")
186     def put(self, result_id):
187         """
188             @description: update a single result by _id
189             @param body: fields to be updated
190             @type body: L{ResultUpdateRequest}
191             @in body: body
192             @rtype: L{Result}
193             @return 200: update success
194             @raise 404: result not exist
195             @raise 403: nothing to update
196         """
197         query = {'_id': objectid.ObjectId(result_id)}
198         db_keys = []
199         self._update(query, db_keys)