How to use CommandLineArgs class of org.testng package

Best Testng code snippet using org.testng.CommandLineArgs

Run Testng automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package com.time.ttest.proxy;
2
3import com.beust.jcommander.JCommander;
4import com.time.ttest.TTestApplication;
5import lombok.extern.slf4j.Slf4j;
6import org.testng.CommandLineArgs;
7import org.testng.TestNG;
8import org.testng.TestNGException;
9import org.testng.TestRunner;
10import org.testng.collections.Lists;
11import org.testng.internal.ExitCode;
12
13import java.util.Arrays;
14import java.util.List;
15import java.util.Properties;
16import java.util.stream.Collectors;
17
18/**
19 * testng代理类
20 * @Auther guoweijie
21
22 * @Date 2020-03-22 23:07
23 */
24@Slf4j
25public class TTestNGProxy<T> extends Proxy<T>{
26
27    /**
28     * 配置文件
29     */
30    private Properties properties;
31
32    /**
33     * 命令行参数
34     */
35    private String[] args;
36
37    public TTestNGProxy(TestNG testNG) {
38        setBeProxy((T) testNG);
39    }
40
41    public TTestNGProxy(TestNG testNG,Properties properties) {
42        setBeProxy((T) testNG);
43        this.properties = properties;
44    }
45
46    public TTestNGProxy(TestNG testNG,Properties properties,String[] args) {
47        setBeProxy((T) testNG);
48        this.properties = properties;
49        this.args = args;
50    }
51
52    public TestNG getTestNG(){
53        return (TestNG) getBeProxy();
54    }
55
56    public void run(){
57        CommandLineArgs cla = commandLineArgs(properties,args);
58        getTestNG().setTestSuites(cla.suiteFiles);
59        //调用testng的方法,校验参数
60        invokeMethod("validateCommandLineParameters",new Class[]{CommandLineArgs.class},cla);
61        //调用testng的方法,配置参数
62        invokeMethod("configure",new Class[]{CommandLineArgs.class},cla);
63        try {
64            getTestNG().run();
65        }catch (TestNGException ex) {
66            if (TestRunner.getVerbose() > 1) {
67                ex.printStackTrace(System.out);
68            } else {
69                log.error(ex.getMessage());
70            }
71            modifyPrivateParam("exitCode", ExitCode.newExitCodeRepresentingFailure());
72        }
73    }
74
75    private CommandLineArgs commandLineArgs(Properties properties,String... args){
76        CommandLineArgs cla = new CommandLineArgs();
77        JCommander jCommander = new JCommander(cla);
78        jCommander.parse(args);
79        //如果启动参数没有指定xml,则使用配置文件中的
80        cla.suiteFiles = cla.suiteFiles.size()>0?cla.suiteFiles:getTestNgSuitFiles(properties);
81        //添加 guice InjectorFactory
82        cla.dependencyInjectoryFactoryClass = TTestApplication.class.getName();
83        return cla;
84    }
85
86
87    /**
88     *  获取配置文件的 suitefile
89     * @param properties 配置文件参数
90     * @return
91     */
92    private List<String> getTestNgSuitFiles(Properties properties){
93        List<String> suiteFiles = Lists.newArrayList();
94        String[] ttestSuiteFiles =properties.getProperty("testng.suite.file").split(",");
95        suiteFiles.addAll(Arrays.asList(ttestSuiteFiles));
96        suiteFiles = suiteFiles.stream().distinct().collect(Collectors.toList());
97        return suiteFiles;
98    }
99}
100
Full Screen
copy
1package org.testng;
2
3import java.io.File;
4import java.io.IOException;
5import java.net.URLClassLoader;
6import java.util.ArrayList;
7import java.util.Arrays;
8import java.util.Collection;
9import java.util.Collections;
10import java.util.List;
11import java.util.Map;
12import java.util.ServiceLoader;
13import java.util.Set;
14import java.util.concurrent.LinkedBlockingQueue;
15import java.util.concurrent.TimeUnit;
16
17import org.testng.annotations.ITestAnnotation;
18import org.testng.collections.Lists;
19import org.testng.collections.Maps;
20import org.testng.collections.Sets;
21import org.testng.internal.ClassHelper;
22import org.testng.internal.Configuration;
23import org.testng.internal.DynamicGraph;
24import org.testng.internal.ExitCode;
25import org.testng.internal.IConfiguration;
26import org.testng.internal.OverrideProcessor;
27import org.testng.internal.RuntimeBehavior;
28import org.testng.internal.SuiteRunnerMap;
29import org.testng.internal.Systematiser;
30import org.testng.internal.Utils;
31import org.testng.internal.Version;
32import org.testng.internal.annotations.DefaultAnnotationTransformer;
33import org.testng.internal.annotations.IAnnotationFinder;
34import org.testng.internal.annotations.JDK15AnnotationFinder;
35import org.testng.internal.thread.graph.GraphThreadPoolExecutor;
36import org.testng.internal.thread.graph.IThreadWorkerFactory;
37import org.testng.internal.thread.graph.SuiteWorkerFactory;
38import org.testng.junit.JUnitTestFinder;
39import org.testng.log4testng.Logger;
40import org.testng.reporters.EmailableReporter;
41import org.testng.reporters.EmailableReporter2;
42import org.testng.reporters.FailedReporter;
43import org.testng.reporters.JUnitReportReporter;
44import org.testng.reporters.SuiteHTMLReporter;
45import org.testng.reporters.VerboseReporter;
46import org.testng.reporters.XMLReporter;
47import org.testng.reporters.jq.Main;
48import org.testng.util.Strings;
49import org.testng.xml.IPostProcessor;
50import org.testng.xml.Parser;
51import org.testng.xml.XmlClass;
52import org.testng.xml.XmlInclude;
53import org.testng.xml.XmlMethodSelector;
54import org.testng.xml.XmlSuite;
55import org.testng.xml.XmlTest;
56
57import com.beust.jcommander.JCommander;
58import com.beust.jcommander.ParameterException;
59
60import org.testng.xml.internal.TestNamesMatcher;
61import org.testng.xml.internal.XmlSuiteUtils;
62
63import static org.testng.internal.Utils.defaultIfStringEmpty;
64import static org.testng.internal.Utils.isStringEmpty;
65import static org.testng.internal.Utils.isStringNotEmpty;
66import static org.testng.xml.XmlSuite.ParallelMode.skipDeprecatedValues;
67
68/**
69 * This class is the main entry point for running tests in the TestNG framework. Users can create
70 * their own TestNG object and invoke it in many different ways:
71 *
72 * <ul>
73 *   <li>On an existing testng.xml
74 *   <li>On a synthetic testng.xml, created entirely from Java
75 *   <li>By directly setting the test classes
76 * </ul>
77 *
78 * You can also define which groups to include or exclude, assign parameters, etc...
79 *
80 * <p>The command line parameters are:
81 *
82 * <UL>
83 *   <LI>-d <TT>outputdir</TT>: specify the output directory
84 *   <LI>-testclass <TT>class_name</TT>: specifies one or several class names
85 *   <LI>-testjar <TT>jar_name</TT>: specifies the jar containing the tests
86 *   <LI>-sourcedir <TT>src1;src2</TT>: ; separated list of source directories (used only when
87 *       javadoc annotations are used)
88 *   <LI>-target
89 *   <LI>-groups
90 *   <LI>-testrunfactory
91 *   <LI>-listener
92 * </UL>
93 *
94 * <p>Please consult documentation for more details.
95 *
96 * <p>FIXME: should support more than simple paths for suite xmls
97 *
98 * @see #usage()
99 * @author <a href = "mailto:cedric&#64;beust.com">Cedric Beust</a>
100 */
101public class TestNG {
102
103  /** This class' log4testng Logger. */
104  private static final Logger LOGGER = Logger.getLogger(TestNG.class);
105
106  /** The default name for a suite launched from the command line */
107  public static final String DEFAULT_COMMAND_LINE_SUITE_NAME = "Command line suite";
108
109  /** The default name for a test launched from the command line */
110  public static final String DEFAULT_COMMAND_LINE_TEST_NAME = "Command line test";
111
112  /** The default name of the result's output directory (keep public, used by Eclipse). */
113  public static final String DEFAULT_OUTPUTDIR = "test-output";
114
115  private static TestNG m_instance;
116
117  private static JCommander m_jCommander;
118
119  private List<String> m_commandLineMethods;
120  protected List<XmlSuite> m_suites = Lists.newArrayList();
121  private List<XmlSuite> m_cmdlineSuites;
122  private String m_outputDir = DEFAULT_OUTPUTDIR;
123
124  private String[] m_includedGroups;
125  private String[] m_excludedGroups;
126
127  private Boolean m_isJUnit = XmlSuite.DEFAULT_JUNIT;
128  private Boolean m_isMixed = XmlSuite.DEFAULT_MIXED;
129  protected boolean m_useDefaultListeners = true;
130
131  private ITestRunnerFactory m_testRunnerFactory;
132
133  // These listeners can be overridden from the command line
134  private final Map<Class<? extends IClassListener>, IClassListener> m_classListeners =
135      Maps.newHashMap();
136  private final Map<Class<? extends ITestListener>, ITestListener> m_testListeners =
137      Maps.newHashMap();
138  private final Map<Class<? extends ISuiteListener>, ISuiteListener> m_suiteListeners =
139      Maps.newHashMap();
140  private final Map<Class<? extends IReporter>, IReporter> m_reporters = Maps.newHashMap();
141  private final Map<Class<? extends IDataProviderListener>, IDataProviderListener>
142      m_dataProviderListeners = Maps.newHashMap();
143
144  public static final Integer DEFAULT_VERBOSE = 1;
145
146  // Command line suite parameters
147  private int m_threadCount = -1;
148  private XmlSuite.ParallelMode m_parallelMode = null;
149  private XmlSuite.FailurePolicy m_configFailurePolicy;
150  private Class[] m_commandLineTestClasses;
151
152  private String m_defaultSuiteName = DEFAULT_COMMAND_LINE_SUITE_NAME;
153  private String m_defaultTestName = DEFAULT_COMMAND_LINE_TEST_NAME;
154
155  private Map<String, Integer> m_methodDescriptors = Maps.newHashMap();
156
157  private Set<XmlMethodSelector> m_selectors = Sets.newLinkedHashSet();
158
159  private ITestObjectFactory m_objectFactory;
160
161  private final Map<Class<? extends IInvokedMethodListener>, IInvokedMethodListener>
162      m_invokedMethodListeners = Maps.newHashMap();
163
164  private Integer m_dataProviderThreadCount = null;
165
166  private String m_jarPath;
167  /** The path of the testng.xml file inside the jar file */
168  private String m_xmlPathInJar = CommandLineArgs.XML_PATH_IN_JAR_DEFAULT;
169
170  private List<String> m_stringSuites = Lists.newArrayList();
171
172  private IHookable m_hookable;
173  private IConfigurable m_configurable;
174
175  protected long m_end;
176  protected long m_start;
177
178  private final Map<Class<? extends IAlterSuiteListener>, IAlterSuiteListener>
179      m_alterSuiteListeners = Maps.newHashMap();
180
181  private boolean m_isInitialized = false;
182  private boolean isSuiteInitialized = false;
183  private final org.testng.internal.ExitCodeListener exitCodeListener =
184      new org.testng.internal.ExitCodeListener();
185  private ExitCode exitCode;
186  private final Map<Class<? extends IExecutionVisualiser>, IExecutionVisualiser>
187      m_executionVisualisers = Maps.newHashMap();
188
189  /** Default constructor. Setting also usage of default listeners/reporters. */
190  public TestNG() {
191    init(true);
192  }
193
194  /**
195   * Used by maven2 to have 0 output of any kind come out of testng.
196   *
197   * @param useDefaultListeners Whether or not any default reports should be added to tests.
198   */
199  public TestNG(boolean useDefaultListeners) {
200    init(useDefaultListeners);
201  }
202
203  private void init(boolean useDefaultListeners) {
204    m_instance = this;
205
206    m_useDefaultListeners = useDefaultListeners;
207    m_configuration = new Configuration();
208  }
209
210  public int getStatus() {
211    if (exitCodeListener.noTestsFound()) {
212      return ExitCode.HAS_NO_TEST;
213    }
214    return exitCode.getExitCode();
215  }
216
217  /**
218   * Sets the output directory where the reports will be created.
219   *
220   * @param outputdir The directory.
221   */
222  public void setOutputDirectory(final String outputdir) {
223    if (isStringNotEmpty(outputdir)) {
224      m_outputDir = outputdir;
225    }
226  }
227
228  /**
229   * If this method is passed true before run(), the default listeners will not be used.
230   *
231   * <ul>
232   *   <li>org.testng.reporters.TestHTMLReporter
233   *   <li>org.testng.reporters.JUnitXMLReporter
234   *   <li>org.testng.reporters.XMLReporter
235   * </ul>
236   *
237   * @see org.testng.reporters.TestHTMLReporter
238   * @see org.testng.reporters.JUnitXMLReporter
239   * @see org.testng.reporters.XMLReporter
240   */
241  public void setUseDefaultListeners(boolean useDefaultListeners) {
242    m_useDefaultListeners = useDefaultListeners;
243  }
244
245  /**
246   * Sets a jar containing a testng.xml file.
247   *
248   * @param jarPath
249   */
250  public void setTestJar(String jarPath) {
251    m_jarPath = jarPath;
252  }
253
254  /** Sets the path to the XML file in the test jar file. */
255  public void setXmlPathInJar(String xmlPathInJar) {
256    m_xmlPathInJar = xmlPathInJar;
257  }
258
259  private void parseSuiteFiles() {
260    IPostProcessor processor = getProcessor();
261    for (XmlSuite s : m_suites) {
262      if (s.isParsed()) {
263        continue;
264      }
265      for (String suiteFile : s.getSuiteFiles()) {
266        try {
267          String fileNameToUse = s.getFileName();
268          if (fileNameToUse == null || fileNameToUse.trim().isEmpty()) {
269            fileNameToUse = suiteFile;
270          }
271          Collection<XmlSuite> childSuites = Parser.parse(fileNameToUse, processor);
272          for (XmlSuite cSuite : childSuites) {
273            cSuite.setParentSuite(s);
274            s.getChildSuites().add(cSuite);
275          }
276        } catch (IOException e) {
277          e.printStackTrace(System.out);
278        }
279      }
280    }
281  }
282
283  private OverrideProcessor getProcessor() {
284    return new OverrideProcessor(m_includedGroups, m_excludedGroups);
285  }
286
287  private void parseSuite(String suitePath) {
288    if (LOGGER.isDebugEnabled()) {
289      LOGGER.debug("suiteXmlPath: \"" + suitePath + "\"");
290    }
291    try {
292      Collection<XmlSuite> allSuites = Parser.parse(suitePath, getProcessor());
293
294      for (XmlSuite s : allSuites) {
295        if (this.m_parallelMode != null) {
296          s.setParallel(this.m_parallelMode);
297        }
298        if (this.m_threadCount > 0) {
299          s.setThreadCount(this.m_threadCount);
300        }
301        if (m_testNames == null) {
302          m_suites.add(s);
303          continue;
304        }
305        // If test names were specified, only run these test names
306        TestNamesMatcher testNamesMatcher = new TestNamesMatcher(s, m_testNames);
307        List<String> missMatchedTestname = testNamesMatcher.getMissMatchedTestNames();
308        if (!missMatchedTestname.isEmpty()) {
309          throw new TestNGException("The test(s) <" + missMatchedTestname + "> cannot be found.");
310        }
311        m_suites.addAll(testNamesMatcher.getSuitesMatchingTestNames());
312      }
313    } catch (IOException e) {
314      e.printStackTrace(System.out);
315    } catch (Exception ex) {
316      // Probably a Yaml exception, unnest it
317      Throwable t = ex;
318      while (t.getCause() != null) {
319        t = t.getCause();
320      }
321      if (t instanceof TestNGException) {
322        throw (TestNGException) t;
323      }
324      throw new TestNGException(t);
325    }
326  }
327
328  public void initializeSuitesAndJarFile() {
329    // The IntelliJ plug-in might have invoked this method already so don't initialize suites twice.
330    if (isSuiteInitialized) {
331      return;
332    }
333    isSuiteInitialized = true;
334
335    if (!m_suites.isEmpty()) {
336      parseSuiteFiles(); // to parse the suite files (<suite-file>), if any
337      return;
338    }
339
340    //
341    // Parse the suites that were passed on the command line
342    //
343    for (String suitePath : m_stringSuites) {
344      parseSuite(suitePath);
345    }
346
347    //
348    // jar path
349    //
350    // If suites were passed on the command line, they take precedence over the suite file
351    // inside that jar path
352    if (m_jarPath != null && !m_stringSuites.isEmpty()) {
353      StringBuilder suites = new StringBuilder();
354      for (String s : m_stringSuites) {
355        suites.append(s);
356      }
357      Utils.log(
358          "TestNG",
359          2,
360          "Ignoring the XML file inside " + m_jarPath + " and using " + suites + " instead");
361      return;
362    }
363    if (isStringEmpty(m_jarPath)) {
364      return;
365    }
366
367    // We have a jar file and no XML file was specified: try to find an XML file inside the jar
368    File jarFile = new File(m_jarPath);
369
370    JarFileUtils utils =
371        new JarFileUtils(getProcessor(), m_xmlPathInJar, m_testNames, m_parallelMode);
372
373    m_suites.addAll(utils.extractSuitesFrom(jarFile));
374  }
375
376  /** Define the number of threads in the thread pool. */
377  public void setThreadCount(int threadCount) {
378    if (threadCount < 1) {
379      exitWithError("Cannot use a threadCount parameter less than 1; 1 > " + threadCount);
380    }
381
382    m_threadCount = threadCount;
383  }
384
385  /**
386   * Define whether this run will be run in parallel mode.
387   *
388   * @deprecated Use #setParallel(XmlSuite.ParallelMode) instead
389   */
390  @Deprecated
391  // TODO: krmahadevan: This method is being used by Gradle. Removal causes build failures.
392  public void setParallel(String parallel) {
393    if (parallel == null) {
394      setParallel(XmlSuite.ParallelMode.NONE);
395    } else {
396      setParallel(XmlSuite.ParallelMode.getValidParallel(parallel));
397    }
398  }
399
400  public void setParallel(XmlSuite.ParallelMode parallel) {
401    m_parallelMode = skipDeprecatedValues(parallel);
402  }
403
404  public void setCommandLineSuite(XmlSuite suite) {
405    m_cmdlineSuites = Lists.newArrayList();
406    m_cmdlineSuites.add(suite);
407    m_suites.add(suite);
408  }
409
410  /**
411   * Set the test classes to be run by this TestNG object. This method will create a dummy suite
412   * that will wrap these classes called "Command Line Test".
413   *
414   * <p>If used together with threadCount, parallel, groups, excludedGroups than this one must be
415   * set first.
416   *
417   * @param classes An array of classes that contain TestNG annotations.
418   */
419  public void setTestClasses(Class[] classes) {
420    m_suites.clear();
421    m_commandLineTestClasses = classes;
422  }
423
424  /**
425   * Given a string com.example.Foo.f1, return an array where [0] is the class and [1] is the
426   * method.
427   */
428  private String[] splitMethod(String m) {
429    int index = m.lastIndexOf(".");
430    if (index < 0) {
431      throw new TestNGException(
432          "Bad format for command line method:" + m + ", expected <class>.<method>");
433    }
434
435    return new String[] {m.substring(0, index), m.substring(index + 1).replaceAll("\\*", "\\.\\*")};
436  }
437
438  /**
439   * @return a list of XmlSuite objects that represent the list of classes and methods passed in
440   *     parameter.
441   * @param commandLineMethods a string with the form "com.example.Foo.f1,com.example.Bar.f2"
442   */
443  private List<XmlSuite> createCommandLineSuitesForMethods(List<String> commandLineMethods) {
444    //
445    // Create the <classes> tag
446    //
447    Set<Class> classes = Sets.newHashSet();
448    for (String m : commandLineMethods) {
449      Class c = ClassHelper.forName(splitMethod(m)[0]);
450      if (c != null) {
451        classes.add(c);
452      }
453    }
454
455    List<XmlSuite> result = createCommandLineSuitesForClasses(classes.toArray(new Class[0]));
456
457    //
458    // Add the method tags
459    //
460    List<XmlClass> xmlClasses = Lists.newArrayList();
461    for (XmlSuite s : result) {
462      for (XmlTest t : s.getTests()) {
463        xmlClasses.addAll(t.getClasses());
464      }
465    }
466
467    for (XmlClass xc : xmlClasses) {
468      for (String m : commandLineMethods) {
469        String[] split = splitMethod(m);
470        String className = split[0];
471        if (xc.getName().equals(className)) {
472          XmlInclude includedMethod = new XmlInclude(split[1]);
473          xc.getIncludedMethods().add(includedMethod);
474        }
475      }
476    }
477
478    return result;
479  }
480
481  private List<XmlSuite> createCommandLineSuitesForClasses(Class[] classes) {
482    //
483    // See if any of the classes has an xmlSuite or xmlTest attribute.
484    // If it does, create the appropriate XmlSuite, otherwise, create
485    // the default one
486    //
487    XmlClass[] xmlClasses = Utils.classesToXmlClasses(classes);
488    Map<String, XmlSuite> suites = Maps.newHashMap();
489    IAnnotationFinder finder = m_configuration.getAnnotationFinder();
490
491    for (int i = 0; i < classes.length; i++) {
492      Class c = classes[i];
493      ITestAnnotation test = finder.findAnnotation(c, ITestAnnotation.class);
494      String suiteName = getDefaultSuiteName();
495      String testName = getDefaultTestName();
496      boolean isJUnit = false;
497      if (test != null) {
498        suiteName = defaultIfStringEmpty(test.getSuiteName(), suiteName);
499        testName = defaultIfStringEmpty(test.getTestName(), testName);
500      } else {
501        if (m_isMixed && JUnitTestFinder.isJUnitTest(c)) {
502          isJUnit = true;
503          testName = c.getName();
504        }
505      }
506      XmlSuite xmlSuite = suites.get(suiteName);
507      if (xmlSuite == null) {
508        xmlSuite = new XmlSuite();
509        xmlSuite.setName(suiteName);
510        suites.put(suiteName, xmlSuite);
511      }
512
513      if (m_dataProviderThreadCount != null) {
514        xmlSuite.setDataProviderThreadCount(m_dataProviderThreadCount);
515      }
516      XmlTest xmlTest = null;
517      for (XmlTest xt : xmlSuite.getTests()) {
518        if (xt.getName().equals(testName)) {
519          xmlTest = xt;
520          break;
521        }
522      }
523
524      if (xmlTest == null) {
525        xmlTest = new XmlTest(xmlSuite);
526        xmlTest.setName(testName);
527        xmlTest.setJUnit(isJUnit);
528      }
529
530      xmlTest.getXmlClasses().add(xmlClasses[i]);
531    }
532
533    return new ArrayList<>(suites.values());
534  }
535
536  public void addMethodSelector(String className, int priority) {
537    if (Strings.isNotNullAndNotEmpty(className)) {
538      m_methodDescriptors.put(className, priority);
539    }
540  }
541
542  public void addMethodSelector(XmlMethodSelector selector) {
543    m_selectors.add(selector);
544  }
545
546  /**
547   * Set the suites file names to be run by this TestNG object. This method tries to load and parse
548   * the specified TestNG suite xml files. If a file is missing, it is ignored.
549   *
550   * @param suites A list of paths to one more XML files defining the tests. For example:
551   *     <pre>
552   * TestNG tng = new TestNG();
553   * List<String> suites = Lists.newArrayList();
554   * suites.add("c:/tests/testng1.xml");
555   * suites.add("c:/tests/testng2.xml");
556   * tng.setTestSuites(suites);
557   * tng.run();
558   * </pre>
559   */
560  public void setTestSuites(List<String> suites) {
561    m_stringSuites = suites;
562  }
563
564  /**
565   * Specifies the XmlSuite objects to run.
566   *
567   * @param suites
568   * @see org.testng.xml.XmlSuite
569   */
570  public void setXmlSuites(List<XmlSuite> suites) {
571    m_suites = suites;
572  }
573
574  /**
575   * Define which groups will be excluded from this run.
576   *
577   * @param groups A list of group names separated by a comma.
578   */
579  public void setExcludedGroups(String groups) {
580    m_excludedGroups = Utils.split(groups, ",");
581  }
582
583  /**
584   * Define which groups will be included from this run.
585   *
586   * @param groups A list of group names separated by a comma.
587   */
588  public void setGroups(String groups) {
589    m_includedGroups = Utils.split(groups, ",");
590  }
591
592  private void setTestRunnerFactoryClass(Class testRunnerFactoryClass) {
593    setTestRunnerFactory((ITestRunnerFactory) ClassHelper.newInstance(testRunnerFactoryClass));
594  }
595
596  protected void setTestRunnerFactory(ITestRunnerFactory itrf) {
597    m_testRunnerFactory = itrf;
598  }
599
600  public void setObjectFactory(Class c) {
601    m_objectFactory = (ITestObjectFactory) ClassHelper.newInstance(c);
602  }
603
604  public void setObjectFactory(ITestObjectFactory factory) {
605    m_objectFactory = factory;
606  }
607
608  /**
609   * Define which listeners to user for this run.
610   *
611   * @param classes A list of classes, which must be either ISuiteListener, ITestListener or
612   *     IReporter
613   */
614  public void setListenerClasses(List<Class<? extends ITestNGListener>> classes) {
615    for (Class<? extends ITestNGListener> cls : classes) {
616      addListener(ClassHelper.newInstance(cls));
617    }
618  }
619
620  /** @deprecated Use addListener(ITestNGListener) instead */
621  // TODO remove later /!\ Caution: IntelliJ is using it. Check with @akozlova before removing it
622  @Deprecated
623  public void addListener(Object listener) {
624    if (!(listener instanceof ITestNGListener)) {
625      exitWithError(
626          "Listener "
627              + listener
628              + " must be one of ITestListener, ISuiteListener, IReporter, "
629              + " IAnnotationTransformer, IMethodInterceptor or IInvokedMethodListener");
630    }
631    addListener((ITestNGListener) listener);
632  }
633
634  private static <E> void maybeAddListener(Map<Class<? extends E>, E> map, E value) {
635    maybeAddListener(map, (Class<? extends E>) value.getClass(), value, false);
636  }
637
638  private static <E> void maybeAddListener(
639      Map<Class<? extends E>, E> map, Class<? extends E> type, E value, boolean quiet) {
640    if (map.containsKey(type)) {
641      if (!quiet) {
642        LOGGER.warn("Ignoring duplicate listener : " + type.getName());
643      }
644    } else {
645      map.put(type, value);
646    }
647  }
648
649  public void addListener(ITestNGListener listener) {
650    if (listener == null) {
651      return;
652    }
653    if (listener instanceof IExecutionVisualiser) {
654      IExecutionVisualiser visualiser = (IExecutionVisualiser) listener;
655      maybeAddListener(m_executionVisualisers, visualiser);
656    }
657    if (listener instanceof ISuiteListener) {
658      ISuiteListener suite = (ISuiteListener) listener;
659      maybeAddListener(m_suiteListeners, suite);
660    }
661    if (listener instanceof ITestListener) {
662      ITestListener test = (ITestListener) listener;
663      maybeAddListener(m_testListeners, test);
664    }
665    if (listener instanceof IClassListener) {
666      IClassListener clazz = (IClassListener) listener;
667      maybeAddListener(m_classListeners, clazz);
668    }
669    if (listener instanceof IReporter) {
670      IReporter reporter = (IReporter) listener;
671      maybeAddListener(m_reporters, reporter);
672    }
673    if (listener instanceof IAnnotationTransformer) {
674      setAnnotationTransformer((IAnnotationTransformer) listener);
675    }
676    if (listener instanceof IMethodInterceptor) {
677      m_methodInterceptors.add((IMethodInterceptor) listener);
678    }
679    if (listener instanceof IInvokedMethodListener) {
680      IInvokedMethodListener method = (IInvokedMethodListener) listener;
681      maybeAddListener(m_invokedMethodListeners, method);
682    }
683    if (listener instanceof IHookable) {
684      setHookable((IHookable) listener);
685    }
686    if (listener instanceof IConfigurable) {
687      setConfigurable((IConfigurable) listener);
688    }
689    if (listener instanceof IExecutionListener) {
690      m_configuration.addExecutionListenerIfAbsent((IExecutionListener) listener);
691    }
692    if (listener instanceof IConfigurationListener) {
693      m_configuration.addConfigurationListener((IConfigurationListener) listener);
694    }
695    if (listener instanceof IAlterSuiteListener) {
696      IAlterSuiteListener alter = (IAlterSuiteListener) listener;
697      maybeAddListener(m_alterSuiteListeners, alter);
698    }
699    if (listener instanceof IDataProviderListener) {
700      IDataProviderListener dataProvider = (IDataProviderListener) listener;
701      maybeAddListener(m_dataProviderListeners, dataProvider);
702    }
703  }
704
705  public Set<IReporter> getReporters() {
706    // This will now cause a different behavior for consumers of this method because unlike before
707    // they are no longer
708    // going to be getting the original set but only a copy of it (since we internally moved from
709    // Sets to Maps)
710    return Sets.newHashSet(m_reporters.values());
711  }
712
713  public List<ITestListener> getTestListeners() {
714    return Lists.newArrayList(m_testListeners.values());
715  }
716
717  public List<ISuiteListener> getSuiteListeners() {
718    return Lists.newArrayList(m_suiteListeners.values());
719  }
720
721  /** If m_verbose gets set, it will override the verbose setting in testng.xml */
722  private Integer m_verbose = null;
723
724  private final IAnnotationTransformer m_defaultAnnoProcessor = new DefaultAnnotationTransformer();
725  private IAnnotationTransformer m_annotationTransformer = m_defaultAnnoProcessor;
726
727  private Boolean m_skipFailedInvocationCounts = false;
728
729  private List<IMethodInterceptor> m_methodInterceptors = Lists.newArrayList();
730
731  /** The list of test names to run from the given suite */
732  private List<String> m_testNames;
733
734  private Integer m_suiteThreadPoolSize = CommandLineArgs.SUITE_THREAD_POOL_SIZE_DEFAULT;
735
736  private boolean m_randomizeSuites = Boolean.FALSE;
737
738  private Boolean m_preserveOrder = XmlSuite.DEFAULT_PRESERVE_ORDER;
739  private Boolean m_groupByInstances;
740
741  private IConfiguration m_configuration;
742
743  /**
744   * Sets the level of verbosity. This value will override the value specified in the test suites.
745   *
746   * @param verbose the verbosity level (0 to 10 where 10 is most detailed) Actually, this is a lie:
747   *     you can specify -1 and this will put TestNG in debug mode (no longer slicing off stack
748   *     traces and all).
749   */
750  public void setVerbose(int verbose) {
751    m_verbose = verbose;
752  }
753
754  private void initializeCommandLineSuites() {
755    if (m_commandLineTestClasses != null || m_commandLineMethods != null) {
756      if (null != m_commandLineMethods) {
757        m_cmdlineSuites = createCommandLineSuitesForMethods(m_commandLineMethods);
758      } else {
759        m_cmdlineSuites = createCommandLineSuitesForClasses(m_commandLineTestClasses);
760      }
761
762      for (XmlSuite s : m_cmdlineSuites) {
763        for (XmlTest t : s.getTests()) {
764          t.setPreserveOrder(m_preserveOrder);
765        }
766        m_suites.add(s);
767        if (m_groupByInstances != null) {
768          s.setGroupByInstances(m_groupByInstances);
769        }
770      }
771    }
772  }
773
774  private void initializeCommandLineSuitesParams() {
775    if (null == m_cmdlineSuites) {
776      return;
777    }
778
779    for (XmlSuite s : m_cmdlineSuites) {
780      if (m_threadCount != -1) {
781        s.setThreadCount(m_threadCount);
782      }
783      if (m_parallelMode != null) {
784        s.setParallel(m_parallelMode);
785      }
786      if (m_configFailurePolicy != null) {
787        s.setConfigFailurePolicy(m_configFailurePolicy);
788      }
789    }
790  }
791
792  private void initializeCommandLineSuitesGroups() {
793    // If groups were specified on the command line, they should override groups
794    // specified in the XML file
795    boolean hasIncludedGroups = null != m_includedGroups && m_includedGroups.length > 0;
796    boolean hasExcludedGroups = null != m_excludedGroups && m_excludedGroups.length > 0;
797    List<XmlSuite> suites = m_cmdlineSuites != null ? m_cmdlineSuites : m_suites;
798    if (hasIncludedGroups || hasExcludedGroups) {
799      for (XmlSuite s : suites) {
800        initializeCommandLineSuitesGroups(
801            s, hasIncludedGroups, m_includedGroups, hasExcludedGroups, m_excludedGroups);
802      }
803    }
804  }
805
806  private static void initializeCommandLineSuitesGroups(
807      XmlSuite s,
808      boolean hasIncludedGroups,
809      String[] m_includedGroups,
810      boolean hasExcludedGroups,
811      String[] m_excludedGroups) {
812    if (hasIncludedGroups) {
813      s.setIncludedGroups(Arrays.asList(m_includedGroups));
814    }
815    if (hasExcludedGroups) {
816      s.setExcludedGroups(Arrays.asList(m_excludedGroups));
817    }
818    for (XmlSuite child : s.getChildSuites()) {
819      initializeCommandLineSuitesGroups(
820          child, hasIncludedGroups, m_includedGroups, hasExcludedGroups, m_excludedGroups);
821    }
822  }
823
824  private void addReporter(Class<? extends IReporter> r) {
825    if (!m_reporters.containsKey(r)) {
826      m_reporters.put(r, ClassHelper.newInstance(r));
827    }
828  }
829
830  private void initializeDefaultListeners() {
831    addListener(this.exitCodeListener);
832    if (m_useDefaultListeners) {
833      addReporter(SuiteHTMLReporter.class);
834      addReporter(Main.class);
835      addReporter(FailedReporter.class);
836      addReporter(XMLReporter.class);
837      if (RuntimeBehavior.useOldTestNGEmailableReporter()) {
838        addReporter(EmailableReporter.class);
839      } else if (RuntimeBehavior.useEmailableReporter()) {
840        addReporter(EmailableReporter2.class);
841      }
842      addReporter(JUnitReportReporter.class);
843      if (m_verbose != null && m_verbose > 4) {
844        addListener(new VerboseReporter("[TestNG] "));
845      }
846    }
847  }
848
849  private void initializeConfiguration() {
850    ITestObjectFactory factory = m_objectFactory;
851    //
852    // Install the listeners found in ServiceLoader (or use the class
853    // loader for tests, if specified).
854    //
855    addServiceLoaderListeners();
856
857    //
858    // Install the listeners found in the suites
859    //
860    for (XmlSuite s : m_suites) {
861      addListeners(s);
862
863      //
864      // Install the method selectors
865      //
866      for (XmlMethodSelector methodSelector : s.getMethodSelectors()) {
867        addMethodSelector(methodSelector.getClassName(), methodSelector.getPriority());
868        addMethodSelector(methodSelector);
869      }
870
871      //
872      // Find if we have an object factory
873      //
874      if (s.getObjectFactory() != null) {
875        if (factory == null) {
876          factory = s.getObjectFactory();
877        } else {
878          throw new TestNGException("Found more than one object-factory tag in your suites");
879        }
880      }
881    }
882
883    m_configuration.setAnnotationFinder(new JDK15AnnotationFinder(getAnnotationTransformer()));
884    m_configuration.setHookable(m_hookable);
885    m_configuration.setConfigurable(m_configurable);
886    m_configuration.setObjectFactory(factory);
887  }
888
889  private void addListeners(XmlSuite s) {
890    for (String listenerName : s.getListeners()) {
891      Class<?> listenerClass = ClassHelper.forName(listenerName);
892
893      // If specified listener does not exist, a TestNGException will be thrown
894      if (listenerClass == null) {
895        throw new TestNGException(
896            "Listener " + listenerName + " was not found in project's classpath");
897      }
898
899      ITestNGListener listener = (ITestNGListener) ClassHelper.newInstance(listenerClass);
900      addListener(listener);
901    }
902
903    // Add the child suite listeners
904    List<XmlSuite> childSuites = s.getChildSuites();
905    for (XmlSuite c : childSuites) {
906      addListeners(c);
907    }
908  }
909
910  /** Using reflection to remain Java 5 compliant. */
911  private void addServiceLoaderListeners() {
912    Iterable<ITestNGListener> loader =
913        m_serviceLoaderClassLoader != null
914            ? ServiceLoader.load(ITestNGListener.class, m_serviceLoaderClassLoader)
915            : ServiceLoader.load(ITestNGListener.class);
916    for (ITestNGListener l : loader) {
917      Utils.log("[TestNG]", 2, "Adding ServiceLoader listener:" + l);
918      addListener(l);
919      addServiceLoaderListener(l);
920    }
921  }
922
923  /**
924   * Before suites are executed, do a sanity check to ensure all required conditions are met. If
925   * not, throw an exception to stop test execution
926   *
927   * @throws TestNGException if the sanity check fails
928   */
929  private void sanityCheck() {
930    XmlSuiteUtils.validateIfSuitesContainDuplicateTests(m_suites);
931    XmlSuiteUtils.adjustSuiteNamesToEnsureUniqueness(m_suites);
932  }
933
934  /** Invoked by the remote runner. */
935  public void initializeEverything() {
936    // The Eclipse plug-in (RemoteTestNG) might have invoked this method already
937    // so don't initialize suites twice.
938    if (m_isInitialized) {
939      return;
940    }
941
942    initializeSuitesAndJarFile();
943    initializeConfiguration();
944    initializeDefaultListeners();
945    initializeCommandLineSuites();
946    initializeCommandLineSuitesParams();
947    initializeCommandLineSuitesGroups();
948
949    m_isInitialized = true;
950  }
951
952  /** Run TestNG. */
953  public void run() {
954    initializeEverything();
955    sanityCheck();
956
957    runExecutionListeners(true /* start */);
958
959    runSuiteAlterationListeners();
960
961    m_start = System.currentTimeMillis();
962    List<ISuite> suiteRunners = runSuites();
963
964    m_end = System.currentTimeMillis();
965
966    if (null != suiteRunners) {
967      generateReports(suiteRunners);
968    }
969
970    runExecutionListeners(false /* finish */);
971    exitCode = this.exitCodeListener.getStatus();
972
973    if (exitCodeListener.noTestsFound()) {
974      if (TestRunner.getVerbose() > 1) {
975        System.err.println("[TestNG] No tests found. Nothing was run");
976        usage();
977      }
978    }
979
980    m_instance = null;
981    m_jCommander = null;
982  }
983
984  /**
985   * Run the test suites.
986   *
987   * <p>This method can be overridden by subclass. <br>
988   * For example, DistributedTestNG to run in master/slave mode according to commandline args.
989   *
990   * @return - List of suites that were run as {@link ISuite} objects.
991   * @since 6.9.11 when moving distributed/remote classes out into separate project
992   */
993  protected List<ISuite> runSuites() {
994    return runSuitesLocally();
995  }
996
997  private void runSuiteAlterationListeners() {
998    for (IAlterSuiteListener l : m_alterSuiteListeners.values()) {
999      l.alter(m_suites);
1000    }
1001  }
1002
1003  private void runExecutionListeners(boolean start) {
1004    for (IExecutionListener l : m_configuration.getExecutionListeners()) {
1005      if (start) {
1006        l.onExecutionStart();
1007      } else {
1008        l.onExecutionFinish();
1009      }
1010    }
1011  }
1012
1013  private static void usage() {
1014    if (m_jCommander == null) {
1015      m_jCommander = new JCommander(new CommandLineArgs());
1016    }
1017    m_jCommander.usage();
1018  }
1019
1020  private void generateReports(List<ISuite> suiteRunners) {
1021    for (IReporter reporter : m_reporters.values()) {
1022      try {
1023        long start = System.currentTimeMillis();
1024        reporter.generateReport(m_suites, suiteRunners, m_outputDir);
1025        Utils.log(
1026            "TestNG",
1027            2,
1028            "Time taken by " + reporter + ": " + (System.currentTimeMillis() - start) + " ms");
1029      } catch (Exception ex) {
1030        System.err.println("[TestNG] Reporter " + reporter + " failed");
1031        ex.printStackTrace(System.err);
1032      }
1033    }
1034  }
1035
1036  /**
1037   * This needs to be public for maven2, for now..At least until an alternative mechanism is found.
1038   */
1039  public List<ISuite> runSuitesLocally() {
1040    if (m_suites.isEmpty()) {
1041      error("No test suite found. Nothing to run");
1042      usage();
1043      return Collections.emptyList();
1044    }
1045
1046    SuiteRunnerMap suiteRunnerMap = new SuiteRunnerMap();
1047
1048    if (m_suites.get(0).getVerbose() >= 2) {
1049      Version.displayBanner();
1050    }
1051
1052    // First initialize the suite runners to ensure there are no configuration issues.
1053    // Create a map with XmlSuite as key and corresponding SuiteRunner as value
1054    for (XmlSuite xmlSuite : m_suites) {
1055      createSuiteRunners(suiteRunnerMap, xmlSuite);
1056    }
1057
1058    //
1059    // Run suites
1060    //
1061    if (m_suiteThreadPoolSize == 1 && !m_randomizeSuites) {
1062      // Single threaded and not randomized: run the suites in order
1063      for (XmlSuite xmlSuite : m_suites) {
1064        runSuitesSequentially(
1065            xmlSuite, suiteRunnerMap, getVerbose(xmlSuite), getDefaultSuiteName());
1066      }
1067      //
1068      // Generate the suites report
1069      //
1070      return Lists.newArrayList(suiteRunnerMap.values());
1071    }
1072    // Multithreaded: generate a dynamic graph that stores the suite hierarchy. This is then
1073    // used to run related suites in specific order. Parent suites are run only
1074    // once all the child suites have completed execution
1075    DynamicGraph<ISuite> suiteGraph = new DynamicGraph<>();
1076    for (XmlSuite xmlSuite : m_suites) {
1077      populateSuiteGraph(suiteGraph, suiteRunnerMap, xmlSuite);
1078    }
1079
1080    IThreadWorkerFactory<ISuite> factory =
1081        new SuiteWorkerFactory(
1082            suiteRunnerMap, 0 /* verbose hasn't been set yet */, getDefaultSuiteName());
1083    GraphThreadPoolExecutor<ISuite> pooledExecutor =
1084        new GraphThreadPoolExecutor<>(
1085            "suites",
1086            suiteGraph,
1087            factory,
1088            m_suiteThreadPoolSize,
1089            m_suiteThreadPoolSize,
1090            Integer.MAX_VALUE,
1091            TimeUnit.MILLISECONDS,
1092            new LinkedBlockingQueue<>());
1093
1094    Utils.log("TestNG", 2, "Starting executor for all suites");
1095    // Run all suites in parallel
1096    pooledExecutor.run();
1097    try {
1098      pooledExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
1099      pooledExecutor.shutdownNow();
1100    } catch (InterruptedException handled) {
1101      Thread.currentThread().interrupt();
1102      error("Error waiting for concurrent executors to finish " + handled.getMessage());
1103    }
1104
1105    //
1106    // Generate the suites report
1107    //
1108    return Lists.newArrayList(suiteRunnerMap.values());
1109  }
1110
1111  private static void error(String s) {
1112    LOGGER.error(s);
1113  }
1114
1115  /**
1116   * @return the verbose level, checking in order: the verbose level on the suite, the verbose level
1117   *     on the TestNG object, or 1.
1118   */
1119  private int getVerbose(XmlSuite xmlSuite) {
1120    return xmlSuite.getVerbose() != null
1121        ? xmlSuite.getVerbose()
1122        : (m_verbose != null ? m_verbose : DEFAULT_VERBOSE);
1123  }
1124
1125  /**
1126   * Recursively runs suites. Runs the children suites before running the parent suite. This is done
1127   * so that the results for parent suite can reflect the combined results of the children suites.
1128   *
1129   * @param xmlSuite XML Suite to be executed
1130   * @param suiteRunnerMap Maps {@code XmlSuite}s to respective {@code ISuite}
1131   * @param verbose verbose level
1132   * @param defaultSuiteName default suite name
1133   */
1134  private void runSuitesSequentially(
1135      XmlSuite xmlSuite, SuiteRunnerMap suiteRunnerMap, int verbose, String defaultSuiteName) {
1136    for (XmlSuite childSuite : xmlSuite.getChildSuites()) {
1137      runSuitesSequentially(childSuite, suiteRunnerMap, verbose, defaultSuiteName);
1138    }
1139    SuiteRunnerWorker srw =
1140        new SuiteRunnerWorker(
1141            suiteRunnerMap.get(xmlSuite), suiteRunnerMap, verbose, defaultSuiteName);
1142    srw.run();
1143  }
1144
1145  /**
1146   * Populates the dynamic graph with the reverse hierarchy of suites. Edges are added pointing from
1147   * child suite runners to parent suite runners, hence making parent suite runners dependent on all
1148   * the child suite runners
1149   *
1150   * @param suiteGraph dynamic graph representing the reverse hierarchy of SuiteRunners
1151   * @param suiteRunnerMap Map with XMLSuite as key and its respective SuiteRunner as value
1152   * @param xmlSuite XML Suite
1153   */
1154  private void populateSuiteGraph(
1155      DynamicGraph<ISuite> suiteGraph /* OUT */, SuiteRunnerMap suiteRunnerMap, XmlSuite xmlSuite) {
1156    ISuite parentSuiteRunner = suiteRunnerMap.get(xmlSuite);
1157    if (xmlSuite.getChildSuites().isEmpty()) {
1158      suiteGraph.addNode(parentSuiteRunner);
1159    } else {
1160      for (XmlSuite childSuite : xmlSuite.getChildSuites()) {
1161        suiteGraph.addEdge(0, parentSuiteRunner, suiteRunnerMap.get(childSuite));
1162        populateSuiteGraph(suiteGraph, suiteRunnerMap, childSuite);
1163      }
1164    }
1165  }
1166
1167  /**
1168   * Creates the {@code SuiteRunner}s and populates the suite runner map with this information
1169   *
1170   * @param suiteRunnerMap Map with XMLSuite as key and it's respective SuiteRunner as value. This
1171   *     is updated as part of this method call
1172   * @param xmlSuite Xml Suite (and its children) for which {@code SuiteRunner}s are created
1173   */
1174  private void createSuiteRunners(SuiteRunnerMap suiteRunnerMap /* OUT */, XmlSuite xmlSuite) {
1175    if (null != m_isJUnit && !m_isJUnit.equals(XmlSuite.DEFAULT_JUNIT)) {
1176      xmlSuite.setJUnit(m_isJUnit);
1177    }
1178
1179    // If the skip flag was invoked on the command line, it
1180    // takes precedence
1181    if (null != m_skipFailedInvocationCounts) {
1182      xmlSuite.setSkipFailedInvocationCounts(m_skipFailedInvocationCounts);
1183    }
1184
1185    // Override the XmlSuite verbose value with the one from TestNG
1186    if (m_verbose != null) {
1187      xmlSuite.setVerbose(m_verbose);
1188    }
1189
1190    if (null != m_configFailurePolicy) {
1191      xmlSuite.setConfigFailurePolicy(m_configFailurePolicy);
1192    }
1193
1194    for (XmlTest t : xmlSuite.getTests()) {
1195      for (Map.Entry<String, Integer> ms : m_methodDescriptors.entrySet()) {
1196        XmlMethodSelector xms = new XmlMethodSelector();
1197        xms.setName(ms.getKey());
1198        xms.setPriority(ms.getValue());
1199        t.getMethodSelectors().add(xms);
1200      }
1201      for (XmlMethodSelector selector : m_selectors) {
1202        t.getMethodSelectors().add(selector);
1203      }
1204    }
1205
1206    suiteRunnerMap.put(xmlSuite, createSuiteRunner(xmlSuite));
1207
1208    for (XmlSuite childSuite : xmlSuite.getChildSuites()) {
1209      createSuiteRunners(suiteRunnerMap, childSuite);
1210    }
1211  }
1212
1213  /** Creates a suite runner and configures its initial state */
1214  private SuiteRunner createSuiteRunner(XmlSuite xmlSuite) {
1215    SuiteRunner result =
1216        new SuiteRunner(
1217            getConfiguration(),
1218            xmlSuite,
1219            m_outputDir,
1220            m_testRunnerFactory,
1221            m_useDefaultListeners,
1222            m_methodInterceptors,
1223            m_invokedMethodListeners.values(),
1224            m_testListeners.values(),
1225            m_classListeners.values(),
1226            m_dataProviderListeners,
1227            Systematiser.getComparator());
1228
1229    for (ISuiteListener isl : m_suiteListeners.values()) {
1230      result.addListener(isl);
1231    }
1232
1233    for (IReporter r : result.getReporters()) {
1234      maybeAddListener(m_reporters, r.getClass(), r, true);
1235    }
1236
1237    for (IConfigurationListener cl : m_configuration.getConfigurationListeners()) {
1238      result.addConfigurationListener(cl);
1239    }
1240
1241    m_executionVisualisers.values().forEach(result::addListener);
1242
1243    return result;
1244  }
1245
1246  protected IConfiguration getConfiguration() {
1247    return m_configuration;
1248  }
1249
1250  /**
1251   * The TestNG entry point for command line execution.
1252   *
1253   * @param argv the TestNG command line parameters.
1254   */
1255  public static void main(String[] argv) {
1256    TestNG testng = privateMain(argv, null);
1257    System.exit(testng.getStatus());
1258  }
1259
1260  /**
1261   * <B>Note</B>: this method is not part of the public API and is meant for internal usage only.
1262   */
1263  public static TestNG privateMain(String[] argv, ITestListener listener) {
1264    TestNG result = new TestNG();
1265
1266    if (null != listener) {
1267      result.addListener(listener);
1268    }
1269
1270    //
1271    // Parse the arguments
1272    //
1273    try {
1274      CommandLineArgs cla = new CommandLineArgs();
1275      m_jCommander = new JCommander(cla, argv);
1276      validateCommandLineParameters(cla);
1277      result.configure(cla);
1278    } catch (ParameterException ex) {
1279      exitWithError(ex.getMessage());
1280    }
1281
1282    //
1283    // Run
1284    //
1285    try {
1286      result.run();
1287    } catch (TestNGException ex) {
1288      if (TestRunner.getVerbose() > 1) {
1289        ex.printStackTrace(System.out);
1290      } else {
1291        error(ex.getMessage());
1292      }
1293      result.exitCode = ExitCode.newExitCodeRepresentingFailure();
1294    }
1295
1296    return result;
1297  }
1298
1299  /** Configure the TestNG instance based on the command line parameters. */
1300  protected void configure(CommandLineArgs cla) {
1301    if (cla.verbose != null) {
1302      setVerbose(cla.verbose);
1303    }
1304    setOutputDirectory(cla.outputDirectory);
1305
1306    String testClasses = cla.testClass;
1307    if (null != testClasses) {
1308      String[] strClasses = testClasses.split(",");
1309      List<Class> classes = Lists.newArrayList();
1310      for (String c : strClasses) {
1311        classes.add(ClassHelper.fileToClass(c));
1312      }
1313
1314      setTestClasses(classes.toArray(new Class[0]));
1315    }
1316
1317    setOutputDirectory(cla.outputDirectory);
1318
1319    if (cla.testNames != null) {
1320      setTestNames(Arrays.asList(cla.testNames.split(",")));
1321    }
1322
1323    // Note: can't use a Boolean field here because we are allowing a boolean
1324    // parameter with an arity of 1 ("-usedefaultlisteners false")
1325    if (cla.useDefaultListeners != null) {
1326      setUseDefaultListeners("true".equalsIgnoreCase(cla.useDefaultListeners));
1327    }
1328
1329    setGroups(cla.groups);
1330    setExcludedGroups(cla.excludedGroups);
1331    setTestJar(cla.testJar);
1332    setXmlPathInJar(cla.xmlPathInJar);
1333    setJUnit(cla.junit);
1334    setMixed(cla.mixed);
1335    setSkipFailedInvocationCounts(cla.skipFailedInvocationCounts);
1336    if (cla.parallelMode != null) {
1337      setParallel(cla.parallelMode);
1338    }
1339    if (cla.configFailurePolicy != null) {
1340      setConfigFailurePolicy(XmlSuite.FailurePolicy.getValidPolicy(cla.configFailurePolicy));
1341    }
1342    if (cla.threadCount != null) {
1343      setThreadCount(cla.threadCount);
1344    }
1345    if (cla.dataProviderThreadCount != null) {
1346      setDataProviderThreadCount(cla.dataProviderThreadCount);
1347    }
1348    if (cla.suiteName != null) {
1349      setDefaultSuiteName(cla.suiteName);
1350    }
1351    if (cla.testName != null) {
1352      setDefaultTestName(cla.testName);
1353    }
1354    if (cla.listener != null) {
1355      String sep = ";";
1356      if (cla.listener.contains(",")) {
1357        sep = ",";
1358      }
1359      String[] strs = Utils.split(cla.listener, sep);
1360      List<Class<? extends ITestNGListener>> classes = Lists.newArrayList();
1361
1362      for (String cls : strs) {
1363        Class<?> clazz = ClassHelper.fileToClass(cls);
1364        if (ITestNGListener.class.isAssignableFrom(clazz)) {
1365          classes.add((Class<? extends ITestNGListener>) clazz);
1366        }
1367      }
1368
1369      setListenerClasses(classes);
1370    }
1371
1372    if (null != cla.methodSelectors) {
1373      String[] strs = Utils.split(cla.methodSelectors, ",");
1374      for (String cls : strs) {
1375        String[] sel = Utils.split(cls, ":");
1376        try {
1377          if (sel.length == 2) {
1378            addMethodSelector(sel[0], Integer.parseInt(sel[1]));
1379          } else {
1380            error("Method selector value was not in the format org.example.Selector:4");
1381          }
1382        } catch (NumberFormatException nfe) {
1383          error("Method selector value was not in the format org.example.Selector:4");
1384        }
1385      }
1386    }
1387
1388    if (cla.objectFactory != null) {
1389      setObjectFactory(ClassHelper.fileToClass(cla.objectFactory));
1390    }
1391    if (cla.testRunnerFactory != null) {
1392      setTestRunnerFactoryClass(ClassHelper.fileToClass(cla.testRunnerFactory));
1393    }
1394
1395    if (cla.reporter != null) {
1396      ReporterConfig reporterConfig = ReporterConfig.deserialize(cla.reporter);
1397      addReporter(reporterConfig);
1398    }
1399
1400    if (cla.commandLineMethods.size() > 0) {
1401      m_commandLineMethods = cla.commandLineMethods;
1402    }
1403
1404    if (cla.suiteFiles != null) {
1405      setTestSuites(cla.suiteFiles);
1406    }
1407
1408    setSuiteThreadPoolSize(cla.suiteThreadPoolSize);
1409    setRandomizeSuites(cla.randomizeSuites);
1410  }
1411
1412  public void setSuiteThreadPoolSize(Integer suiteThreadPoolSize) {
1413    m_suiteThreadPoolSize = suiteThreadPoolSize;
1414  }
1415
1416  public Integer getSuiteThreadPoolSize() {
1417    return m_suiteThreadPoolSize;
1418  }
1419
1420  public void setRandomizeSuites(boolean randomizeSuites) {
1421    m_randomizeSuites = randomizeSuites;
1422  }
1423
1424  /**
1425   * This method is invoked by Maven's Surefire, only remove it once Surefire has been modified to
1426   * no longer call it.
1427   */
1428  public void setSourcePath(String path) {
1429    // nop
1430  }
1431
1432  private static int parseInt(Object value) {
1433    if (value == null) {
1434      return -1;
1435    }
1436    if (value instanceof String) {
1437      return Integer.parseInt(String.valueOf(value));
1438    }
1439    if (value instanceof Integer) {
1440      return (Integer) value;
1441    }
1442    throw new IllegalArgumentException("Unable to parse " + value + " as an Integer.");
1443  }
1444
1445  /**
1446   * This method is invoked by Maven's Surefire to configure the runner, do not remove unless you
1447   * know for sure that Surefire has been updated to use the new configure(CommandLineArgs) method.
1448   *
1449   * @deprecated use new configure(CommandLineArgs) method
1450   */
1451  @SuppressWarnings({"unchecked"})
1452  @Deprecated
1453  public void configure(Map cmdLineArgs) {
1454    CommandLineArgs result = new CommandLineArgs();
1455
1456    int value = parseInt(cmdLineArgs.get(CommandLineArgs.LOG));
1457    if (value != -1) {
1458      result.verbose = value;
1459    }
1460    result.outputDirectory = (String) cmdLineArgs.get(CommandLineArgs.OUTPUT_DIRECTORY);
1461
1462    String testClasses = (String) cmdLineArgs.get(CommandLineArgs.TEST_CLASS);
1463    if (null != testClasses) {
1464      result.testClass = testClasses;
1465    }
1466
1467    String testNames = (String) cmdLineArgs.get(CommandLineArgs.TEST_NAMES);
1468    if (testNames != null) {
1469      result.testNames = testNames;
1470    }
1471
1472    String useDefaultListeners = (String) cmdLineArgs.get(CommandLineArgs.USE_DEFAULT_LISTENERS);
1473    if (null != useDefaultListeners) {
1474      result.useDefaultListeners = useDefaultListeners;
1475    }
1476
1477    result.groups = (String) cmdLineArgs.get(CommandLineArgs.GROUPS);
1478    result.excludedGroups = (String) cmdLineArgs.get(CommandLineArgs.EXCLUDED_GROUPS);
1479    result.testJar = (String) cmdLineArgs.get(CommandLineArgs.TEST_JAR);
1480    result.xmlPathInJar = (String) cmdLineArgs.get(CommandLineArgs.XML_PATH_IN_JAR);
1481    result.junit = (Boolean) cmdLineArgs.get(CommandLineArgs.JUNIT);
1482    result.mixed = (Boolean) cmdLineArgs.get(CommandLineArgs.MIXED);
1483    result.skipFailedInvocationCounts =
1484        (Boolean) cmdLineArgs.get(CommandLineArgs.SKIP_FAILED_INVOCATION_COUNTS);
1485    String parallelMode = (String) cmdLineArgs.get(CommandLineArgs.PARALLEL);
1486    if (parallelMode != null) {
1487      result.parallelMode = XmlSuite.ParallelMode.getValidParallel(parallelMode);
1488    }
1489
1490    value = parseInt(cmdLineArgs.get(CommandLineArgs.THREAD_COUNT));
1491    if (value != -1) {
1492      result.threadCount = value;
1493    }
1494
1495    // Not supported by Surefire yet
1496    value = parseInt(cmdLineArgs.get(CommandLineArgs.DATA_PROVIDER_THREAD_COUNT));
1497    if (value != -1) {
1498      result.dataProviderThreadCount = value;
1499    }
1500    String defaultSuiteName = (String) cmdLineArgs.get(CommandLineArgs.SUITE_NAME);
1501    if (defaultSuiteName != null) {
1502      result.suiteName = defaultSuiteName;
1503    }
1504
1505    String defaultTestName = (String) cmdLineArgs.get(CommandLineArgs.TEST_NAME);
1506    if (defaultTestName != null) {
1507      result.testName = defaultTestName;
1508    }
1509
1510    Object listeners = cmdLineArgs.get(CommandLineArgs.LISTENER);
1511    if (listeners instanceof List) {
1512      result.listener = Utils.join((List<?>) listeners, ",");
1513    } else {
1514      result.listener = (String) listeners;
1515    }
1516
1517    String ms = (String) cmdLineArgs.get(CommandLineArgs.METHOD_SELECTORS);
1518    if (null != ms) {
1519      result.methodSelectors = ms;
1520    }
1521
1522    String objectFactory = (String) cmdLineArgs.get(CommandLineArgs.OBJECT_FACTORY);
1523    if (null != objectFactory) {
1524      result.objectFactory = objectFactory;
1525    }
1526
1527    String runnerFactory = (String) cmdLineArgs.get(CommandLineArgs.TEST_RUNNER_FACTORY);
1528    if (null != runnerFactory) {
1529      result.testRunnerFactory = runnerFactory;
1530    }
1531
1532    String reporterConfigs = (String) cmdLineArgs.get(CommandLineArgs.REPORTER);
1533    if (reporterConfigs != null) {
1534      result.reporter = reporterConfigs;
1535    }
1536
1537    String failurePolicy = (String) cmdLineArgs.get(CommandLineArgs.CONFIG_FAILURE_POLICY);
1538    if (failurePolicy != null) {
1539      result.configFailurePolicy = failurePolicy;
1540    }
1541
1542    value = parseInt(cmdLineArgs.get(CommandLineArgs.SUITE_THREAD_POOL_SIZE));
1543    if (value != -1) {
1544      result.suiteThreadPoolSize = value;
1545    }
1546
1547    configure(result);
1548  }
1549
1550  /** Only run the specified tests from the suite. */
1551  public void setTestNames(List<String> testNames) {
1552    m_testNames = testNames;
1553  }
1554
1555  public void setSkipFailedInvocationCounts(Boolean skip) {
1556    m_skipFailedInvocationCounts = skip;
1557  }
1558
1559  private void addReporter(ReporterConfig reporterConfig) {
1560    IReporter instance = reporterConfig.newReporterInstance();
1561    if (instance != null) {
1562      addListener(instance);
1563    } else {
1564      LOGGER.warn("Could not find reporter class : " + reporterConfig.getClassName());
1565    }
1566  }
1567
1568  /**
1569   * Specify if this run should be made in JUnit mode
1570   *
1571   * @param isJUnit
1572   */
1573  public void setJUnit(Boolean isJUnit) {
1574    m_isJUnit = isJUnit;
1575  }
1576
1577  /** Specify if this run should be made in mixed mode */
1578  public void setMixed(Boolean isMixed) {
1579    if (isMixed == null) {
1580      return;
1581    }
1582    m_isMixed = isMixed;
1583  }
1584
1585  /** Double check that the command line parameters are valid. */
1586  protected static void validateCommandLineParameters(CommandLineArgs args) {
1587    String testClasses = args.testClass;
1588    List<String> testNgXml = args.suiteFiles;
1589    String testJar = args.testJar;
1590    List<String> methods = args.commandLineMethods;
1591
1592    if (testClasses == null
1593        && testJar == null
1594        && (testNgXml == null || testNgXml.isEmpty())
1595        && (methods == null || methods.isEmpty())) {
1596      throw new ParameterException(
1597          "You need to specify at least one testng.xml, one class" + " or one method");
1598    }
1599
1600    String groups = args.groups;
1601    String excludedGroups = args.excludedGroups;
1602
1603    if (testJar == null
1604        && (null != groups || null != excludedGroups)
1605        && testClasses == null
1606        && (testNgXml == null || testNgXml.isEmpty())) {
1607      throw new ParameterException("Groups option should be used with testclass option");
1608    }
1609
1610    Boolean junit = args.junit;
1611    Boolean mixed = args.mixed;
1612    if (junit && mixed) {
1613      throw new ParameterException(
1614          CommandLineArgs.MIXED + " can't be combined with " + CommandLineArgs.JUNIT);
1615    }
1616  }
1617
1618  /** @return true if at least one test failed. */
1619  public boolean hasFailure() {
1620    return this.exitCode.hasFailure();
1621  }
1622
1623  /** @return true if at least one test failed within success percentage. */
1624  public boolean hasFailureWithinSuccessPercentage() {
1625    return this.exitCode.hasFailureWithinSuccessPercentage();
1626  }
1627
1628  /** @return true if at least one test was skipped. */
1629  public boolean hasSkip() {
1630    return this.exitCode.hasSkip();
1631  }
1632
1633  static void exitWithError(String msg) {
1634    System.err.println(msg);
1635    usage();
1636    System.exit(1);
1637  }
1638
1639  public String getOutputDirectory() {
1640    return m_outputDir;
1641  }
1642
1643  public IAnnotationTransformer getAnnotationTransformer() {
1644    return m_annotationTransformer;
1645  }
1646
1647  private void setAnnotationTransformer(IAnnotationTransformer t) {
1648    // compare by reference!
1649    if (m_annotationTransformer != m_defaultAnnoProcessor && m_annotationTransformer != t) {
1650      LOGGER.warn("AnnotationTransformer already set");
1651    }
1652    m_annotationTransformer = t;
1653  }
1654
1655  /** @return the defaultSuiteName */
1656  public String getDefaultSuiteName() {
1657    return m_defaultSuiteName;
1658  }
1659
1660  /** @param defaultSuiteName the defaultSuiteName to set */
1661  public void setDefaultSuiteName(String defaultSuiteName) {
1662    m_defaultSuiteName = defaultSuiteName;
1663  }
1664
1665  /** @return the defaultTestName */
1666  public String getDefaultTestName() {
1667    return m_defaultTestName;
1668  }
1669
1670  /** @param defaultTestName the defaultTestName to set */
1671  public void setDefaultTestName(String defaultTestName) {
1672    m_defaultTestName = defaultTestName;
1673  }
1674
1675  /**
1676   * Sets the policy for whether or not to ever invoke a configuration method again after it has
1677   * failed once. Possible values are defined in {@link XmlSuite}. The default value is {@link
1678   * org.testng.xml.XmlSuite.FailurePolicy#SKIP}
1679   *
1680   * @param failurePolicy the configuration failure policy
1681   */
1682  public void setConfigFailurePolicy(XmlSuite.FailurePolicy failurePolicy) {
1683    m_configFailurePolicy = failurePolicy;
1684  }
1685
1686  /**
1687   * Returns the configuration failure policy.
1688   *
1689   * @return config failure policy
1690   */
1691  public XmlSuite.FailurePolicy getConfigFailurePolicy() {
1692    return m_configFailurePolicy;
1693  }
1694
1695  // DEPRECATED: to be removed after a major version change
1696  /** @deprecated since 5.1 */
1697  @Deprecated
1698  public static TestNG getDefault() {
1699    return m_instance;
1700  }
1701
1702  private void setConfigurable(IConfigurable c) {
1703    // compare by reference!
1704    if (m_configurable != null && m_configurable != c) {
1705      LOGGER.warn("Configurable already set");
1706    }
1707    m_configurable = c;
1708  }
1709
1710  private void setHookable(IHookable h) {
1711    // compare by reference!
1712    if (m_hookable != null && m_hookable != h) {
1713      LOGGER.warn("Hookable already set");
1714    }
1715    m_hookable = h;
1716  }
1717
1718  public void setMethodInterceptor(IMethodInterceptor methodInterceptor) {
1719    m_methodInterceptors.add(methodInterceptor);
1720  }
1721
1722  public void setDataProviderThreadCount(int count) {
1723    m_dataProviderThreadCount = count;
1724  }
1725
1726  /** Add a class loader to the searchable loaders. */
1727  public void addClassLoader(final ClassLoader loader) {
1728    if (loader != null) {
1729      ClassHelper.addClassLoader(loader);
1730    }
1731  }
1732
1733  public void setPreserveOrder(boolean b) {
1734    m_preserveOrder = b;
1735  }
1736
1737  protected long getStart() {
1738    return m_start;
1739  }
1740
1741  protected long getEnd() {
1742    return m_end;
1743  }
1744
1745  public void setGroupByInstances(boolean b) {
1746    m_groupByInstances = b;
1747  }
1748
1749  /////
1750  // ServiceLoader testing
1751  //
1752
1753  private URLClassLoader m_serviceLoaderClassLoader;
1754  private Map<Class<? extends ITestNGListener>, ITestNGListener> serviceLoaderListeners =
1755      Maps.newHashMap();
1756
1757  /*
1758   * Used to test ServiceClassLoader
1759   */
1760  public void setServiceLoaderClassLoader(URLClassLoader ucl) {
1761    m_serviceLoaderClassLoader = ucl;
1762  }
1763
1764  /*
1765   * Used to test ServiceClassLoader
1766   */
1767  private void addServiceLoaderListener(ITestNGListener l) {
1768    if (!serviceLoaderListeners.containsKey(l.getClass())) {
1769      serviceLoaderListeners.put(l.getClass(), l);
1770    }
1771  }
1772
1773  /*
1774   * Used to test ServiceClassLoader
1775   */
1776  public List<ITestNGListener> getServiceLoaderListeners() {
1777    return Lists.newArrayList(serviceLoaderListeners.values());
1778  }
1779
1780  //
1781  // ServiceLoader testing
1782  /////
1783}
1784
Full Screen
copy
1<?xml version="1.0" encoding="UTF-8"?>
2<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3    <modelVersion>4.0.0</modelVersion>
4    <groupId>com.mysite</groupId>
5    <artifactId>myproject</artifactId>
6    <version>1.0-SNAPSHOT</version>
7    <packaging>jar</packaging>
8    <properties>
9        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
10        <maven.compiler.source>1.8</maven.compiler.source>
11        <maven.compiler.target>1.8</maven.compiler.target>
12    </properties>
13    <repositories>
14        <repository>
15            <id>repo</id>
16            <url>file://${project.basedir}/temp-repo</url>
17        </repository>
18    </repositories>
19    <dependencies>
20        <dependency>
21            <groupId>jni4net</groupId>
22            <artifactId>jni4net.j</artifactId>
23            <version>0.8.8.0</version>
24        </dependency>
25    </dependencies>
26    <build>
27        <plugins>
28            <plugin>
29                <groupId>org.apache.maven.plugins</groupId>
30                <artifactId>maven-dependency-plugin</artifactId>
31                <version>2.10</version>
32                <executions>
33                    <execution>
34                        <id>copy</id>
35                        <phase>package</phase>
36                        <goals>
37                            <goal>copy-dependencies</goal>
38                        </goals>
39                        <configuration>
40                            <outputDirectory>
41                                ${project.build.directory}/lib
42                            </outputDirectory>
43                        </configuration>
44                    </execution>
45                </executions>
46            </plugin>
47            <plugin>
48                <groupId>org.apache.maven.plugins</groupId>
49                <artifactId>maven-jar-plugin</artifactId>
50                <version>3.0.2</version>
51                <configuration>
52                    <archive>
53                        <manifest>
54                            <addClasspath>true</addClasspath>
55                            <classpathPrefix>lib/</classpathPrefix>
56                            <mainClass>com.mysite.myproject.Main</mainClass>
57                        </manifest>
58                    </archive>
59                </configuration>
60            </plugin>
61            <plugin>
62                <artifactId>maven-resources-plugin</artifactId>
63                <version>3.0.1</version>
64                <executions>
65                    <execution>
66                        <id>copy-resources</id>
67                        <phase>validate</phase>
68                        <goals>
69                            <goal>copy-resources</goal>
70                        </goals>
71                        <configuration>
72                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
73                            <resources>          
74                                <resource>
75                                    <directory>lib</directory>
76                                    <filtering>false</filtering>
77                                </resource>
78                            </resources>
79                        </configuration>            
80                    </execution>
81                </executions>
82            </plugin>
83        </plugins>
84    </build>
85</project>
86
Full Screen
copy
1    final Map<String, Object> collect = env.getPropertySources()
2        .stream()
3        .parallel()
4        .filter(EnumerablePropertySource.class::isInstance)
5        .map(EnumerablePropertySource.class::cast)
6        .map(EnumerablePropertySource::getPropertyNames)
7        .flatMap(Arrays::stream)
8        .collect(HashMap::new, (a, e) -> a.put(e, env.getRequiredProperty(e)), Map::putAll);
9    System.out.println(collect);
10
Full Screen
copy
1package de.idealo.ecommerce.order.history.config;
2
3import java.util.Arrays;
4import java.util.stream.StreamSupport;
5
6import org.slf4j.Logger;
7import org.slf4j.LoggerFactory;
8import org.springframework.context.event.ContextRefreshedEvent;
9import org.springframework.context.event.EventListener;
10import org.springframework.core.env.AbstractEnvironment;
11import org.springframework.core.env.EnumerablePropertySource;
12import org.springframework.core.env.Environment;
13import org.springframework.core.env.MutablePropertySources;
14import org.springframework.stereotype.Component;
15
16@Component
17public class PropertyLogger  {
18
19    private static final Logger LOGGER = LoggerFactory.getLogger(PropertyLogger.class);
20
21    @EventListener
22    public void handleContextRefresh(ContextRefreshedEvent event) {
23        final Environment env = event.getApplicationContext().getEnvironment();
24        LOGGER.info("====== Environment and configuration ======");
25        LOGGER.info("Active profiles: {}", Arrays.toString(env.getActiveProfiles()));
26        final MutablePropertySources sources = ((AbstractEnvironment) env).getPropertySources();
27        StreamSupport.stream(sources.spliterator(), false)
28                .filter(ps -> ps instanceof EnumerablePropertySource)
29                .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames())
30                .flatMap(Arrays::stream)
31                .distinct()
32                .filter(prop -> !(prop.contains("credentials") || prop.contains("password")))
33                .forEach(prop -> LOGGER.info("{}: {}", prop, env.getProperty(prop)));
34        LOGGER.info("===========================================");
35    }
36}
37
Full Screen
copy
1<dependency>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-actuator</artifactId>
4</dependency>
5
Full Screen
copy
1{
2  "profiles": [
3
4  ],
5  "bootstrap": {
6
7  },
8  "commandLineArgs": {
9
10  },
11  "servletContextInitParams": {
12
13  },
14  "systemProperties": {
15    "jboss.i18n.generate-proxies": "true",
16    "java.runtime.name": "Java(TM) SE Runtime Environment",
17    "java.protocol.handler.pkgs": "null|org.springframework.boot.loader",
18    ...
19  },
20  "systemEnvironment": {
21    "LOCALAPPDATA": "C:\\Windows\\system32\\config\\systemprofile\\AppData\\Local",
22    "PROCESSOR_LEVEL": "6",
23    "ProgramFiles": "C:\\Program Files",
24    "PUBLIC": "C:\\Users\\Public",
25    "NUMBER_OF_PROCESSORS": "2",
26    "windir": "C:\\Windows",
27    ...
28  },
29  "applicationConfig: [file:.\/application.yml]": {
30    "server.port": 11016,
31    "server.tomcat.access-log-enabled": true,
32    "server.tomcat.access-log-pattern": "%h %l %u %t \"%r\" %>s %b %D",
33    "server.tomcat.basedir": ".\/",
34    ...
35  },
36  "applicationConfig: [classpath:\/application.yml]": {
37    ...
38    "spring.messages.basename": "messages",
39    "spring.messages.cache-seconds": -1,
40    "spring.messages.encoding": "UTF-8"
41  },
42  "defaultProperties": {
43    "spring.application.name": "bootstrap"
44  }
45}
46
Full Screen
copy
1    <arguments>
2        <argument>-action</argument>
3        <argument>GetAppList</argument>
4        <argument>-vuser</argument>
5        <argument>${veracode.username}</argument>
6        <argument>-vpassword</argument>
7        <argument>${veracode.password}</argument>
8    </arguments>
9
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used methods in CommandLineArgs

    No methods found for this class 😞

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)