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