Merge "Support opera test in functest releng"
[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
12 from bson import objectid
13
14 from opnfv_testapi.common import message
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(message.must_int(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(query=self.set_query(),
130                    sort=[('start_date', -1)],
131                    last=last)
132
133     @swagger.operation(nickname="createTestResult")
134     def post(self):
135         """
136             @description: create a test result
137             @param body: result to be created
138             @type body: L{ResultCreateRequest}
139             @in body: body
140             @rtype: L{CreateResponse}
141             @return 200: result is created.
142             @raise 404: pod/project/testcase not exist
143             @raise 400: body/pod_name/project_name/case_name not provided
144         """
145         def pod_query():
146             return {'name': self.json_args.get('pod_name')}
147
148         def project_query():
149             return {'name': self.json_args.get('project_name')}
150
151         def testcase_query():
152             return {'project_name': self.json_args.get('project_name'),
153                     'name': self.json_args.get('case_name')}
154
155         miss_fields = ['pod_name', 'project_name', 'case_name']
156         carriers = [('pods', pod_query),
157                     ('projects', project_query),
158                     ('testcases', testcase_query)]
159         self._create(miss_fields=miss_fields, carriers=carriers)
160
161
162 class ResultsGURHandler(GenericResultHandler):
163     @swagger.operation(nickname='getTestResultById')
164     def get(self, result_id):
165         """
166             @description: get a single result by result_id
167             @rtype: L{TestResult}
168             @return 200: test result exist
169             @raise 404: test result not exist
170         """
171         query = dict()
172         query["_id"] = objectid.ObjectId(result_id)
173         self._get_one(query=query)
174
175     @swagger.operation(nickname="updateTestResultById")
176     def put(self, result_id):
177         """
178             @description: update a single result by _id
179             @param body: fields to be updated
180             @type body: L{ResultUpdateRequest}
181             @in body: body
182             @rtype: L{Result}
183             @return 200: update success
184             @raise 404: result not exist
185             @raise 403: nothing to update
186         """
187         query = {'_id': objectid.ObjectId(result_id)}
188         db_keys = []
189         self._update(query=query, db_keys=db_keys)