Use constants instead of hard-coding paths
[functest-xtesting.git] / xtesting / core / testcase.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2016 Orange and others.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 """Define the parent class of all Xtesting TestCases."""
11
12 import abc
13 from datetime import datetime
14 import json
15 import logging
16 import mimetypes
17 import os
18 import re
19 import sys
20
21 import boto3
22 from boto3.s3.transfer import TransferConfig
23 import botocore
24 import prettytable
25 import requests
26 import six
27 from six.moves import urllib
28
29 from xtesting.utils import decorators
30 from xtesting.utils import env
31 from xtesting.utils import constants
32
33 __author__ = "Cedric Ollivier <cedric.ollivier@orange.com>"
34
35
36 @six.add_metaclass(abc.ABCMeta)
37 class TestCase():
38     # pylint: disable=too-many-instance-attributes
39     """Base model for single test case."""
40
41     EX_OK = os.EX_OK
42     """everything is OK"""
43
44     EX_RUN_ERROR = os.EX_SOFTWARE
45     """run() failed"""
46
47     EX_PUSH_TO_DB_ERROR = os.EX_SOFTWARE - 1
48     """push_to_db() failed"""
49
50     EX_TESTCASE_FAILED = os.EX_SOFTWARE - 2
51     """results are false"""
52
53     EX_TESTCASE_SKIPPED = os.EX_SOFTWARE - 3
54     """requirements are unmet"""
55
56     EX_PUBLISH_ARTIFACTS_ERROR = os.EX_SOFTWARE - 4
57     """publish_artifacts() failed"""
58
59     dir_results = constants.RESULTS_DIR
60     _job_name_rule = "(dai|week)ly-(.+?)-[0-9]*"
61     headers = {'Content-Type': 'application/json'}
62     __logger = logging.getLogger(__name__)
63
64     def __init__(self, **kwargs):
65         self.details = {}
66         self.project_name = kwargs.get('project_name', 'xtesting')
67         self.case_name = kwargs.get('case_name', '')
68         self.criteria = kwargs.get('criteria', 100)
69         self.result = 0
70         self.start_time = 0
71         self.stop_time = 0
72         self.is_skipped = False
73         self.output_log_name = os.path.basename(constants.LOG_PATH)
74         self.output_debug_log_name = os.path.basename(constants.DEBUG_LOG_PATH)
75         self.res_dir = os.path.join(self.dir_results, self.case_name)
76
77     def __str__(self):
78         try:
79             assert self.project_name
80             assert self.case_name
81             if self.is_skipped:
82                 result = 'SKIP'
83             else:
84                 result = 'PASS' if(self.is_successful(
85                     ) == TestCase.EX_OK) else 'FAIL'
86             msg = prettytable.PrettyTable(
87                 header_style='upper', padding_width=5,
88                 field_names=['test case', 'project', 'duration',
89                              'result'])
90             msg.add_row([self.case_name, self.project_name,
91                          self.get_duration(), result])
92             return msg.get_string()
93         except AssertionError:
94             self.__logger.error("We cannot print invalid objects")
95             return super(TestCase, self).__str__()
96
97     def get_duration(self):
98         """Return the duration of the test case.
99
100         Returns:
101             duration if start_time and stop_time are set
102             "XX:XX" otherwise.
103         """
104         try:
105             if self.is_skipped:
106                 return "00:00"
107             assert self.start_time
108             assert self.stop_time
109             if self.stop_time < self.start_time:
110                 return "XX:XX"
111             return "{}:{}".format(
112                 str(int(self.stop_time - self.start_time) // 60).zfill(2),
113                 str(int(self.stop_time - self.start_time) % 60).zfill(2))
114         except Exception:  # pylint: disable=broad-except
115             self.__logger.error("Please run test before getting the duration")
116             return "XX:XX"
117
118     def is_successful(self):
119         """Interpret the result of the test case.
120
121         It allows getting the result of TestCase. It completes run()
122         which only returns the execution status.
123
124         It can be overriden if checking result is not suitable.
125
126         Returns:
127             TestCase.EX_OK if result is 'PASS'.
128             TestCase.EX_TESTCASE_SKIPPED if test case is skipped.
129             TestCase.EX_TESTCASE_FAILED otherwise.
130         """
131         try:
132             if self.is_skipped:
133                 return TestCase.EX_TESTCASE_SKIPPED
134             assert self.criteria
135             assert self.result is not None
136             if (not isinstance(self.result, str) and
137                     not isinstance(self.criteria, str)):
138                 if self.result >= self.criteria:
139                     return TestCase.EX_OK
140             else:
141                 # Backward compatibility
142                 # It must be removed as soon as TestCase subclasses
143                 # stop setting result = 'PASS' or 'FAIL'.
144                 # In this case criteria is unread.
145                 self.__logger.warning(
146                     "Please update result which must be an int!")
147                 if self.result == 'PASS':
148                     return TestCase.EX_OK
149         except AssertionError:
150             self.__logger.error("Please run test before checking the results")
151         return TestCase.EX_TESTCASE_FAILED
152
153     def check_requirements(self):  # pylint: disable=no-self-use
154         """Check the requirements of the test case.
155
156         It can be overriden on purpose.
157         """
158         self.is_skipped = False
159
160     @abc.abstractmethod
161     def run(self, **kwargs):
162         """Run the test case.
163
164         It allows running TestCase and getting its execution
165         status.
166
167         The subclasses must override the default implementation which
168         is false on purpose.
169
170         The new implementation must set the following attributes to
171         push the results to DB:
172
173             * result,
174             * start_time,
175             * stop_time.
176
177         Args:
178             kwargs: Arbitrary keyword arguments.
179         """
180
181     @decorators.can_dump_request_to_file
182     def push_to_db(self):
183         """Push the results of the test case to the DB.
184
185         It allows publishing the results and checking the status.
186
187         It could be overriden if the common implementation is not
188         suitable.
189
190         The following attributes must be set before pushing the results to DB:
191
192             * project_name,
193             * case_name,
194             * result,
195             * start_time,
196             * stop_time.
197
198         The next vars must be set in env:
199
200             * TEST_DB_URL,
201             * INSTALLER_TYPE,
202             * DEPLOY_SCENARIO,
203             * NODE_NAME,
204             * BUILD_TAG.
205
206         Returns:
207             TestCase.EX_OK if results were pushed to DB.
208             TestCase.EX_PUSH_TO_DB_ERROR otherwise.
209         """
210         try:
211             if self.is_skipped:
212                 return TestCase.EX_PUSH_TO_DB_ERROR
213             assert self.project_name
214             assert self.case_name
215             assert self.start_time
216             assert self.stop_time
217             url = env.get('TEST_DB_URL')
218             data = {"project_name": self.project_name,
219                     "case_name": self.case_name,
220                     "details": self.details}
221             data["installer"] = env.get('INSTALLER_TYPE')
222             data["scenario"] = env.get('DEPLOY_SCENARIO')
223             data["pod_name"] = env.get('NODE_NAME')
224             data["build_tag"] = env.get('BUILD_TAG')
225             data["criteria"] = 'PASS' if self.is_successful(
226                 ) == TestCase.EX_OK else 'FAIL'
227             data["start_date"] = datetime.fromtimestamp(
228                 self.start_time).strftime('%Y-%m-%d %H:%M:%S')
229             data["stop_date"] = datetime.fromtimestamp(
230                 self.stop_time).strftime('%Y-%m-%d %H:%M:%S')
231             try:
232                 data["version"] = re.search(
233                     TestCase._job_name_rule,
234                     env.get('BUILD_TAG')).group(2)
235             except Exception:  # pylint: disable=broad-except
236                 data["version"] = "unknown"
237             req = requests.post(
238                 url, data=json.dumps(data, sort_keys=True),
239                 headers=self.headers)
240             req.raise_for_status()
241             if urllib.parse.urlparse(url).scheme != "file":
242                 # href must be postprocessed as OPNFV testapi is misconfigured
243                 # (localhost is returned)
244                 uid = re.sub(r'^.*/api/v1/results/*', '', req.json()["href"])
245                 netloc = env.get('TEST_DB_EXT_URL') if env.get(
246                     'TEST_DB_EXT_URL') else env.get('TEST_DB_URL')
247                 self.__logger.info(
248                     "The results were successfully pushed to DB: \n\n%s\n",
249                     os.path.join(netloc, uid))
250         except AssertionError:
251             self.__logger.exception(
252                 "Please run test before publishing the results")
253             return TestCase.EX_PUSH_TO_DB_ERROR
254         except requests.exceptions.HTTPError:
255             self.__logger.exception("The HTTP request raises issues")
256             return TestCase.EX_PUSH_TO_DB_ERROR
257         except Exception:  # pylint: disable=broad-except
258             self.__logger.exception("The results cannot be pushed to DB")
259             return TestCase.EX_PUSH_TO_DB_ERROR
260         return TestCase.EX_OK
261
262     def publish_artifacts(self):  # pylint: disable=too-many-locals
263         """Push the artifacts to the S3 repository.
264
265         It allows publishing the artifacts.
266
267         It could be overriden if the common implementation is not
268         suitable.
269
270         The credentials must be configured before publishing the artifacts:
271
272             * fill ~/.aws/credentials or ~/.boto,
273             * set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in env.
274
275         The next vars must be set in env:
276
277             * S3_ENDPOINT_URL (http://127.0.0.1:9000),
278             * S3_DST_URL (s3://xtesting/prefix),
279             * HTTP_DST_URL (http://127.0.0.1/prefix).
280
281         Returns:
282             TestCase.EX_OK if artifacts were published to repository.
283             TestCase.EX_PUBLISH_ARTIFACTS_ERROR otherwise.
284         """
285         try:
286             b3resource = boto3.resource(
287                 's3', endpoint_url=os.environ["S3_ENDPOINT_URL"])
288             dst_s3_url = os.environ["S3_DST_URL"]
289             multipart_threshold = 5 * 1024 ** 5 if "google" in os.environ[
290                 "S3_ENDPOINT_URL"] else 8 * 1024 * 1024
291             config = TransferConfig(multipart_threshold=multipart_threshold)
292             bucket_name = urllib.parse.urlparse(dst_s3_url).netloc
293             try:
294                 b3resource.meta.client.head_bucket(Bucket=bucket_name)
295             except botocore.exceptions.ClientError as exc:
296                 error_code = exc.response['Error']['Code']
297                 if error_code == '404':
298                     # pylint: disable=no-member
299                     b3resource.create_bucket(Bucket=bucket_name)
300                 else:
301                     typ, value, traceback = sys.exc_info()
302                     six.reraise(typ, value, traceback)
303             except Exception:  # pylint: disable=broad-except
304                 typ, value, traceback = sys.exc_info()
305                 six.reraise(typ, value, traceback)
306             path = urllib.parse.urlparse(dst_s3_url).path.strip("/")
307             dst_http_url = os.environ["HTTP_DST_URL"]
308             output_str = "\n"
309             self.details["links"] = []
310             for log_file in [self.output_log_name, self.output_debug_log_name]:
311                 if os.path.exists(os.path.join(self.dir_results, log_file)):
312                     abs_file = os.path.join(self.dir_results, log_file)
313                     mime_type = mimetypes.guess_type(abs_file)
314                     self.__logger.debug(
315                         "Publishing %s %s", abs_file, mime_type)
316                     # pylint: disable=no-member
317                     b3resource.Bucket(bucket_name).upload_file(
318                         abs_file, os.path.join(path, log_file), Config=config,
319                         ExtraArgs={'ContentType': mime_type[
320                             0] or 'application/octet-stream'})
321                     link = os.path.join(dst_http_url, log_file)
322                     output_str += "\n{}".format(link)
323                     self.details["links"].append(link)
324             for root, _, files in os.walk(self.res_dir):
325                 for pub_file in files:
326                     abs_file = os.path.join(root, pub_file)
327                     mime_type = mimetypes.guess_type(abs_file)
328                     self.__logger.debug(
329                         "Publishing %s %s", abs_file, mime_type)
330                     # pylint: disable=no-member
331                     b3resource.Bucket(bucket_name).upload_file(
332                         abs_file,
333                         os.path.join(path, os.path.relpath(
334                             os.path.join(root, pub_file),
335                             start=self.dir_results)),
336                         Config=config,
337                         ExtraArgs={'ContentType': mime_type[
338                             0] or 'application/octet-stream'})
339                     link = os.path.join(dst_http_url, os.path.relpath(
340                         os.path.join(root, pub_file),
341                         start=self.dir_results))
342                     output_str += "\n{}".format(link)
343                     self.details["links"].append(link)
344             self.__logger.info(
345                 "All artifacts were successfully published: %s\n", output_str)
346             return TestCase.EX_OK
347         except KeyError as ex:
348             self.__logger.error("Please check env var: %s", str(ex))
349             return TestCase.EX_PUBLISH_ARTIFACTS_ERROR
350         except botocore.exceptions.NoCredentialsError:
351             self.__logger.error(
352                 "Please fill ~/.aws/credentials, ~/.boto or set "
353                 "AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in env")
354             return TestCase.EX_PUBLISH_ARTIFACTS_ERROR
355         except Exception:  # pylint: disable=broad-except
356             self.__logger.exception("Cannot publish the artifacts")
357             return TestCase.EX_PUBLISH_ARTIFACTS_ERROR
358
359     def clean(self):
360         """Clean the resources.
361
362         It can be overriden if resources must be deleted after
363         running the test case.
364         """