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