1# Copyright 2018, The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""
16SUITE Tradefed test runner class.
17"""
18
19import copy
20import logging
21
22import atest_utils
23import constants
24
25from test_runners import atest_tf_test_runner
26
27class SuitePlanTestRunner(atest_tf_test_runner.AtestTradefedTestRunner):
28    """Suite Plan Test Runner class."""
29    NAME = 'SuitePlanTestRunner'
30    EXECUTABLE = '%s-tradefed'
31    _RUN_CMD = ('{exe} run commandAndExit {test} {args}')
32
33    def __init__(self, results_dir, **kwargs):
34        """Init stuff for suite tradefed runner class."""
35        super(SuitePlanTestRunner, self).__init__(results_dir, **kwargs)
36        self.run_cmd_dict = {'exe': '',
37                             'test': '',
38                             'args': ''}
39
40    def get_test_runner_build_reqs(self):
41        """Return the build requirements.
42
43        Returns:
44            Set of build targets.
45        """
46        build_req = set()
47        build_req |= super(SuitePlanTestRunner,
48                           self).get_test_runner_build_reqs()
49        return build_req
50
51    def run_tests(self, test_infos, extra_args, reporter):
52        """Run the list of test_infos.
53        Args:
54            test_infos: List of TestInfo.
55            extra_args: Dict of extra args to add to test run.
56            reporter: An instance of result_report.ResultReporter.
57
58        Returns:
59            Return code of the process for running tests.
60        """
61        reporter.register_unsupported_runner(self.NAME)
62        run_cmds = self.generate_run_commands(test_infos, extra_args)
63        ret_code = constants.EXIT_CODE_SUCCESS
64        for run_cmd in run_cmds:
65            proc = super(SuitePlanTestRunner, self).run(run_cmd,
66                                                        output_to_stdout=True)
67            ret_code |= self.wait_for_subprocess(proc)
68        return ret_code
69
70    def _parse_extra_args(self, extra_args):
71        """Convert the extra args into something *ts-tf can understand.
72
73        We want to transform the top-level args from atest into specific args
74        that *ts-tradefed supports. The only arg we take as is
75        EXTRA_ARG since that is what the user intentionally wants to pass to
76        the test runner.
77
78        Args:
79            extra_args: Dict of args
80
81        Returns:
82            List of args to append.
83        """
84        args_to_append = []
85        args_not_supported = []
86        for arg in extra_args:
87            if constants.SERIAL == arg:
88                args_to_append.append('--serial')
89                args_to_append.append(extra_args[arg])
90                continue
91            if constants.CUSTOM_ARGS == arg:
92                args_to_append.extend(extra_args[arg])
93                continue
94            if constants.DRY_RUN == arg:
95                continue
96            args_not_supported.append(arg)
97        if args_not_supported:
98            logging.info('%s does not support the following args: %s',
99                         self.EXECUTABLE, args_not_supported)
100        return args_to_append
101
102    # pylint: disable=arguments-differ
103    def generate_run_commands(self, test_infos, extra_args):
104        """Generate a list of run commands from TestInfos.
105
106        Args:
107            test_infos: List of TestInfo tests to run.
108            extra_args: Dict of extra args to add to test run.
109
110        Returns:
111            A List of strings that contains the run command
112            which *ts-tradefed supports.
113        """
114        cmds = []
115        args = []
116        args.extend(self._parse_extra_args(extra_args))
117        args.extend(atest_utils.get_result_server_args())
118        for test_info in test_infos:
119            cmd_dict = copy.deepcopy(self.run_cmd_dict)
120            cmd_dict['test'] = test_info.test_name
121            cmd_dict['args'] = ' '.join(args)
122            cmd_dict['exe'] = self.EXECUTABLE % test_info.suite
123            cmds.append(self._RUN_CMD.format(**cmd_dict))
124        return cmds
125