1#!/usr/bin/env python
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.
16
17"""Atest Argument Parser class for atest."""
18
19import argparse
20
21from atest import bazel_mode
22from atest import constants
23from atest.atest_utils import BuildOutputMode
24
25
26def _output_mode_msg() -> str:
27  """Generate helper strings for BuildOutputMode."""
28  msg = []
29  for _, value in BuildOutputMode.__members__.items():
30    if value == BuildOutputMode.STREAMED:
31      msg.append(
32          f'\t\t{BuildOutputMode.STREAMED.value}: '
33          'full output like what "m" does. (default)'
34      )
35    elif value == BuildOutputMode.LOGGED:
36      msg.append(
37          f'\t\t{BuildOutputMode.LOGGED.value}: '
38          'print build output to a log file.'
39      )
40    else:
41      raise RuntimeError('Found unknown attribute!')
42  return '\n'.join(msg)
43
44
45def _positive_int(value):
46  """Verify value by whether or not a positive integer.
47
48  Args:
49      value: A string of a command-line argument.
50
51  Returns:
52      int of value, if it is a positive integer.
53      Otherwise, raise argparse.ArgumentTypeError.
54  """
55  err_msg = "invalid positive int value: '%s'" % value
56  try:
57    converted_value = int(value)
58    if converted_value < 1:
59      raise argparse.ArgumentTypeError(err_msg)
60    return converted_value
61  except ValueError as value_err:
62    raise argparse.ArgumentTypeError(err_msg) from value_err
63
64
65def create_atest_arg_parser():
66  """Creates an instance of the default Atest arg parser."""
67
68  parser = argparse.ArgumentParser(
69      description=_HELP_DESCRIPTION,
70      add_help=True,
71      formatter_class=argparse.RawDescriptionHelpFormatter,
72  )
73
74  parser.add_argument('tests', nargs='*', help='Tests to build and/or run.')
75
76  parser.add_argument(
77      '--minimal-build',
78      action=argparse.BooleanOptionalAction,
79      default=True,
80      help=(
81          'Build required dependencies only (default: True). Use'
82          ' --no-minimal-build to disable it.'
83      ),
84  )
85  parser.add_argument(
86      '--update-device',
87      action='store_true',
88      help=(
89          'Build and deploy your changes to the device. By default, ATest'
90          ' will build `sync` and use `adevice` to update the device. '
91          'Note, this feature currently only works for incremental device '
92          'updates and not after a repo sync. Please flash the device after a '
93          'repo sync.'
94      ),
95  )
96  parser.add_argument(
97      '--update:modules',
98      dest='update_modules',
99      type=lambda value: value.split(','),
100      help=(
101          'Modules that are built if the device is being updated. '
102          'Modules should be separated by comma.'
103      ),
104  )
105
106  parser.add_argument(
107      '-a',
108      '--all-abi',
109      action='store_true',
110      help='Set to run tests for all ABIs (Application Binary Interfaces).',
111  )
112  parser.add_argument(
113      '-b',
114      '--build',
115      action='append_const',
116      dest='steps',
117      const=constants.BUILD_STEP,
118      help='Run a build.',
119  )
120  parser.add_argument(
121      '--bazel-mode',
122      default=True,
123      action='store_true',
124      help='Run tests using Bazel (default: True).',
125  )
126  parser.add_argument(
127      '--no-bazel-mode',
128      dest='bazel_mode',
129      action='store_false',
130      help='Run tests without using Bazel.',
131  )
132  parser.add_argument(
133      '--bazel-arg',
134      nargs='*',
135      action='append',
136      help=(
137          'Forward a flag to Bazel for tests executed with Bazel; see'
138          ' --bazel-mode.'
139      ),
140  )
141  bazel_mode.add_parser_arguments(parser, dest='bazel_mode_features')
142
143  parser.add_argument(
144      '-d',
145      '--disable-teardown',
146      action='store_true',
147      help='Disable test teardown and cleanup.',
148  )
149
150  parser.add_argument(
151      '--code-under-test',
152      type=lambda value: set(value.split(',')),
153      help=(
154          'Comma-separated list of modules whose sources should be included in'
155          ' the code coverage report. The dependencies of these modules are not'
156          ' included. For use with the --experimental-coverage flag.'
157      ),
158  )
159
160  parser.add_argument(
161      '--experimental-coverage',
162      action='store_true',
163      help=(
164          'Instrument tests with code coverage and generate a code coverage'
165          ' report.'
166      ),
167  )
168
169  parser.add_argument(
170      '--group-test',
171      default=True,
172      action='store_true',
173      help=(
174          'Group tests by module name during the test run (default: True). To'
175          ' run tests in the same order as they are input, use'
176          ' `--no-group-test`'
177      ),
178  )
179  parser.add_argument(
180      '--no-group-test',
181      dest='group_test',
182      action='store_false',
183      help=(
184          'Group the tests by module name for running the test, if you want'
185          ' to run the test using the same input order, use --no-group-test.'
186      ),
187  )
188
189  hgroup = parser.add_mutually_exclusive_group()
190  hgroup.add_argument(
191      '--host',
192      action='store_true',
193      help=(
194          'Run the test completely on the host without a device. (Note:'
195          ' running a host test that requires a device without --host will'
196          ' fail.)'
197      ),
198  )
199  hgroup.add_argument(
200      '--device-only',
201      action='store_true',
202      help=(
203          'Only run tests that require a device. (Note: only workable with'
204          ' --test-mapping.)'
205      ),
206  )
207
208  parser.add_argument(
209      '-i',
210      '--install',
211      action='append_const',
212      dest='steps',
213      const=constants.INSTALL_STEP,
214      help='Install an APK.',
215  )
216  parser.add_argument(
217      '-m',
218      constants.REBUILD_MODULE_INFO_FLAG,
219      action='store_true',
220      help=(
221          'Forces a rebuild of the module-info.json file. This may be'
222          ' necessary following a repo sync or when writing a new test.'
223      ),
224  )
225  parser.add_argument(
226      '--sharding',
227      nargs='?',
228      const=2,
229      type=_positive_int,
230      default=0,
231      help='Option to specify sharding count. (default: 2)',
232  )
233  parser.add_argument(
234      '--sqlite-module-cache',
235      action=argparse.BooleanOptionalAction,
236      default=True,
237      help='Use SQLite database as cache instead of JSON.',
238  )
239  parser.add_argument(
240      '-t',
241      '--test',
242      action='append_const',
243      dest='steps',
244      const=constants.TEST_STEP,
245      help=(
246          'Run the tests. WARNING: Many test configs force cleanup of device'
247          ' after test run. In this case, "-d" must be used in previous test'
248          ' run to disable cleanup for "-t" to work. Otherwise, device will'
249          ' need to be setup again with "-i".'
250      ),
251  )
252  parser.add_argument(
253      '--use-modules-in',
254      help=(
255          'Force include MODULES-IN-* as build targets. Hint: This may solve'
256          ' missing test dependencies issue.'
257      ),
258      action='store_true',
259  )
260  parser.add_argument(
261      '-w',
262      '--wait-for-debugger',
263      action='store_true',
264      help='Wait for debugger prior to execution (Instrumentation tests only).',
265  )
266
267  ugroup = parser.add_mutually_exclusive_group()
268  ugroup.add_argument(
269      '--request-upload-result',
270      action='store_true',
271      help=(
272          'Request permission to upload test result. This option only needs'
273          ' to set once and takes effect until --disable-upload-result is'
274          ' set.'
275      ),
276  )
277  ugroup.add_argument(
278      '--disable-upload-result',
279      action='store_true',
280      help=(
281          'Turn off the upload of test result. This option only needs to set'
282          ' once and takes effect until --request-upload-result is set'
283      ),
284  )
285
286  test_mapping_or_host_unit_group = parser.add_mutually_exclusive_group()
287  test_mapping_or_host_unit_group.add_argument(
288      '-p',
289      '--test-mapping',
290      action='store_true',
291      help='Run tests defined in TEST_MAPPING files.',
292  )
293  test_mapping_or_host_unit_group.add_argument(
294      '--host-unit-test-only',
295      action='store_true',
296      help='Run all host unit tests under the current directory.',
297  )
298  parser.add_argument(
299      '--include-subdirs',
300      action='store_true',
301      help='Search TEST_MAPPING files in subdirs as well.',
302  )
303  # TODO(b/146980564): Remove enable-file-patterns when support
304  # file-patterns in TEST_MAPPING by default.
305  parser.add_argument(
306      '--enable-file-patterns',
307      action='store_true',
308      help='Enable FILE_PATTERNS in TEST_MAPPING.',
309  )
310
311  group = parser.add_mutually_exclusive_group()
312  group.add_argument(
313      '--collect-tests-only',
314      action='store_true',
315      help=(
316          'Collect a list test cases of the instrumentation tests without'
317          ' testing them in real.'
318      ),
319  )
320  group.add_argument(
321      '--dry-run',
322      action='store_true',
323      help=(
324          'Dry run atest without building, installing and running tests in'
325          ' real.'
326      ),
327  )
328  parser.add_argument(
329      '-L', '--list-modules', help='List testable modules of the given suite.'
330  )
331  parser.add_argument(
332      '-v',
333      '--verbose',
334      action='store_true',
335      help='Display DEBUG level logging.',
336  )
337  parser.add_argument(
338      '-V', '--version', action='store_true', help='Display version string.'
339  )
340  parser.add_argument(
341      '--build-output',
342      default=BuildOutputMode.STREAMED,
343      choices=BuildOutputMode,
344      type=BuildOutputMode,
345      help=(
346          'Specifies the desired build output mode. Valid values are:'
347          f' {_output_mode_msg()}'
348      ),
349  )
350
351  agroup = parser.add_mutually_exclusive_group()
352  agroup.add_argument(
353      '--acloud-create',
354      nargs=argparse.REMAINDER,
355      type=str,
356      help='(For testing with AVDs) Create AVD(s) via acloud command.',
357  )
358  agroup.add_argument(
359      '--start-avd',
360      action='store_true',
361      help=(
362          '(For testing with AVDs) Automatically create an AVD and run tests'
363          ' on the virtual device.'
364      ),
365  )
366  agroup.add_argument(
367      '-s', '--serial', action='append', help='The device to run the test on.'
368  )
369
370  parser.add_argument(
371      '--test-config-select',
372      action='store_true',
373      help=(
374          'If multiple test config belong to same test module pop out a'
375          ' selection menu on console.'
376      ),
377  )
378
379  parser.add_argument(
380      '--instant',
381      action='store_true',
382      help=(
383          '(For module parameterization) Run the instant_app version of the'
384          " module if the module supports it. Note: Nothing's going to run if"
385          " it's not an Instant App test and '--instant' is passed."
386      ),
387  )
388  parser.add_argument(
389      '--user-type',
390      help=(
391          '(For module parameterization) Run test with specific user type,'
392          ' e.g. atest <test> --user-type secondary_user'
393      ),
394  )
395  parser.add_argument(
396      '--annotation-filter',
397      action='append',
398      help=(
399          '(For module parameterization) Accept keyword that will be'
400          ' translated to fully qualified annotation class name.'
401      ),
402  )
403
404  parser.add_argument(
405      '-c',
406      '--clear-cache',
407      action='store_true',
408      help='Wipe out the test_infos cache of the test and start a new search.',
409  )
410  parser.add_argument(
411      '-D',
412      '--tf-debug',
413      nargs='?',
414      const=10888,
415      type=_positive_int,
416      default=0,
417      help='Enable tradefed debug mode with a specified port. (default: 10888)',
418  )
419  parser.add_argument(
420      '--tf-template',
421      action='append',
422      help=(
423          'Add extra tradefed template for ATest suite, e.g. atest <test>'
424          ' --tf-template <template_key>=<template_path>'
425      ),
426  )
427  parser.add_argument(
428      '--test-filter',
429      nargs='?',
430      # TODO(b/326457393): JarHostTest to support running parameterized tests
431      # with base method
432      # TODO(b/326141263): TradeFed to support wildcard in include-filter for
433      # parametrized JarHostTests
434      help=(
435          'Run only the tests which are specified with this option. '
436          'Filtering by method and with wildcard is not yet supported for '
437          'all test types.'
438      ),
439  )
440  parser.add_argument(
441      '--test-timeout',
442      nargs='?',
443      type=int,
444      help=(
445          'Customize test timeout. E.g. 60000(in milliseconds) represents 1'
446          ' minute timeout. For no timeout, set to 0.'
447      ),
448  )
449
450  iteration_group = parser.add_mutually_exclusive_group()
451  iteration_group.add_argument(
452      '--iterations',
453      nargs='?',
454      type=_positive_int,
455      const=10,
456      default=0,
457      metavar='MAX_ITERATIONS',
458      help=(
459          '(For iteration testing) Loop-run tests until the max iteration is'
460          ' reached. (default: 10)'
461      ),
462  )
463  iteration_group.add_argument(
464      '--rerun-until-failure',
465      nargs='?',
466      type=_positive_int,
467      const=2147483647,  # Java's Integer.MAX_VALUE for TradeFed.
468      default=0,
469      metavar='MAX_ITERATIONS',
470      help=(
471          '(For iteration testing) Rerun all tests until a failure occurs or'
472          ' the max iteration is reached. (default: forever!)'
473      ),
474  )
475  iteration_group.add_argument(
476      '--retry-any-failure',
477      nargs='?',
478      type=_positive_int,
479      const=10,
480      default=0,
481      metavar='MAX_ITERATIONS',
482      help=(
483          '(For iteration testing) Rerun failed tests until passed or the max'
484          ' iteration is reached. (default: 10)'
485      ),
486  )
487
488  history_group = parser.add_mutually_exclusive_group()
489  history_group.add_argument(
490      '--latest-result', action='store_true', help='Print latest test result.'
491  )
492  history_group.add_argument(
493      '--history',
494      nargs='?',
495      const='99999',
496      help=(
497          'Show test results in chronological order(with specified number or'
498          ' all by default).'
499      ),
500  )
501
502  parser.add_argument(
503      constants.NO_METRICS_ARG,
504      action='store_true',
505      help='(For metrics) Do not send metrics.',
506  )
507
508  parser.add_argument(
509      '--aggregate-metric-filter',
510      action='append',
511      help=(
512          '(For performance testing) Regular expression that will be used for'
513          ' filtering the aggregated metrics.'
514      ),
515  )
516
517  parser.add_argument(
518      '--no-checking-device',
519      action='store_true',
520      help='Do NOT check device availability. (even it is a device test)',
521  )
522
523  parser.add_argument(
524      '-j',
525      '--build-j',
526      nargs='?',
527      type=int,
528      help='Number of build run processes.',
529  )
530  # Flag to use atest_local_min.xml as the TF base templates, this is added
531  # to roll out the change that uses separate templates for device/deviceless
532  # tests and should be removed once that feature is stable.
533  parser.add_argument(
534      '--use-tf-min-base-template',
535      dest='use_tf_min_base_template',
536      action=argparse.BooleanOptionalAction,
537      default=False,
538      help='Run tests using atest_local_min.xml as the TF base templates.',
539  )
540
541  # This arg actually doesn't consume anything, it's primarily used for
542  # the help description and creating custom_args in the NameSpace object.
543  parser.add_argument(
544      '--',
545      dest='custom_args',
546      nargs='*',
547      help=(
548          'Specify custom args for the test runners. Everything after -- will'
549          ' be consumed as custom args.'
550      ),
551  )
552
553  return parser
554
555
556_HELP_DESCRIPTION = """NAME
557        atest - A command line tool that allows users to build, install, and run Android tests locally, greatly speeding test re-runs without requiring knowledge of Trade Federation test harness command line options.
558
559
560SYNOPSIS
561        atest [OPTION]... [TEST_TARGET]... -- [CUSTOM_ARGS]...
562
563
564OPTIONS
565        The below arguments are categorized by feature and purpose. Arguments marked with an implicit default will apply even when the user doesn't pass them explicitly.
566
567        *NOTE* Atest reads ~/.atest/config that supports all optional arguments to help users reduce repeating options they often use.
568        E.g. Assume "--all-abi" and "--verbose" are frequently used and have been defined line-by-line in ~/.atest/config, issuing
569
570            atest hello_world_test -v -- --test-arg xxx
571
572        is equivalent to
573
574            atest hello_world_test -v --all-abi --verbose -- --test-arg xxx
575
576        If you only need to run tests for a specific abi, please use:
577            atest <test> -- --abi arm64-v8a   # ARM 64-bit
578            atest <test> -- --abi armeabi-v7a # ARM 32-bit
579
580        Also, to avoid confusing Atest from testing TEST_MAPPING file and implicit test names from ~/.atest/config, any test names defined in the config file
581        will be ignored without any hints.
582
583
584EXAMPLES
585    - - - - - - - - -
586    IDENTIFYING TESTS
587    - - - - - - - - -
588
589    The positional argument <tests> should be a reference to one or more of the tests you'd like to run. Multiple tests can be run in one command by separating test references with spaces.
590
591    Usage template: atest <reference_to_test_1> <reference_to_test_2>
592
593    A <reference_to_test> can be satisfied by the test's MODULE NAME, MODULE:CLASS, CLASS NAME, TF INTEGRATION TEST, FILE PATH or PACKAGE NAME. Explanations and examples of each follow.
594
595
596    < MODULE NAME >
597
598        Identifying a test by its module name will run the entire module. Input the name as it appears in the LOCAL_MODULE or LOCAL_PACKAGE_NAME variables in that test's Android.mk or Android.bp file.
599
600        Note: Use < TF INTEGRATION TEST > to run non-module tests integrated directly into TradeFed.
601
602        Examples:
603            atest FrameworksServicesTests
604            atest CtsJankDeviceTestCases
605
606
607    < MODULE:CLASS >
608
609        Identifying a test by its class name will run just the tests in that class and not the whole module. MODULE:CLASS is the preferred way to run a single class. MODULE is the same as described above. CLASS is the name of the test class in the .java file. It can either be the fully qualified class name or just the basic name.
610
611        Examples:
612            atest FrameworksServicesTests:ScreenDecorWindowTests
613            atest FrameworksServicesTests:com.android.server.wm.ScreenDecorWindowTests
614            atest CtsJankDeviceTestCases:CtsDeviceJankUi
615
616
617    < CLASS NAME >
618
619        A single class can also be run by referencing the class name without the module name.
620
621        Examples:
622            atest ScreenDecorWindowTests
623            atest CtsDeviceJankUi
624
625        However, this will take more time than the equivalent MODULE:CLASS reference, so we suggest using a MODULE:CLASS reference whenever possible. Examples below are ordered by performance from the fastest to the slowest:
626
627        Examples:
628            atest FrameworksServicesTests:com.android.server.wm.ScreenDecorWindowTests
629            atest FrameworksServicesTests:ScreenDecorWindowTests
630            atest ScreenDecorWindowTests
631
632    < TF INTEGRATION TEST >
633
634        To run tests that are integrated directly into TradeFed (non-modules), input the name as it appears in the output of the "tradefed.sh list configs" cmd.
635
636        Examples:
637           atest example/reboot
638           atest native-benchmark
639
640
641    < FILE PATH >
642
643        Both module-based tests and integration-based tests can be run by inputting the path to their test file or dir as appropriate. A single class can also be run by inputting the path to the class's java file.
644
645        Both relative and absolute paths are supported.
646
647        Example - 2 ways to run the `CtsJankDeviceTestCases` module via path:
648        1. run module from android <repo root>:
649            atest cts/tests/jank/jank
650
651        2. from <android root>/cts/tests/jank:
652            atest .
653
654        Example - run a specific class within CtsJankDeviceTestCases module from <android repo> root via path:
655           atest cts/tests/jank/src/android/jank/cts/ui/CtsDeviceJankUi.java
656
657        Example - run an integration test from <android repo> root via path:
658           atest tools/tradefederation/contrib/res/config/example/reboot.xml
659
660
661    < PACKAGE NAME >
662
663        Atest supports searching tests from package name as well.
664
665        Examples:
666           atest com.android.server.wm
667           atest android.jank.cts
668
669
670    - - - - - - - - - - - - - - - - - - - - - - - - - -
671    SPECIFYING INDIVIDUAL STEPS: BUILD, INSTALL OR RUN
672    - - - - - - - - - - - - - - - - - - - - - - - - - -
673
674    The -b, -i and -t options allow you to specify which steps you want to run. If none of those options are given, then all steps are run. If any of these options are provided then only the listed steps are run.
675
676    Note: -i alone is not currently support and can only be included with -t.
677    Both -b and -t can be run alone.
678
679    Examples:
680        atest -b <test>    (just build targets)
681        atest -t <test>    (run tests only)
682        atest -it <test>   (install apk and run tests)
683        atest -bt <test>   (build targets, run tests, but skip installing apk)
684
685
686    Atest now has the ability to force a test to skip its cleanup/teardown step. Many tests, e.g. CTS, cleanup the device after the test is run, so trying to rerun your test with -t will fail without having the --disable-teardown parameter. Use -d before -t to skip the test clean up step and test iteratively.
687
688        atest -d <test>    (disable installing apk and cleaning up device)
689        atest -t <test>
690
691    Note that -t disables both setup/install and teardown/cleanup of the device. So you can continue to rerun your test with just
692
693        atest -t <test>
694
695    as many times as you want.
696
697
698    - - - - - - - - - - - - -
699    RUNNING SPECIFIC METHODS
700    - - - - - - - - - - - - -
701
702    It is possible to run only specific methods within a test class. To run only specific methods, identify the class in any of the ways supported for identifying a class (MODULE:CLASS, FILE PATH, etc) and then append the name of the method or method using the following template:
703
704      <reference_to_class>#<method1>
705
706    Multiple methods can be specified with commas:
707
708      <reference_to_class>#<method1>,<method2>,<method3>...
709
710    Examples:
711      atest com.android.server.wm.ScreenDecorWindowTests#testMultipleDecors
712
713      atest FrameworksServicesTests:ScreenDecorWindowTests#testFlagChange,testRemoval
714
715
716    - - - - - - - - - - - - -
717    FILTERING TESTS
718    - - - - - - - - - - - - -
719    It is possible to run only the tests that are specified by a custom filter, although not all test types support filtering by wildcard.
720
721    Usage format:
722      atest <TestModuleName> --test-filter <test.package.name>.<TestClass>#<testMethod>
723
724    Example:
725      atest  ParameterizedHelloWorldTests --test-filter '.*HelloWorldTest#testHa.*'
726
727    Note: parametrized JarHostTests can only be filtered by a specific method if parameters are also provided TODO(b/326457393). Wildcard filtering is not supported TODO(b/326141263):
728      atest <TestModuleName> --test-filter <test.package.name>.<ParameterizedTestClass>#<testMethod>[<param1>=<value>,<param2>=<value>]
729
730    - - - - - - - - - - - - -
731    RUNNING MULTIPLE CLASSES
732    - - - - - - - - - - - - -
733
734    To run multiple classes, deliminate them with spaces just like you would when running multiple tests.  Atest will handle building and running classes in the most efficient way possible, so specifying a subset of classes in a module will improve performance over running the whole module.
735
736
737    Examples:
738    - two classes in same module:
739      atest FrameworksServicesTests:ScreenDecorWindowTests FrameworksServicesTests:DimmerTests
740
741    - two classes, different modules:
742      atest FrameworksServicesTests:ScreenDecorWindowTests CtsJankDeviceTestCases:CtsDeviceJankUi
743
744
745    - - - - - - - - - - -
746    RUNNING NATIVE TESTS
747    - - - - - - - - - - -
748
749    Atest can run native test.
750
751    Example:
752    - Input tests:
753      atest -a libinput_tests inputflinger_tests
754
755    Use -a|--all-abi to run the tests for all available device architectures, which in this example is armeabi-v7a (ARM 32-bit) and arm64-v8a (ARM 64-bit).
756
757    To select a specific native test to run, use colon (:) to specify the test name and hashtag (#) to further specify an individual method. For example, for the following test definition:
758
759        TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents)
760
761    You can run the entire test using:
762
763        atest inputflinger_tests:InputDispatcherTest
764
765    or an individual test method using:
766
767        atest inputflinger_tests:InputDispatcherTest#InjectInputEvent_ValidatesKeyEvents
768
769
770    - - - - - - - - - - - - - -
771    RUNNING TESTS IN ITERATION
772    - - - - - - - - - - - - - -
773
774    To run tests in iterations, simply pass --iterations argument. No matter pass or fail, atest won't stop testing until the max iteration is reached.
775
776    Example:
777        atest <test> --iterations    # 10 iterations(by default).
778        atest <test> --iterations 5  # run <test> 5 times.
779
780    Two approaches that assist users to detect flaky tests:
781
782    1) Run all tests until a failure occurs or the max iteration is reached.
783
784    Example:
785        - 10 iterations(by default).
786        atest <test> --rerun-until-failure
787        - stop when failed or reached the 20th run.
788        atest <test> --rerun-until-failure 20
789
790    2) Run failed tests until passed or the max iteration is reached.
791
792    Example:
793        - 10 iterations(by default).
794        atest <test> --retry-any-failure
795        - stop when passed or reached the 20th run.
796        atest <test> --retry-any-failure 20
797
798
799    - - - - - - - - - - - -
800    RUNNING TESTS ON AVD(s)
801    - - - - - - - - - - - -
802
803    Atest is able to run tests with the newly created AVD. Atest can build and 'acloud create' simultaneously, and run tests after the AVD has been created successfully.
804
805    Examples:
806    - Start an AVD before running tests on that newly created device.
807
808        acloud create && atest <test>
809
810    can be simplified by:
811
812        atest <test> --start-avd
813
814    - Start AVD(s) by specifying 'acloud create' arguments and run tests on that newly created device.
815
816        atest <test> --acloud-create "--build-id 6509363 --build-target aosp_cf_x86_phone-userdebug --branch aosp_master"
817
818    To know detail about the argument, please run 'acloud create --help'.
819
820    [WARNING]
821    * --acloud-create must be the LAST optional argument: the remainder args will be consumed as its positional args.
822    * --acloud-create/--start-avd do not delete newly created AVDs. The users will be deleting them manually.
823
824
825    - - - - - - - - - - - -
826    TESTS IN TEST MAPPING
827    - - - - - - - - - - - -
828
829    Atest can run tests in TEST_MAPPING files:
830
831    1) Run presubmit tests in TEST_MAPPING files in current and parent
832       directories. You can also specify a target directory.
833
834    Example:
835        atest  (run presubmit tests in TEST_MAPPING files and host unit tests in current and parent directories)
836        atest --test-mapping </path/to/project>
837               (run presubmit tests in TEST_MAPPING files in </path/to/project> and its parent directories)
838
839    2) Run a specified test group in TEST_MAPPING files.
840
841    Example:
842        atest :postsubmit
843              (run postsubmit tests in TEST_MAPPING files in current and parent directories)
844        atest :all
845              (Run tests from all groups in TEST_MAPPING files)
846        atest --test-mapping </path/to/project>:postsubmit
847              (run postsubmit tests in TEST_MAPPING files in </path/to/project> and its parent directories)
848        atest --test-mapping </path/to/project>:mainline-presubmit
849              (run mainline tests in TEST_MAPPING files in </path/to/project> and its parent directories)
850
851    3) Run tests in TEST_MAPPING files including sub directories
852
853    By default, atest will only search for tests in TEST_MAPPING files in current (or given directory) and its parent directories. If you want to run tests in TEST_MAPPING files in the sub-directories, you can use option --include-subdirs to force atest to include those tests too.
854
855    Example:
856        atest --include-subdirs [optional </path/to/project>:<test_group_name>]
857              (run presubmit tests in TEST_MAPPING files in current, sub and parent directories)
858    A path can be provided optionally if you want to search for tests in a given directory, with optional test group name. By default, the test group is presubmit.
859
860
861    - - - - - - - - - - - - - -
862    ADDITIONAL ARGS TO TRADEFED
863    - - - - - - - - - - - - - -
864
865    When trying to pass custom arguments for the test runners, everything after '--'
866    will be consumed as custom args.
867
868    Example:
869        atest -v <test> -- <custom_args1> <custom_args2>
870
871    Examples of passing options to the modules:
872        atest <test> -- --module-arg <module-name>:<option-name>:<option-value>
873        atest GtsPermissionTestCases -- --module-arg GtsPermissionTestCases:ignore-business-logic-failure:true
874
875    Examples of passing options to the runner type or class:
876        atest <test> -- --test-arg <test-class>:<option-name>:<option-value>
877        atest CtsVideoTestCases -- --test-arg com.android.tradefed.testtype.JarHosttest:collect-tests-only:true
878
879
880                                                     2022-03-25
881"""
882