Forbid multipart upload if google storage
[functest-xtesting.git] / xtesting / core / behaveframework.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2019 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 classes required to run any Behave test suites."""
11
12 from __future__ import division
13
14 import logging
15 import os
16 import time
17
18 import json
19 import six
20
21 from behave.__main__ import main as behave_main
22
23 from xtesting.core import testcase
24
25 __author__ = "Deepak Chandella <deepak.chandella@orange.com>"
26
27
28 class BehaveFramework(testcase.TestCase):
29     """BehaveFramework runner."""
30     # pylint: disable=too-many-instance-attributes
31
32     __logger = logging.getLogger(__name__)
33     dir_results = "/var/lib/xtesting/results"
34
35     def __init__(self, **kwargs):
36         super(BehaveFramework, self).__init__(**kwargs)
37         self.json_file = os.path.join(self.res_dir, 'output.json')
38         self.total_tests = 0
39         self.pass_tests = 0
40         self.fail_tests = 0
41         self.skip_tests = 0
42         self.response = None
43
44     def parse_results(self):
45         """Parse output.json and get the details in it."""
46
47         try:
48             with open(self.json_file) as stream_:
49                 self.response = json.load(stream_)
50         except IOError:
51             self.__logger.error("Error reading the file %s", self.json_file)
52
53         try:
54             if self.response:
55                 self.total_tests = len(self.response)
56             for item in self.response:
57                 if item['status'] == 'passed':
58                     self.pass_tests += 1
59                 elif item['status'] == 'failed':
60                     self.fail_tests += 1
61                 elif item['status'] == 'skipped':
62                     self.skip_tests += 1
63         except KeyError:
64             self.__logger.error("Error in json - %s", self.response)
65
66         try:
67             self.result = 100 * (
68                 self.pass_tests / self.total_tests)
69         except ZeroDivisionError:
70             self.__logger.error("No test has been run")
71
72         self.details = {}
73         self.details['total_tests'] = self.total_tests
74         self.details['pass_tests'] = self.pass_tests
75         self.details['fail_tests'] = self.fail_tests
76         self.details['skip_tests'] = self.skip_tests
77         self.details['tests'] = self.response
78
79     def run(self, **kwargs):
80         """Run the BehaveFramework feature files
81
82         Here are the steps:
83            * create the output directories if required,
84            * run behave features with parameters
85            * get the results in output.json,
86
87         Args:
88             kwargs: Arbitrary keyword arguments.
89
90         Returns:
91             EX_OK if all suites ran well.
92             EX_RUN_ERROR otherwise.
93         """
94         try:
95             suites = kwargs["suites"]
96             tags = kwargs.get("tags", [])
97         except KeyError:
98             self.__logger.exception("Mandatory args were not passed")
99             return self.EX_RUN_ERROR
100         if not os.path.exists(self.res_dir):
101             try:
102                 os.makedirs(self.res_dir)
103             except Exception:  # pylint: disable=broad-except
104                 self.__logger.exception("Cannot create %s", self.res_dir)
105                 return self.EX_RUN_ERROR
106         config = ['--tags='+','.join(tags),
107                   '--junit', '--junit-directory={}'.format(self.res_dir),
108                   '--format=json', '--outfile={}'.format(self.json_file)]
109         if six.PY3:
110             html_file = os.path.join(self.res_dir, 'output.html')
111             config += ['--format=behave_html_formatter:HTMLFormatter',
112                        '--outfile={}'.format(html_file)]
113         for feature in suites:
114             config.append(feature)
115         self.start_time = time.time()
116         behave_main(config)
117         self.stop_time = time.time()
118
119         try:
120             self.parse_results()
121             self.__logger.info("Results were successfully parsed")
122         except Exception:  # pylint: disable=broad-except
123             self.__logger.exception("Cannot parse results")
124             return self.EX_RUN_ERROR
125         return self.EX_OK