~3v1n0/unity/overlay-border-scale

« back to all changes in this revision

Viewing changes to tools/autopilot

  • Committer: Daniel van Vugt
  • Date: 2012-03-14 06:24:18 UTC
  • mfrom: (2108 unity)
  • mto: This revision was merged to the branch mainline in revision 2146.
  • Revision ID: daniel.van.vugt@canonical.com-20120314062418-nprucpbr0m7qky5e
MergedĀ latestĀ lp:unity

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/env python
2
2
 
 
3
from imp import find_module
3
4
import os
 
5
import os.path
4
6
import sys
5
 
import junitxml
 
7
from textwrap import dedent
6
8
from argparse import ArgumentParser
7
9
from unittest.loader import TestLoader
8
10
from unittest.runner import TextTestRunner
9
11
 
 
12
 
 
13
# list autopilot depends here, with the form:
 
14
# ('python module name', 'ubuntu package name'),
 
15
DEPENDS = [
 
16
    ('compizconfig', 'python-compizconfig'),
 
17
    ('dbus', 'python-dbus'),
 
18
    ('gobject', 'python-gobject'),
 
19
    ('gtk', 'python-gtk2'),
 
20
    ('ibus', 'python-ibus'),
 
21
    ('junitxml', 'python-junitxml'),
 
22
    ('testscenarios', 'python-testscenarios'),
 
23
    ('testtools', 'python-testtools'),
 
24
    ('xdg', 'python-xdg'),
 
25
    ('Xlib', 'python-xlib'),
 
26
]
 
27
 
 
28
 
 
29
def check_depends():
 
30
    """Check for required dependancies, and print a helpful message if any are
 
31
    missing.
 
32
 
 
33
    If all required modules are present, return True, False otherwise.
 
34
    """
 
35
    missing = []
 
36
    for module_name, package_name in DEPENDS:
 
37
        try:
 
38
            find_module(module_name)
 
39
        except ImportError:
 
40
            missing.append(package_name)
 
41
    if missing:
 
42
        print dedent("""\
 
43
            You are missing one or more packages required to run autopilot. They
 
44
            are:
 
45
 
 
46
            %s
 
47
 
 
48
            Please install these packages and re-run this script.
 
49
            """ % (' '.join(missing))
 
50
            )
 
51
        return False
 
52
    return True
 
53
 
 
54
 
 
55
def ensure_autopilot_is_importable():
 
56
    """Patch sys.path with the local autopilot directory if it's not already
 
57
    importable.
 
58
    """
 
59
    try:
 
60
        find_module("autopilot")
 
61
    except ImportError:
 
62
        ap_dir = os.path.join(os.path.dirname(__file__),
 
63
            "../tests/autopilot")
 
64
        ap_dir = os.path.realpath(ap_dir)
 
65
        sys.path.append(ap_dir)
 
66
        print "Patching sys.path to include local autopilot folder '%s'\n" % ap_dir
 
67
 
 
68
 
 
69
def parse_arguments():
 
70
    """Parse command-line arguments, and return an argparse arguments object."""
 
71
    parser = ArgumentParser(description="Autopilot test-runner")
 
72
    subparsers = parser.add_subparsers(help='Run modes', dest="mode")
 
73
 
 
74
    parser_run = subparsers.add_parser('run', help="Run autopilot tests")
 
75
    parser_run.add_argument('-o', "--output", required=False,
 
76
        help='Write test result report to file. Defaults to stdout')
 
77
    parser_run.add_argument('-f', "--format", choices=['text', 'xml'], default='text',
 
78
        required=False, help='Specify desired output format. Default is "text".')
 
79
    parser_run.add_argument('-r', '--record', action='store_true', default=False,
 
80
        required=False, help="Record failing tests. Required 'recordmydesktop' app to be installed. Videos \
 
81
        are stored in /tmp/autopilot.")
 
82
    parser_run.add_argument("-rd", "--record-directory", required=False,
 
83
        default="/tmp/autopilot", type=str, help="Directory to put recorded tests (only if -r) specified.")
 
84
    parser_run.add_argument("test", nargs="*", help="Specify tests to run, as listed by the 'list' command")
 
85
 
 
86
 
 
87
    parser_list = subparsers.add_parser('list', help="List autopilot tests")
 
88
    args = parser.parse_args()
 
89
 
 
90
    return args
 
91
 
 
92
 
 
93
def list_tests():
 
94
    """Print a list of tests we find inside autopilot.tests."""
 
95
    num_tests = 0
 
96
    from testtools import iterate_tests
 
97
    loader = TestLoader()
 
98
    test_suite = loader.discover('autopilot.tests')
 
99
    print "Listing all autopilot tests:"
 
100
    print
 
101
    for test in iterate_tests(test_suite):
 
102
        has_scenarios = hasattr(test, "scenarios")
 
103
        if has_scenarios:
 
104
            num_tests += len(test.scenarios)
 
105
            print " *%d %s" % (len(test.scenarios), test.id())
 
106
        else:
 
107
            num_tests += 1
 
108
            print test.id()
 
109
    print "\n %d total tests." % (num_tests)
 
110
 
 
111
 
 
112
def run_tests(args):
 
113
    """Run tests, using input from `args`."""
 
114
    import junitxml
 
115
    import autopilot.globals
 
116
 
 
117
    if args.record:
 
118
        autopilot.globals.video_recording_enabled = True
 
119
        autopilot.globals.video_record_directory = args.record_directory
 
120
 
 
121
    loader = TestLoader()
 
122
    if args.test:
 
123
        test_suite = loader.loadTestsFromNames(args.test)
 
124
    else:
 
125
        test_suite = loader.discover('autopilot.tests')
 
126
 
 
127
    if args.output == None:
 
128
        results_stream = sys.stdout
 
129
    else:
 
130
        try:
 
131
            path = os.path.dirname(args.output)
 
132
            if path != '' and not os.path.exists(path):
 
133
                os.makedirs(path)
 
134
            results_stream = open(args.output, 'w')
 
135
        except:
 
136
            results_stream = sys.stdout
 
137
    if args.format == "xml":
 
138
        result = junitxml.JUnitXmlResult(results_stream)
 
139
        result.startTestRun()
 
140
        test_suite.run(result)
 
141
        result.stopTestRun()
 
142
        results_stream.close()
 
143
        if not result.wasSuccessful:
 
144
            exit(1)
 
145
    elif args.format == "text":
 
146
        runner = TextTestRunner(stream=results_stream)
 
147
        success = runner.run(test_suite).wasSuccessful()
 
148
        if not success:
 
149
            exit(1)
 
150
 
 
151
def main():
 
152
    args = parse_arguments()
 
153
    if args.mode == 'list':
 
154
        list_tests()
 
155
    elif args.mode == 'run':
 
156
        run_tests(args)
 
157
 
10
158
if __name__ == "__main__":
11
 
        parser = ArgumentParser()
12
 
        parser.add_argument('-o', "--output", required=False, help='Write test result report to file. Defaults to stdout')
13
 
        args = parser.parse_args()
14
 
 
15
 
        if args.output == None:
16
 
                results_stream = sys.stdout
17
 
        else:
18
 
                path = os.path.dirname(args.output)
19
 
                if not (os.path.exists(path) or path==''):
20
 
                        os.makedirs(path)
21
 
                results_stream = open(args.output, 'w')
22
 
 
23
 
        loader = TestLoader()
24
 
        result = junitxml.JUnitXmlResult(results_stream)
25
 
        result.startTestRun()
26
 
        test_suite = loader.discover('autopilot.tests')
27
 
        test_suite.run(result)
28
 
        result.stopTestRun()
29
 
        results_stream.close()
 
159
    if not check_depends():
 
160
        exit(1)
 
161
    ensure_autopilot_is_importable()
 
162
    main()