Cleanup previous run output files
[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         with open(self.json_file) as stream_:
47             self.response = json.load(stream_)
48             if self.response:
49                 self.total_tests = len(self.response)
50             for item in self.response:
51                 if item['status'] == 'passed':
52                     self.pass_tests += 1
53                 elif item['status'] == 'failed':
54                     self.fail_tests += 1
55                 elif item['status'] == 'skipped':
56                     self.skip_tests += 1
57             self.result = 100 * (
58                 self.pass_tests / self.total_tests)
59             self.details = {}
60             self.details['total_tests'] = self.total_tests
61             self.details['pass_tests'] = self.pass_tests
62             self.details['fail_tests'] = self.fail_tests
63             self.details['skip_tests'] = self.skip_tests
64             self.details['tests'] = self.response
65
66     def run(self, **kwargs):
67         """Run the BehaveFramework feature files
68
69         Here are the steps:
70            * create the output directories if required,
71            * run behave features with parameters
72            * get the results in output.json,
73
74         Args:
75             kwargs: Arbitrary keyword arguments.
76
77         Returns:
78             EX_OK if all suites ran well.
79             EX_RUN_ERROR otherwise.
80         """
81         try:
82             suites = kwargs["suites"]
83             tags = kwargs.get("tags", [])
84         except KeyError:
85             self.__logger.exception("Mandatory args were not passed")
86             return self.EX_RUN_ERROR
87         if not os.path.exists(self.res_dir):
88             try:
89                 os.makedirs(self.res_dir)
90             except Exception:  # pylint: disable=broad-except
91                 self.__logger.exception("Cannot create %s", self.res_dir)
92                 return self.EX_RUN_ERROR
93         config = ['--tags='+','.join(tags),
94                   '--junit', '--junit-directory={}'.format(self.res_dir),
95                   '--format=json', '--outfile={}'.format(self.json_file)]
96         if six.PY3:
97             html_file = os.path.join(self.res_dir, 'output.html')
98             config += ['--format=behave_html_formatter:HTMLFormatter',
99                        '--outfile={}'.format(html_file)]
100         for feature in suites:
101             config.append(feature)
102         self.start_time = time.time()
103         behave_main(config)
104         self.stop_time = time.time()
105
106         try:
107             self.parse_results()
108             self.__logger.info("Results were successfully parsed")
109         except Exception:  # pylint: disable=broad-except
110             self.__logger.exception("Cannot parse results")
111             return self.EX_RUN_ERROR
112         return self.EX_OK