~laney/autopilot/legacy-psutil-children

« back to all changes in this revision

Viewing changes to autopilot/__init__.py

  • Committer: Thomi Richards
  • Date: 2014-04-10 20:41:43 UTC
  • mfrom: (479 autopilot)
  • mto: This revision was merged to the branch mainline in revision 480.
  • Revision ID: thomi.richards@canonical.com-20140410204143-5a7znkjdjcoc7gxj
Merged trunk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
18
#
19
19
 
20
 
from argparse import ArgumentParser, REMAINDER, Action
21
 
import subprocess
22
 
 
23
 
from autopilot._debug import (
24
 
    get_all_debug_profiles,
25
 
    get_default_debug_profile,
26
 
)
27
 
from autopilot.testresult import get_output_formats, get_default_format
28
 
from autopilot.exceptions import BackendException
29
 
 
30
 
version = '1.4.0'
31
 
 
32
 
 
33
 
def parse_arguments(argv=None):
34
 
    """Parse command-line arguments, and return an argparse arguments
35
 
    object.
36
 
    """
37
 
    parser = ArgumentParser(
38
 
        description="Autopilot test tool.",
39
 
        epilog="Each command (run, list, launch etc.) has additional help that"
40
 
        " can be viewed by passing the '-h' flag to the command. For "
41
 
        "example: 'autopilot run -h' displays further help for the "
42
 
        "'run' command."
43
 
    )
44
 
    parser.add_argument('-v', '--version', action='version',
45
 
                        version=get_version_string(),
46
 
                        help="Display autopilot version and exit.")
47
 
    subparsers = parser.add_subparsers(help='Run modes', dest="mode")
48
 
 
49
 
    parser_run = subparsers.add_parser('run', help="Run autopilot tests")
50
 
    parser_run.add_argument('-o', "--output", required=False,
51
 
                            help='Write test result report to file.\
52
 
                            Defaults to stdout.\
53
 
                            If given a directory instead of a file will \
54
 
                            write to a file in that directory named: \
55
 
                            <hostname>_<dd.mm.yyy_HHMMSS>.log')
56
 
    available_formats = get_output_formats().keys()
57
 
    parser_run.add_argument('-f', "--format", choices=available_formats,
58
 
                            default=get_default_format(),
59
 
                            required=False,
60
 
                            help='Specify desired output format. \
61
 
                            Default is "text".')
62
 
    parser_run.add_argument("-ff", "--failfast", action='store_true',
63
 
                            required=False, default=False,
64
 
                            help="Stop the test run on the first error \
65
 
                            or failure.")
66
 
    parser_run.add_argument('-r', '--record', action='store_true',
67
 
                            default=False, required=False,
68
 
                            help="Record failing tests. Required \
69
 
                            'recordmydesktop' app to be installed.\
70
 
                            Videos are stored in /tmp/autopilot.")
71
 
    parser_run.add_argument("-rd", "--record-directory", required=False,
72
 
                            type=str, help="Directory to put recorded tests")
73
 
    parser_run.add_argument("--record-options", required=False,
74
 
                            type=str, help="Comma separated list of options \
75
 
                            to pass to recordmydesktop")
76
 
    parser_run.add_argument("-ro", "--random-order", action='store_true',
77
 
                            required=False, default=False,
78
 
                            help="Run the tests in random order")
79
 
    parser_run.add_argument(
80
 
        '-v', '--verbose', default=False, required=False, action='count',
81
 
        help="If set, autopilot will output test log data to stderr during a "
82
 
        "test run. Set twice to also log data useful for debugging autopilot "
83
 
        "itself.")
84
 
    parser_run.add_argument(
85
 
        "--debug-profile",
86
 
        choices=[p.name for p in get_all_debug_profiles()],
87
 
        default=get_default_debug_profile().name,
88
 
        help="Select a profile for what additional debugging information "
89
 
        "should be attached to failed test results."
90
 
    )
91
 
    parser_run.add_argument(
92
 
        "--timeout-profile",
93
 
        choices=['normal', 'long'],
94
 
        default='normal',
95
 
        help="Alter the timeout values Autopilot uses. Selecting 'long' will "
96
 
        "make autopilot use longer timeouts for various polling loops. This "
97
 
        "useful if autopilot is running on very slow hardware"
98
 
    )
99
 
    parser_run.add_argument("suite", nargs="+",
100
 
                            help="Specify test suite(s) to run.")
101
 
 
102
 
    parser_list = subparsers.add_parser('list', help="List autopilot tests")
103
 
    parser_list.add_argument(
104
 
        "-ro", "--run-order", required=False, default=False,
105
 
        action="store_true",
106
 
        help="List tests in run order, rather than alphabetical order (the "
107
 
        "default).")
108
 
    parser_list.add_argument(
109
 
        "--suites", required=False, action='store_true',
110
 
        help="Lists only available suites, not tests contained within the "
111
 
        "suite.")
112
 
    parser_list.add_argument("suite", nargs="+",
113
 
                             help="Specify test suite(s) to run.")
114
 
 
115
 
    if have_vis():
116
 
        parser_vis = subparsers.add_parser(
117
 
            'vis', help="Open the Autopilot visualiser tool")
118
 
        parser_vis.add_argument(
119
 
            '-v', '--verbose', required=False, default=False, action='count',
120
 
            help="Show autopilot log messages. Set twice to also log data "
121
 
            "useful for debugging autopilot itself.")
122
 
        parser_vis.add_argument(
123
 
            '-testability', required=False, default=False,
124
 
            action='store_true', help="Start the vis tool in testability "
125
 
            "mode. Used for self-tests only."
126
 
        )
127
 
        parser_vis.add_argument(
128
 
            '--enable-profile', required=False, default=False,
129
 
            action="store_true", help="Enable "
130
 
            "collection of profile data for vis itself. If enabled, profile "
131
 
            "data will be stored in 'vis_tool.profile' in the current "
132
 
            "working directory."
133
 
        )
134
 
 
135
 
    parser_launch = subparsers.add_parser(
136
 
        'launch', help="Launch an application with introspection enabled")
137
 
    parser_launch.add_argument(
138
 
        '-i', '--interface', choices=('Gtk', 'Qt', 'Auto'), default='Auto',
139
 
        help="Specify which introspection interface to load. The default"
140
 
        "('Auto') uses ldd to try and detect which interface to load.")
141
 
    parser_launch.add_argument(
142
 
        '-v', '--verbose', required=False, default=False, action='count',
143
 
        help="Show autopilot log messages. Set twice to also log data useful "
144
 
        "for debugging autopilot itself.")
145
 
    parser_launch.add_argument(
146
 
        'application', action=_OneOrMoreArgumentStoreAction, type=str,
147
 
        nargs=REMAINDER,
148
 
        help="The application to launch. Can be a full path, or just an "
149
 
        "application name (in which case Autopilot will search for it in "
150
 
        "$PATH).")
151
 
    args = parser.parse_args(args=argv)
152
 
 
153
 
    # TR - 2013-11-27 - a bug in python3.3 means argparse doesn't fail
154
 
    # correctly when no commands are specified.
155
 
    # http://bugs.python.org/issue16308
156
 
    if args.mode is None:
157
 
        parser.error("too few arguments")
158
 
 
159
 
    if 'suite' in args:
160
 
        args.suite = [suite.rstrip('/') for suite in args.suite]
161
 
 
162
 
    return args
163
 
 
164
 
 
165
 
class _OneOrMoreArgumentStoreAction(Action):
166
 
 
167
 
    def __call__(self,  parser, namespace, values, option_string=None):
168
 
        if len(values) == 0:
169
 
            parser.error(
170
 
                "Must specify at least one argument to the 'launch' command")
171
 
        setattr(namespace, self.dest, values)
172
 
 
173
 
 
174
 
def have_vis():
175
 
    """Return true if the vis package is installed."""
176
 
    try:
177
 
        from autopilot.vis import vis_main  # flake8: noqa
178
 
        return True
179
 
    except ImportError:
180
 
        return False
181
 
 
182
 
 
183
 
def get_version_string():
184
 
    """Return the autopilot source and package versions."""
185
 
    version_string = "Autopilot Source Version: " + _get_source_version()
186
 
    pkg_version = _get_package_version()
187
 
    if pkg_version:
188
 
        version_string += "\nAutopilot Package Version: " + pkg_version
189
 
    return version_string
190
 
 
191
 
 
192
 
def _get_source_version():
193
 
    return version
194
 
 
195
 
 
196
 
def _get_package_version():
197
 
    """Get the version of the currently installed package version, or None.
198
 
 
199
 
    Only returns the package version if the package is installed, *and* we seem
200
 
    to be running the system-wide installed code.
201
 
    """
202
 
    if _running_in_system():
203
 
        return _get_package_installed_version()
204
 
    return None
205
 
 
206
 
 
207
 
def _running_in_system():
208
 
    """Return True if we're running autopilot from the system installation
209
 
    dir."""
210
 
    return __file__.startswith('/usr/')
211
 
 
212
 
 
213
 
def _get_package_installed_version():
214
 
    """Get the version string of the system-wide installed package, or None if
215
 
    it is not installed.
216
 
 
217
 
    """
218
 
    try:
219
 
        return subprocess.check_output(
220
 
            [
221
 
                "dpkg-query",
222
 
                "--showformat",
223
 
                "${Version}",
224
 
                "--show",
225
 
                "python-autopilot",
226
 
            ],
227
 
            universal_newlines=True
228
 
        ).strip()
229
 
    except subprocess.CalledProcessError:
230
 
        return None
 
20
from autopilot._info import get_version_string, have_vis, version
 
21
 
 
22
__all__ = [
 
23
    'get_version_string',
 
24
    'have_vis',
 
25
    'version',
 
26
]