1from __future__ import print_function
2from __future__ import absolute_import
3
4# System modules
5import argparse
6import sys
7import multiprocessing
8import os
9import textwrap
10
11# Third-party modules
12
13# LLDB modules
14from . import configuration
15
16
17class ArgParseNamespace(object):
18    pass
19
20
21def parse_args(parser, argv):
22    """ Returns an argument object. LLDB_TEST_ARGUMENTS environment variable can
23        be used to pass additional arguments.
24    """
25    args = ArgParseNamespace()
26
27    if ('LLDB_TEST_ARGUMENTS' in os.environ):
28        print(
29            "Arguments passed through environment: '%s'" %
30            os.environ['LLDB_TEST_ARGUMENTS'])
31        args = parser.parse_args([sys.argv[0]].__add__(
32            os.environ['LLDB_TEST_ARGUMENTS'].split()), namespace=args)
33
34    return parser.parse_args(args=argv, namespace=args)
35
36
37def default_thread_count():
38    # Check if specified in the environment
39    num_threads_str = os.environ.get("LLDB_TEST_THREADS")
40    if num_threads_str:
41        return int(num_threads_str)
42    else:
43        return multiprocessing.cpu_count()
44
45
46def create_parser():
47    parser = argparse.ArgumentParser(
48        description='description',
49        prefix_chars='+-',
50        add_help=False)
51    group = None
52
53    # Helper function for boolean options (group will point to the current
54    # group when executing X)
55    X = lambda optstr, helpstr, **kwargs: group.add_argument(
56        optstr, help=helpstr, action='store_true', **kwargs)
57
58    group = parser.add_argument_group('Help')
59    group.add_argument(
60        '-h',
61        '--help',
62        dest='h',
63        action='store_true',
64        help="Print this help message and exit.  Add '-v' for more detailed help.")
65
66    # C and Python toolchain options
67    group = parser.add_argument_group('Toolchain options')
68    group.add_argument(
69        '-A',
70        '--arch',
71        metavar='arch',
72        dest='arch',
73        help=textwrap.dedent('''Specify the architecture(s) to test. This option can be specified more than once'''))
74    group.add_argument('-C', '--compiler', metavar='compiler', dest='compiler', help=textwrap.dedent(
75        '''Specify the compiler(s) used to build the inferior executables. The compiler path can be an executable basename or a full path to a compiler executable. This option can be specified multiple times.'''))
76    if sys.platform == 'darwin':
77        group.add_argument('--apple-sdk', metavar='apple_sdk', dest='apple_sdk', default="macosx", help=textwrap.dedent(
78            '''Specify the name of the Apple SDK (macosx, macosx.internal, iphoneos, iphoneos.internal, or path to SDK) and use the appropriate tools from that SDK's toolchain.'''))
79    # FIXME? This won't work for different extra flags according to each arch.
80    group.add_argument(
81        '-E',
82        metavar='extra-flags',
83        help=textwrap.dedent('''Specify the extra flags to be passed to the toolchain when building the inferior programs to be debugged
84                                                           suggestions: do not lump the "-A arch1 -A arch2" together such that the -E option applies to only one of the architectures'''))
85
86    # Test filtering options
87    group = parser.add_argument_group('Test filtering options')
88    group.add_argument(
89        '-f',
90        metavar='filterspec',
91        action='append',
92        help='Specify a filter, which consists of the test class name, a dot, followed by the test method, to only admit such test into the test suite')  # FIXME: Example?
93    X('-l', "Don't skip long running tests")
94    group.add_argument(
95        '-p',
96        metavar='pattern',
97        help='Specify a regexp filename pattern for inclusion in the test suite')
98    group.add_argument('--excluded', metavar='exclusion-file', action='append', help=textwrap.dedent(
99        '''Specify a file for tests to exclude. File should contain lists of regular expressions for test files or methods,
100                                with each list under a matching header (xfail files, xfail methods, skip files, skip methods)'''))
101    group.add_argument(
102        '-G',
103        '--category',
104        metavar='category',
105        action='append',
106        dest='categoriesList',
107        help=textwrap.dedent('''Specify categories of test cases of interest. Can be specified more than once.'''))
108    group.add_argument(
109        '--skip-category',
110        metavar='category',
111        action='append',
112        dest='skipCategories',
113        help=textwrap.dedent('''Specify categories of test cases to skip. Takes precedence over -G. Can be specified more than once.'''))
114
115    # Configuration options
116    group = parser.add_argument_group('Configuration options')
117    group.add_argument(
118        '--framework',
119        metavar='framework-path',
120        help='The path to LLDB.framework')
121    group.add_argument(
122        '--executable',
123        metavar='executable-path',
124        help='The path to the lldb executable')
125    group.add_argument(
126        '--server',
127        metavar='server-path',
128        help='The path to the debug server executable to use')
129    group.add_argument(
130        '-s',
131        metavar='name',
132        help='Specify the name of the dir created to store the session files of tests with errored or failed status. If not specified, the test driver uses the timestamp as the session dir name')
133    group.add_argument(
134        '-S',
135        '--session-file-format',
136        default=configuration.session_file_format,
137        metavar='format',
138        help='Specify session file name format.  See configuration.py for a description.')
139    group.add_argument(
140        '-y',
141        type=int,
142        metavar='count',
143        help="Specify the iteration count used to collect our benchmarks. An example is the number of times to do 'thread step-over' to measure stepping speed.")
144    group.add_argument(
145        '-#',
146        type=int,
147        metavar='sharp',
148        dest='sharp',
149        help='Repeat the test suite for a specified number of times')
150    group.add_argument('--channel', metavar='channel', dest='channels', action='append', help=textwrap.dedent(
151        "Specify the log channels (and optional categories) e.g. 'lldb all' or 'gdb-remote packets' if no categories are specified, 'default' is used"))
152    group.add_argument(
153        '--log-success',
154        dest='log_success',
155        action='store_true',
156        help="Leave logs/traces even for successful test runs (useful for creating reference log files during debugging.)")
157    group.add_argument(
158        '--codesign-identity',
159        metavar='Codesigning identity',
160        default='lldb_codesign',
161        help='The codesigning identity to use')
162    group.add_argument(
163        '--build-dir',
164        dest='test_build_dir',
165        metavar='Test build directory',
166        default='lldb-test-build.noindex',
167        help='The root build directory for the tests. It will be removed before running.')
168
169    # Configuration options
170    group = parser.add_argument_group('Remote platform options')
171    group.add_argument(
172        '--platform-name',
173        dest='lldb_platform_name',
174        metavar='platform-name',
175        help='The name of a remote platform to use')
176    group.add_argument(
177        '--platform-url',
178        dest='lldb_platform_url',
179        metavar='platform-url',
180        help='A LLDB platform URL to use when connecting to a remote platform to run the test suite')
181    group.add_argument(
182        '--platform-working-dir',
183        dest='lldb_platform_working_dir',
184        metavar='platform-working-dir',
185        help='The directory to use on the remote platform.')
186
187    # Test-suite behaviour
188    group = parser.add_argument_group('Runtime behaviour options')
189    X('-d', 'Suspend the process after launch to wait indefinitely for a debugger to attach')
190    X('-q', "Don't print extra output from this script.")
191    X('-t', 'Turn on tracing of lldb command and other detailed test executions')
192    group.add_argument(
193        '-u',
194        dest='unset_env_varnames',
195        metavar='variable',
196        action='append',
197        help='Specify an environment variable to unset before running the test cases. e.g., -u DYLD_INSERT_LIBRARIES -u MallocScribble')
198    group.add_argument(
199        '--env',
200        dest='set_env_vars',
201        metavar='variable',
202        action='append',
203        help='Specify an environment variable to set to the given value before running the test cases e.g.: --env CXXFLAGS=-O3 --env DYLD_INSERT_LIBRARIES')
204    X('-v', 'Do verbose mode of unittest framework (print out each test case invocation)')
205    group.add_argument(
206        '--enable-crash-dialog',
207        dest='disable_crash_dialog',
208        action='store_false',
209        help='(Windows only) When LLDB crashes, display the Windows crash dialog.')
210    group.set_defaults(disable_crash_dialog=True)
211
212    group = parser.add_argument_group('Parallel execution options')
213    group.add_argument(
214        '--inferior',
215        action='store_true',
216        help=('specify this invocation is a multiprocess inferior, '
217              'used internally'))
218    group.add_argument(
219        '--no-multiprocess',
220        action='store_true',
221        help='skip running the multiprocess test runner')
222    group.add_argument(
223        '--threads',
224        type=int,
225        dest='num_threads',
226        default=default_thread_count(),
227        help=('The number of threads/processes to use when running tests '
228              'separately, defaults to the number of CPU cores available'))
229    group.add_argument(
230        '--test-subdir',
231        action='store',
232        help='Specify a test subdirectory to use relative to the test root dir'
233    )
234    group.add_argument(
235        '--test-runner-name',
236        action='store',
237        help=('Specify a test runner strategy.  Valid values: multiprocessing,'
238              ' multiprocessing-pool, serial, threading, threading-pool')
239    )
240
241    # Test results support.
242    group = parser.add_argument_group('Test results options')
243    group.add_argument(
244        '--curses',
245        action='store_true',
246        help='Shortcut for specifying test results using the curses formatter')
247    group.add_argument(
248        '--results-file',
249        action='store',
250        help=('Specifies the file where test results will be written '
251              'according to the results-formatter class used'))
252    group.add_argument(
253        '--results-port',
254        action='store',
255        type=int,
256        help=('Specifies the localhost port to which the results '
257              'formatted output should be sent'))
258    group.add_argument(
259        '--results-formatter',
260        action='store',
261        help=('Specifies the full package/module/class name used to translate '
262              'test events into some kind of meaningful report, written to '
263              'the designated output results file-like object'))
264    group.add_argument(
265        '--results-formatter-option',
266        '-O',
267        action='append',
268        dest='results_formatter_options',
269        help=('Specify an option to pass to the formatter. '
270              'Use --results-formatter-option="--option1=val1" '
271              'syntax.  Note the "=" is critical, don\'t include whitespace.'))
272    group.add_argument(
273        '--event-add-entries',
274        action='store',
275        help=('Specify comma-separated KEY=VAL entries to add key and value '
276              'pairs to all test events generated by this test run.  VAL may '
277              'be specified as VAL:TYPE, where TYPE may be int to convert '
278              'the value to an int'))
279
280    # Re-run related arguments
281    group = parser.add_argument_group('Test Re-run Options')
282    group.add_argument(
283        '--rerun-all-issues',
284        action='store_true',
285        help=('Re-run all issues that occurred during the test run '
286              'irrespective of the test method\'s marking as flakey. '
287              'Default behavior is to apply re-runs only to flakey '
288              'tests that generate issues.'))
289    group.add_argument(
290        '--rerun-max-file-threshold',
291        action='store',
292        type=int,
293        default=50,
294        help=('Maximum number of files requiring a rerun beyond '
295              'which the rerun will not occur.  This is meant to '
296              'stop a catastrophically failing test suite from forcing '
297              'all tests to be rerun in the single-worker phase.'))
298
299    # Remove the reference to our helper function
300    del X
301
302    group = parser.add_argument_group('Test directories')
303    group.add_argument(
304        'args',
305        metavar='test-dir',
306        nargs='*',
307        help='Specify a list of directory names to search for test modules named after Test*.py (test discovery). If empty, search from the current working directory instead.')
308
309    return parser
310