aboutsummaryrefslogtreecommitdiff
path: root/tools/gyp/test_gyp.py
blob: 382e75272d8b6b1d564828271871cdc034d6cc21 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""gyptest.py -- test runner for GYP tests."""

from __future__ import print_function

import argparse
import os
import platform
import subprocess
import sys
import time


def is_test_name(f):
    return f.startswith("gyptest") and f.endswith(".py")


def find_all_gyptest_files(directory):
    result = []
    for root, dirs, files in os.walk(directory):
        result.extend([os.path.join(root, f) for f in files if is_test_name(f)])
    result.sort()
    return result


def main(argv=None):
    if argv is None:
        argv = sys.argv

    parser = argparse.ArgumentParser()
    parser.add_argument("-a", "--all", action="store_true", help="run all tests")
    parser.add_argument("-C", "--chdir", action="store", help="change to directory")
    parser.add_argument(
        "-f",
        "--format",
        action="store",
        default="",
        help="run tests with the specified formats",
    )
    parser.add_argument(
        "-G",
        "--gyp_option",
        action="append",
        default=[],
        help="Add -G options to the gyp command line",
    )
    parser.add_argument(
        "-l", "--list", action="store_true", help="list available tests and exit"
    )
    parser.add_argument(
        "-n",
        "--no-exec",
        action="store_true",
        help="no execute, just print the command line",
    )
    parser.add_argument(
        "--path", action="append", default=[], help="additional $PATH directory"
    )
    parser.add_argument(
        "-q",
        "--quiet",
        action="store_true",
        help="quiet, don't print anything unless there are failures",
    )
    parser.add_argument(
        "-v",
        "--verbose",
        action="store_true",
        help="print configuration info and test results.",
    )
    parser.add_argument("tests", nargs="*")
    args = parser.parse_args(argv[1:])

    if args.chdir:
        os.chdir(args.chdir)

    if args.path:
        extra_path = [os.path.abspath(p) for p in args.path]
        extra_path = os.pathsep.join(extra_path)
        os.environ["PATH"] = extra_path + os.pathsep + os.environ["PATH"]

    if not args.tests:
        if not args.all:
            sys.stderr.write("Specify -a to get all tests.\n")
            return 1
        args.tests = ["test"]

    tests = []
    for arg in args.tests:
        if os.path.isdir(arg):
            tests.extend(find_all_gyptest_files(os.path.normpath(arg)))
        else:
            if not is_test_name(os.path.basename(arg)):
                print(arg, "is not a valid gyp test name.", file=sys.stderr)
                sys.exit(1)
            tests.append(arg)

    if args.list:
        for test in tests:
            print(test)
        sys.exit(0)

    os.environ["PYTHONPATH"] = os.path.abspath("test/lib")

    if args.verbose:
        print_configuration_info()

    if args.gyp_option and not args.quiet:
        print("Extra Gyp options: %s\n" % args.gyp_option)

    if args.format:
        format_list = args.format.split(",")
    else:
        format_list = {
            "aix5": ["make"],
            "freebsd7": ["make"],
            "freebsd8": ["make"],
            "openbsd5": ["make"],
            "cygwin": ["msvs"],
            "win32": ["msvs", "ninja"],
            "linux": ["make", "ninja"],
            "linux2": ["make", "ninja"],
            "linux3": ["make", "ninja"],
            # TODO: Re-enable xcode-ninja.
            # https://bugs.chromium.org/p/gyp/issues/detail?id=530
            # 'darwin':   ['make', 'ninja', 'xcode', 'xcode-ninja'],
            "darwin": ["make", "ninja", "xcode"],
        }[sys.platform]

    gyp_options = []
    for option in args.gyp_option:
        gyp_options += ["-G", option]

    runner = Runner(format_list, tests, gyp_options, args.verbose)
    runner.run()

    if not args.quiet:
        runner.print_results()

    if runner.failures:
        return 1
    else:
        return 0


def print_configuration_info():
    print("Test configuration:")
    if sys.platform == "darwin":
        sys.path.append(os.path.abspath("test/lib"))
        import TestMac

        print("  Mac %s %s" % (platform.mac_ver()[0], platform.mac_ver()[2]))
        print("  Xcode %s" % TestMac.Xcode.Version())
    elif sys.platform == "win32":
        sys.path.append(os.path.abspath("pylib"))
        import gyp.MSVSVersion

        print("  Win %s %s\n" % platform.win32_ver()[0:2])
        print("  MSVS %s" % gyp.MSVSVersion.SelectVisualStudioVersion().Description())
    elif sys.platform in ("linux", "linux2"):
        print("  Linux %s" % " ".join(platform.linux_distribution()))
    print("  Python %s" % platform.python_version())
    print("  PYTHONPATH=%s" % os.environ["PYTHONPATH"])
    print()


class Runner(object):
    def __init__(self, formats, tests, gyp_options, verbose):
        self.formats = formats
        self.tests = tests
        self.verbose = verbose
        self.gyp_options = gyp_options
        self.failures = []
        self.num_tests = len(formats) * len(tests)
        num_digits = len(str(self.num_tests))
        self.fmt_str = "[%%%dd/%%%dd] (%%s) %%s" % (num_digits, num_digits)
        self.isatty = sys.stdout.isatty() and not self.verbose
        self.env = os.environ.copy()
        self.hpos = 0

    def run(self):
        run_start = time.time()

        i = 1
        for fmt in self.formats:
            for test in self.tests:
                self.run_test(test, fmt, i)
                i += 1

        if self.isatty:
            self.erase_current_line()

        self.took = time.time() - run_start

    def run_test(self, test, fmt, i):
        if self.isatty:
            self.erase_current_line()

        msg = self.fmt_str % (i, self.num_tests, fmt, test)
        self.print_(msg)

        start = time.time()
        cmd = [sys.executable, test] + self.gyp_options
        self.env["TESTGYP_FORMAT"] = fmt
        proc = subprocess.Popen(
            cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=self.env
        )
        proc.wait()
        took = time.time() - start

        stdout = proc.stdout.read().decode("utf8")
        if proc.returncode == 2:
            res = "skipped"
        elif proc.returncode:
            res = "failed"
            self.failures.append("(%s) %s" % (test, fmt))
        else:
            res = "passed"
        res_msg = " %s %.3fs" % (res, took)
        self.print_(res_msg)

        if (
            stdout
            and not stdout.endswith("PASSED\n")
            and not (stdout.endswith("NO RESULT\n"))
        ):
            print()
            print("\n".join("    %s" % line for line in stdout.splitlines()))
        elif not self.isatty:
            print()

    def print_(self, msg):
        print(msg, end="")
        index = msg.rfind("\n")
        if index == -1:
            self.hpos += len(msg)
        else:
            self.hpos = len(msg) - index
        sys.stdout.flush()

    def erase_current_line(self):
        print("\b" * self.hpos + " " * self.hpos + "\b" * self.hpos, end="")
        sys.stdout.flush()
        self.hpos = 0

    def print_results(self):
        num_failures = len(self.failures)
        if num_failures:
            print()
            if num_failures == 1:
                print("Failed the following test:")
            else:
                print("Failed the following %d tests:" % num_failures)
            print("\t" + "\n\t".join(sorted(self.failures)))
            print()
        print(
            "Ran %d tests in %.3fs, %d failed."
            % (self.num_tests, self.took, num_failures)
        )
        print()


if __name__ == "__main__":
    sys.exit(main())