• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2#
3#   Copyright 2018 - The Android Open Source Project
4#
5#   Licensed under the Apache License, Version 2.0 (the "License");
6#   you may not use this file except in compliance with the License.
7#   You may obtain a copy of the License at
8#
9#       http://www.apache.org/licenses/LICENSE-2.0
10#
11#   Unless required by applicable law or agreed to in writing, software
12#   distributed under the License is distributed on an "AS IS" BASIS,
13#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14#   See the License for the specific language governing permissions and
15#   limitations under the License.
16import argparse
17
18import sys
19
20from acts import utils
21from acts.config.config_entry_meta import ConfigEntryMeta
22from acts.config.config_sources.config_source import ConfigSource
23
24
25class CliConfigSource(ConfigSource):
26    """A class that handles obtaining configs passed in through the CLI."""
27
28    def gather_configs(self, config_entry_metas):
29        """Initializes the list of inputs so that they can be queried.
30
31        Args:
32            config_entry_metas: A list of ConfigEntryMetas to fetch inputs for.
33
34        Returns:
35            A dict of {config_key: value}
36        """
37        parser = argparse.ArgumentParser(
38            description='Specify tests to run. If nothing specified, '
39                        'run all test cases found.')
40        self._add_arguments(parser, config_entry_metas)
41        args = sys.argv[1:]
42        # Note: parse_args() can generate a SystemExit error if the arguments
43        #       parsed are invalid or malformatted.
44        namespace = parser.parse_args(args)
45        return utils.dict_purge_key_if_value_is_none(dict(vars(namespace)))
46
47    def _add_arguments(self, parser, config_entry_metas):
48        for entry in config_entry_metas:
49            if entry.cli_flags is not None:
50                parser.add_argument(*entry.cli_flags,
51                                    **self._get_cli_kwargs(entry))
52
53    @classmethod
54    def _get_cli_kwargs(cls, config_entry_meta):
55        """Returns a dict of kwargs needed for ArgumentParser.add_argument().
56
57        Args:
58            config_entry_meta: The entry to generate add_argument() kwargs for.
59        """
60        kwarg_dict = {}
61        for attr_name in ConfigEntryMeta.cli_kwarg_attributes:
62            kwarg = ConfigEntryMeta.attr_to_cli_kwarg(attr_name)
63            value = getattr(config_entry_meta, attr_name, None)
64            kwarg_dict[kwarg] = value
65        return utils.dict_purge_key_if_value_is_none(kwarg_dict)
66