Leverage on abc and stevedore
[functest-xtesting.git] / xtesting / core / feature.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2016 ZTE Corp 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 classes of all Xtesting Features.
11
12 Feature is considered as TestCase offered by Third-party. It offers
13 helpers to run any python method or any bash command.
14 """
15
16 import abc
17 import logging
18 import subprocess
19 import time
20
21 import six
22 from xtesting.core import testcase
23
24 __author__ = ("Serena Feng <feng.xiaowei@zte.com.cn>, "
25               "Cedric Ollivier <cedric.ollivier@orange.com>")
26
27
28 @six.add_metaclass(abc.ABCMeta)
29 class Feature(testcase.TestCase):
30     """Base model for single feature."""
31
32     __logger = logging.getLogger(__name__)
33
34     @abc.abstractmethod
35     def execute(self, **kwargs):
36         """Execute the Python method.
37
38         The subclasses must override the default implementation which
39         is false on purpose.
40
41         The new implementation must return 0 if success or anything
42         else if failure.
43
44         Args:
45             kwargs: Arbitrary keyword arguments.
46         """
47
48     def run(self, **kwargs):
49         """Run the feature.
50
51         It allows executing any Python method by calling execute().
52
53         It sets the following attributes required to push the results
54         to DB:
55
56             * result,
57             * start_time,
58             * stop_time.
59
60         It doesn't fulfill details when pushing the results to the DB.
61
62         Args:
63             kwargs: Arbitrary keyword arguments.
64
65         Returns:
66             TestCase.EX_OK if execute() returns 0,
67             TestCase.EX_RUN_ERROR otherwise.
68         """
69         self.start_time = time.time()
70         exit_code = testcase.TestCase.EX_RUN_ERROR
71         self.result = 0
72         try:
73             if self.execute(**kwargs) == 0:
74                 exit_code = testcase.TestCase.EX_OK
75                 self.result = 100
76         except Exception:  # pylint: disable=broad-except
77             self.__logger.exception("%s FAILED", self.project_name)
78         self.stop_time = time.time()
79         return exit_code
80
81
82 class BashFeature(Feature):
83     """Class designed to run any bash command."""
84
85     __logger = logging.getLogger(__name__)
86
87     def __init__(self, **kwargs):
88         super(BashFeature, self).__init__(**kwargs)
89         dir_results = "/var/lib/xtesting/results"
90         self.result_file = "{}/{}.log".format(dir_results, self.case_name)
91
92     def execute(self, **kwargs):
93         """Execute the cmd passed as arg
94
95         Args:
96             kwargs: Arbitrary keyword arguments.
97
98         Returns:
99             0 if cmd returns 0,
100             -1 otherwise.
101         """
102         ret = -1
103         try:
104             cmd = kwargs["cmd"]
105             with open(self.result_file, 'w+') as f_stdout:
106                 proc = subprocess.Popen(cmd.split(), stdout=f_stdout,
107                                         stderr=subprocess.STDOUT)
108             ret = proc.wait()
109             self.__logger.info(
110                 "Test result is stored in '%s'", self.result_file)
111             if ret != 0:
112                 self.__logger.error("Execute command: %s failed", cmd)
113         except KeyError:
114             self.__logger.error("Please give cmd as arg. kwargs: %s", kwargs)
115         return ret