Unlink feature from constants
[functest.git] / functest / 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 Functest 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 logging
17 import subprocess
18 import time
19
20 import functest.core.testcase as base
21
22 __author__ = ("Serena Feng <feng.xiaowei@zte.com.cn>, "
23               "Cedric Ollivier <cedric.ollivier@orange.com>")
24
25
26 class Feature(base.TestCase):
27     """Base model for single feature."""
28
29     __logger = logging.getLogger(__name__)
30     dir_results = "/home/opnfv/functest/results"
31
32     def __init__(self, **kwargs):
33         super(Feature, self).__init__(**kwargs)
34         self.result_file = "{}/{}.log".format(self.dir_results, self.case_name)
35         try:
36             module = kwargs['run']['module']
37             self.logger = logging.getLogger(module)
38         except KeyError:
39             self.__logger.warning(
40                 "Cannot get module name %s. Using %s as fallback",
41                 kwargs, self.case_name)
42             self.logger = logging.getLogger(self.case_name)
43         handler = logging.StreamHandler()
44         handler.setLevel(logging.WARN)
45         self.logger.addHandler(handler)
46         handler = logging.FileHandler(self.result_file)
47         handler.setLevel(logging.DEBUG)
48         self.logger.addHandler(handler)
49         formatter = logging.Formatter(
50             '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
51         handler.setFormatter(formatter)
52         self.logger.addHandler(handler)
53
54     def execute(self, **kwargs):
55         """Execute the Python method.
56
57         The subclasses must override the default implementation which
58         is false on purpose.
59
60         The new implementation must return 0 if success or anything
61         else if failure.
62
63         Args:
64             kwargs: Arbitrary keyword arguments.
65
66         Returns:
67             -1.
68         """
69         # pylint: disable=unused-argument,no-self-use
70         return -1
71
72     def run(self, **kwargs):
73         """Run the feature.
74
75         It allows executing any Python method by calling execute().
76
77         It sets the following attributes required to push the results
78         to DB:
79
80             * result,
81             * start_time,
82             * stop_time.
83
84         It doesn't fulfill details when pushing the results to the DB.
85
86         Args:
87             kwargs: Arbitrary keyword arguments.
88
89         Returns:
90             TestCase.EX_OK if execute() returns 0,
91             TestCase.EX_RUN_ERROR otherwise.
92         """
93         self.start_time = time.time()
94         exit_code = base.TestCase.EX_RUN_ERROR
95         self.result = 0
96         try:
97             if self.execute(**kwargs) == 0:
98                 exit_code = base.TestCase.EX_OK
99                 self.result = 100
100         except Exception:  # pylint: disable=broad-except
101             self.__logger.exception("%s FAILED", self.project_name)
102         self.__logger.info("Test result is stored in '%s'", self.result_file)
103         self.stop_time = time.time()
104         return exit_code
105
106
107 class BashFeature(Feature):
108     """Class designed to run any bash command."""
109
110     __logger = logging.getLogger(__name__)
111
112     def execute(self, **kwargs):
113         """Execute the cmd passed as arg
114
115         Args:
116             kwargs: Arbitrary keyword arguments.
117
118         Returns:
119             0 if cmd returns 0,
120             -1 otherwise.
121         """
122         ret = -1
123         try:
124             cmd = kwargs["cmd"]
125             with open(self.result_file, 'w+') as f_stdout:
126                 proc = subprocess.Popen(cmd.split(), stdout=f_stdout,
127                                         stderr=subprocess.STDOUT)
128             ret = proc.wait()
129             if ret != 0:
130                 self.__logger.error("Execute command: %s failed", cmd)
131         except KeyError:
132             self.__logger.error("Please give cmd as arg. kwargs: %s", kwargs)
133         return ret