refactor int query parameter process in testAPI
[releng.git] / utils / test / result_collection_api / 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, timedelta
10
11 from bson.objectid import ObjectId
12 from tornado.web import HTTPError
13
14 from opnfv_testapi.common.constants import HTTP_BAD_REQUEST, HTTP_NOT_FOUND
15 from opnfv_testapi.resources.handlers import GenericApiHandler
16 from opnfv_testapi.resources.result_models import TestResult
17 from opnfv_testapi.tornado_swagger import swagger
18
19
20 class GenericResultHandler(GenericApiHandler):
21     def __init__(self, application, request, **kwargs):
22         super(GenericResultHandler, self).__init__(application,
23                                                    request,
24                                                    **kwargs)
25         self.table = self.db_results
26         self.table_cls = TestResult
27
28     def get_int(self, key, value):
29         try:
30             value = int(value)
31         except:
32             raise HTTPError(HTTP_BAD_REQUEST, '{} must be int', key)
33         return value
34
35     def set_query(self):
36         query = dict()
37         for k in self.request.query_arguments.keys():
38             v = self.get_query_argument(k)
39             if k == 'project' or k == 'pod' or k == 'case':
40                 query[k + '_name'] = v
41             elif k == 'period':
42                 v = self.get_int(k, v)
43                 if v > 0:
44                     period = datetime.now() - timedelta(days=v)
45                     obj = {"$gte": str(period)}
46                     query['start_date'] = obj
47             elif k == 'trust_indicator':
48                 query[k] = float(v)
49             elif k != 'last':
50                 query[k] = v
51         return query
52
53
54 class ResultsCLHandler(GenericResultHandler):
55     @swagger.operation(nickname="list-all")
56     def get(self):
57         """
58             @description: Retrieve result(s) for a test project
59                           on a specific pod.
60             @notes: Retrieve result(s) for a test project on a specific pod.
61                 Available filters for this request are :
62                  - project : project name
63                  - case : case name
64                  - pod : pod name
65                  - version : platform version (Arno-R1, ...)
66                  - installer (fuel, ...)
67                  - build_tag : Jenkins build tag name
68                  - period : x (x last days)
69                  - scenario : the test scenario (previously version)
70                  - criteria : the global criteria status passed or failed
71                  - trust_indicator : evaluate the stability of the test case
72                    to avoid running systematically long and stable test case
73
74                 GET /results/project=functest&case=vPing&version=Arno-R1 \
75                 &pod=pod_name&period=15
76             @return 200: all test results consist with query,
77                          empty list if no result is found
78             @rtype: L{TestResults}
79             @param pod: pod name
80             @type pod: L{string}
81             @in pod: query
82             @required pod: False
83             @param project: project name
84             @type project: L{string}
85             @in project: query
86             @required project: False
87             @param case: case name
88             @type case: L{string}
89             @in case: query
90             @required case: False
91             @param version: i.e. Colorado
92             @type version: L{string}
93             @in version: query
94             @required version: False
95             @param installer: fuel/apex/joid/compass
96             @type installer: L{string}
97             @in installer: query
98             @required installer: False
99             @param build_tag: i.e. v3.0
100             @type build_tag: L{string}
101             @in build_tag: query
102             @required build_tag: False
103             @param scenario: i.e. odl
104             @type scenario: L{string}
105             @in scenario: query
106             @required scenario: False
107             @param criteria: i.e. passed
108             @type criteria: L{string}
109             @in criteria: query
110             @required criteria: False
111             @param period: last days
112             @type period: L{string}
113             @in period: query
114             @required period: False
115             @param last: last days
116             @type last: L{string}
117             @in last: query
118             @required last: False
119             @param trust_indicator: must be int/long/float
120             @type trust_indicator: L{string}
121             @in trust_indicator: query
122             @required trust_indicator: False
123         """
124         last = self.get_query_argument('last', 0)
125         if last is not None:
126             last = self.get_int('last', last)
127
128         self._list(self.set_query(), sort=[{'start_date', -1}], last=last)
129
130     @swagger.operation(nickname="create")
131     def post(self):
132         """
133             @description: create a test result
134             @param body: result to be created
135             @type body: L{ResultCreateRequest}
136             @in body: body
137             @rtype: L{TestResult}
138             @return 200: result is created.
139             @raise 404: pod/project/testcase not exist
140             @raise 400: body/pod_name/project_name/case_name not provided
141         """
142         def pod_query(data):
143             return {'name': data.pod_name}
144
145         def pod_error(data):
146             message = 'Could not find pod [{}]'.format(data.pod_name)
147             return HTTP_NOT_FOUND, message
148
149         def project_query(data):
150             return {'name': data.project_name}
151
152         def project_error(data):
153             message = 'Could not find project [{}]'.format(data.project_name)
154             return HTTP_NOT_FOUND, message
155
156         def testcase_query(data):
157             return {'project_name': data.project_name, 'name': data.case_name}
158
159         def testcase_error(data):
160             message = 'Could not find testcase [{}] in project [{}]'\
161                 .format(data.case_name, data.project_name)
162             return HTTP_NOT_FOUND, message
163
164         miss_checks = ['pod_name', 'project_name', 'case_name']
165         db_checks = [('pods', True, pod_query, pod_error),
166                      ('projects', True, project_query, project_error),
167                      ('testcases', True, testcase_query, testcase_error)]
168         self._create(miss_checks, db_checks)
169
170
171 class ResultsGURHandler(GenericResultHandler):
172     @swagger.operation(nickname='get-one')
173     def get(self, result_id):
174         """
175             @description: get a single result by result_id
176             @rtype: L{TestResult}
177             @return 200: test result exist
178             @raise 404: test result not exist
179         """
180         query = dict()
181         query["_id"] = ObjectId(result_id)
182         self._get_one(query)