3 # Copyright (c) 2016 ZTE Corp and others.
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
10 """Define the parent classes of all Xtesting Features.
12 Feature is considered as TestCase offered by Third-party. It offers
13 helpers to run any python method or any bash command.
24 from xtesting.core import testcase
26 __author__ = ("Serena Feng <feng.xiaowei@zte.com.cn>, "
27 "Cedric Ollivier <cedric.ollivier@orange.com>")
30 @six.add_metaclass(abc.ABCMeta)
31 class Feature(testcase.TestCase):
32 """Base model for single feature."""
34 __logger = logging.getLogger(__name__)
37 def execute(self, **kwargs):
38 """Execute the Python method.
40 The subclasses must override the default implementation which
43 The new implementation must return 0 if success or anything
47 kwargs: Arbitrary keyword arguments.
50 def run(self, **kwargs):
53 It allows executing any Python method by calling execute().
55 It sets the following attributes required to push the results
62 It doesn't fulfill details when pushing the results to the DB.
65 kwargs: Arbitrary keyword arguments.
68 TestCase.EX_OK if execute() returns 0,
69 TestCase.EX_RUN_ERROR otherwise.
71 self.start_time = time.time()
72 exit_code = testcase.TestCase.EX_RUN_ERROR
75 if self.execute(**kwargs) == 0:
76 exit_code = testcase.TestCase.EX_OK
78 except Exception: # pylint: disable=broad-except
79 self.__logger.exception("%s FAILED", self.project_name)
80 self.stop_time = time.time()
84 class BashFeature(Feature):
85 """Class designed to run any bash command."""
87 __logger = logging.getLogger(__name__)
89 def __init__(self, **kwargs):
90 super(BashFeature, self).__init__(**kwargs)
91 self.result_file = "{}/{}.log".format(self.res_dir, self.case_name)
93 def execute(self, **kwargs):
94 """Execute the cmd passed as arg
97 kwargs: Arbitrary keyword arguments.
105 console = kwargs["console"] if "console" in kwargs else False
106 if not os.path.isdir(self.res_dir):
107 os.makedirs(self.res_dir)
108 with open(self.result_file, 'w') as f_stdout:
109 self.__logger.info("Calling %s", cmd)
110 process = subprocess.Popen(
111 cmd, shell=True, stdout=subprocess.PIPE,
112 stderr=subprocess.STDOUT)
113 for line in iter(process.stdout.readline, b''):
115 sys.stdout.write(line.decode("utf-8"))
116 f_stdout.write(line.decode("utf-8"))
118 with open(self.result_file, 'r') as f_stdin:
119 self.__logger.debug("$ %s\n%s", cmd, f_stdin.read().rstrip())
120 return process.returncode
122 self.__logger.error("Please give cmd as arg. kwargs: %s", kwargs)