Best Testng code snippet using org.testng.xml.XmlPackage.equals
Source:SimpleBaseTest.java
1package test;2import org.testng.Assert;3import org.testng.ITestNGListener;4import org.testng.ITestNGMethod;5import org.testng.ITestResult;6import org.testng.TestNG;7import org.testng.TestNGException;8import org.testng.annotations.ITestAnnotation;9import org.testng.collections.Lists;10import org.testng.internal.annotations.AnnotationHelper;11import org.testng.internal.annotations.DefaultAnnotationTransformer;12import org.testng.internal.annotations.IAnnotationFinder;13import org.testng.internal.annotations.JDK15AnnotationFinder;14import org.testng.xml.Parser;15import org.testng.xml.XmlClass;16import org.testng.xml.XmlGroups;17import org.testng.xml.XmlInclude;18import org.testng.xml.XmlPackage;19import org.testng.xml.XmlRun;20import org.testng.xml.XmlSuite;21import org.testng.xml.XmlTest;22import java.io.BufferedReader;23import java.io.File;24import java.io.FileReader;25import java.io.IOException;26import java.io.Reader;27import java.nio.file.FileVisitResult;28import java.nio.file.Files;29import java.nio.file.Path;30import java.nio.file.SimpleFileVisitor;31import java.nio.file.attribute.BasicFileAttributes;32import java.util.ArrayList;33import java.util.Arrays;34import java.util.List;35import java.util.Map;36import java.util.UUID;37import java.util.regex.Pattern;38public class SimpleBaseTest {39 // System property specifying where the resources (e.g. xml files) can be found40 private static final String TEST_RESOURCES_DIR = "test.resources.dir";41 public static InvokedMethodNameListener run(Class<?>... testClasses) {42 return run(false, testClasses);43 }44 public static InvokedMethodNameListener run(boolean skipConfiguration, Class<?>... testClasses) {45 TestNG tng = create(testClasses);46 return run(skipConfiguration, tng);47 }48 public static InvokedMethodNameListener run(XmlSuite... suites) {49 return run(false, suites);50 }51 public static InvokedMethodNameListener run(boolean skipConfiguration, XmlSuite... suites) {52 TestNG tng = create(suites);53 return run(skipConfiguration, tng);54 }55 private static InvokedMethodNameListener run(boolean skipConfiguration, TestNG tng) {56 InvokedMethodNameListener listener = new InvokedMethodNameListener(skipConfiguration);57 tng.addListener(listener);58 tng.run();59 return listener;60 }61 public static TestNG create() {62 TestNG result = new TestNG();63 result.setUseDefaultListeners(false);64 result.setVerbose(0);65 return result;66 }67 public static TestNG create(Class<?>... testClasses) {68 TestNG result = create();69 result.setTestClasses(testClasses);70 return result;71 }72 protected static TestNG create(Path outputDir, Class<?>... testClasses) {73 TestNG result = create(testClasses);74 result.setOutputDirectory(outputDir.toAbsolutePath().toString());75 return result;76 }77 protected static TestNG create(XmlSuite... suites) {78 return create(Arrays.asList(suites));79 }80 protected static TestNG create(List<XmlSuite> suites) {81 TestNG result = create();82 result.setXmlSuites(suites);83 return result;84 }85 protected static TestNG create(Path outputDir, XmlSuite... suites) {86 return create(outputDir, Arrays.asList(suites));87 }88 protected static TestNG create(Path outputDir, List<XmlSuite> suites) {89 TestNG result = create(suites);90 result.setOutputDirectory(outputDir.toAbsolutePath().toString());91 return result;92 }93 protected static TestNG createTests(String suiteName, Class<?>... testClasses) {94 return createTests(null, suiteName, testClasses);95 }96 protected static TestNG createTests(Path outDir,String suiteName, Class<?>... testClasses) {97 XmlSuite suite = createXmlSuite(suiteName);98 int i=0;99 for (Class<?> testClass : testClasses) {100 createXmlTest(suite, testClass.getName() + i, testClass);101 i++;102 }103 if (outDir == null) {104 return create(suite);105 }106 return create(outDir, suite);107 }108 protected static XmlSuite createDummySuiteWithTestNamesAs(String... tests) {109 XmlSuite suite = new XmlSuite();110 suite.setName("random_suite");111 for (String test : tests) {112 XmlTest xmlTest = new XmlTest(suite);113 xmlTest.setName(test);114 }115 return suite;116 }117 protected static XmlSuite createXmlSuite(String name) {118 XmlSuite result = new XmlSuite();119 result.setName(name);120 return result;121 }122 protected static XmlSuite createXmlSuite(Map<String, String> params) {123 XmlSuite result = createXmlSuite(UUID.randomUUID().toString());124 result.setParameters(params);125 return result;126 }127 protected static XmlSuite createXmlSuite(String suiteName, String testName, Class<?>... classes) {128 XmlSuite suite = createXmlSuite(suiteName);129 createXmlTest(suite, testName, classes);130 return suite;131 }132 protected static XmlTest createXmlTestWithPackages(XmlSuite suite, String name, String... packageName) {133 XmlTest result = createXmlTest(suite, name);134 List<XmlPackage> xmlPackages = Lists.newArrayList();135 for (String each : packageName) {136 XmlPackage xmlPackage = new XmlPackage();137 xmlPackage.setName(each);138 xmlPackages.add(xmlPackage);139 }140 result.setPackages(xmlPackages);141 return result;142 }143 protected static XmlTest createXmlTestWithPackages(XmlSuite suite, String name, Class<?>... packageName) {144 XmlTest result = createXmlTest(suite, name);145 List<XmlPackage> xmlPackages = Lists.newArrayList();146 for (Class<?> each : packageName) {147 XmlPackage xmlPackage = new XmlPackage();148 xmlPackage.setName(each.getPackage().getName());149 xmlPackages.add(xmlPackage);150 }151 result.setPackages(xmlPackages);152 return result;153 }154 protected static XmlTest createXmlTest(String suiteName, String testName) {155 XmlSuite suite = createXmlSuite(suiteName);156 return createXmlTest(suite, testName);157 }158 protected static XmlTest createXmlTest(String suiteName, String testName, Class<?>... classes) {159 XmlSuite suite = createXmlSuite(suiteName);160 XmlTest xmlTest = createXmlTest(suite, testName);161 for(Class<?> clazz: classes) {162 xmlTest.getXmlClasses().add(new XmlClass(clazz));163 }164 return xmlTest;165 }166 protected static XmlTest createXmlTest(XmlSuite suite, String name) {167 XmlTest result = new XmlTest(suite);168 result.setName(name);169 return result;170 }171 protected static XmlTest createXmlTest(XmlSuite suite, String name, Map<String, String> params) {172 XmlTest result = new XmlTest(suite);173 result.setName(name);174 result.setParameters(params);175 return result;176 }177 protected static XmlTest createXmlTest(XmlSuite suite, String name, Class<?>... classes) {178 XmlTest result = createXmlTest(suite, name);179 int index = 0;180 for (Class<?> c : classes) {181 XmlClass xc = new XmlClass(c.getName(), index++, true /* load classes */);182 result.getXmlClasses().add(xc);183 }184 return result;185 }186 protected static XmlClass createXmlClass(XmlTest test, Class<?> testClass) {187 XmlClass clazz = new XmlClass(testClass);188 test.getXmlClasses().add(clazz);189 return clazz;190 }191 protected static XmlClass createXmlClass(XmlTest test, Class<?> testClass, Map<String, String> params) {192 XmlClass clazz = createXmlClass(test, testClass);193 clazz.setParameters(params);194 return clazz;195 }196 protected static XmlInclude createXmlInclude(XmlClass clazz, String method) {197 XmlInclude include = new XmlInclude(method);198 include.setXmlClass(clazz);199 clazz.getIncludedMethods().add(include);200 return include;201 }202 protected static XmlInclude createXmlInclude(XmlClass clazz, String method, Map<String, String> params) {203 XmlInclude include = createXmlInclude(clazz, method);204 include.setParameters(params);205 return include;206 }207 protected static XmlInclude createXmlInclude(XmlClass clazz, String method, int index, Integer... list) {208 XmlInclude include = new XmlInclude(method, Arrays.asList(list), index);209 include.setXmlClass(clazz);210 clazz.getIncludedMethods().add(include);211 return include;212 }213 protected static XmlGroups createXmlGroups(XmlSuite suite, String...includedGroupNames) {214 XmlGroups xmlGroups = createGroupIncluding(includedGroupNames);215 suite.setGroups(xmlGroups);216 return xmlGroups;217 }218 protected static XmlGroups createXmlGroups(XmlTest test, String...includedGroupNames) {219 XmlGroups xmlGroups = createGroupIncluding(includedGroupNames);220 test.setGroups(xmlGroups);221 return xmlGroups;222 }223 private static XmlGroups createGroupIncluding(String...groupNames) {224 XmlGroups xmlGroups = new XmlGroups();225 XmlRun xmlRun = new XmlRun();226 for (String group : groupNames) {227 xmlRun.onInclude(group);228 }229 xmlGroups.setRun(xmlRun);230 return xmlGroups;231 }232 protected static XmlTest createXmlTest(XmlSuite suite, String name, String... classes) {233 XmlTest result = createXmlTest(suite, name);234 int index = 0;235 for (String c : classes) {236 XmlClass xc = new XmlClass(c, index++, true /* load classes */);237 result.getXmlClasses().add(xc);238 }239 return result;240 }241 protected static void addMethods(XmlClass cls, String... methods) {242 int index = 0;243 for (String method : methods) {244 XmlInclude include = new XmlInclude(method, index++);245 cls.getIncludedMethods().add(include);246 }247 }248 public static String getPathToResource(String fileName) {249 String result = System.getProperty(TEST_RESOURCES_DIR, "src/test/resources");250 if (result == null) {251 throw new IllegalArgumentException("System property " + TEST_RESOURCES_DIR + " was not defined.");252 }253 return result + File.separatorChar + fileName;254 }255 public static List<ITestNGMethod> extractTestNGMethods(Class<?>... classes) {256 XmlSuite xmlSuite = new XmlSuite();257 xmlSuite.setName("suite");258 XmlTest xmlTest = createXmlTest(xmlSuite, "tests", classes);259 IAnnotationFinder annotationFinder = new JDK15AnnotationFinder(new DefaultAnnotationTransformer());260 List<ITestNGMethod> methods = Lists.newArrayList();261 for (Class<?> clazz : classes) {262 methods.addAll(263 Arrays.asList(264 AnnotationHelper.findMethodsWithAnnotation(clazz, ITestAnnotation.class, annotationFinder, xmlTest)265 )266 );267 }268 return methods;269 }270 /**271 * Compare a list of ITestResult with a list of String method names,272 */273 protected static void assertTestResultsEqual(List<ITestResult> results, List<String> methods) {274 List<String> resultMethods = Lists.newArrayList();275 for (ITestResult r : results) {276 resultMethods.add(r.getMethod().getMethodName());277 }278 Assert.assertEquals(resultMethods, methods);279 }280 /**281 * Deletes all files and subdirectories under dir.282 */283 protected static void deleteDir(File dir) {284 try {285 Files.walkFileTree(dir.toPath(), new SimpleFileVisitor<Path>() {286 @Override287 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {288 Files.delete(file);289 return FileVisitResult.CONTINUE;290 }291 @Override292 public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {293 Files.delete(dir);294 return FileVisitResult.CONTINUE;295 }296 });297 } catch (IOException e) {298 e.printStackTrace();299 }300 }301 protected static File createDirInTempDir(String dir) {302 File slashTmpDir = new File(System.getProperty("java.io.tmpdir"));303 File mTempDirectory = new File(slashTmpDir, dir);304 mTempDirectory.mkdirs();305 mTempDirectory.deleteOnExit();306 return mTempDirectory;307 }308 /**309 *310 * @param fileName The filename to parse311 * @param regexp The regular expression312 * @param resultLines An out parameter that will contain all the lines313 * that matched the regexp314 * @return A List<Integer> containing the lines of all the matches315 *316 * Note that the size() of the returned valuewill always be equal to317 * result.size() at the end of this function.318 */319 protected static List<Integer> grep(File fileName, String regexp, List<String> resultLines) {320 List<Integer> resultLineNumbers = new ArrayList<>();321 try(Reader reader = new FileReader(fileName)) {322 resultLineNumbers = grep(reader, regexp, resultLines);323 } catch (IOException e) {324 e.printStackTrace();325 }326 return resultLineNumbers;327 }328 protected static List<Integer> grep(Reader reader, String regexp, List<String> resultLines) {329 List<Integer> resultLineNumbers = new ArrayList<>();330 try (BufferedReader fr = new BufferedReader(reader)) {331 String line;332 int currentLine = 0;333 Pattern p = Pattern.compile(".*" + regexp + ".*");334 while ((line = fr.readLine()) != null) {335 if (p.matcher(line).matches()) {336 resultLines.add(line);337 resultLineNumbers.add(currentLine);338 }339 currentLine++;340 }341 } catch (IOException e) {342 e.printStackTrace();343 }344 return resultLineNumbers;345 }346 347 protected static List<XmlSuite> getSuites(String... suiteFiles){348 List<XmlSuite> suites = new ArrayList<>();349 for (String suiteFile : suiteFiles) {350 try {351 suites.addAll(new Parser(suiteFile).parseToList());352 } catch (IOException e) {353 throw new TestNGException(e);354 }355 }356 return suites;357 }358}...
Source:WTFTestNG.java
...65 System.exit(0);66 } 67 }68 if (cla.gridUrl != null && cla.gridUrl.length() > 069 && !("blank".equalsIgnoreCase(cla.gridUrl))) {70 cla.grid = true;71 System.out.println("Running tests against grid: " + cla.gridUrl);72 }73 74 if (cla.gyroSuiteName != null && cla.gyroSuiteName.length() > 075 && !("blank".equalsIgnoreCase(cla.gyroSuiteName))) {76 cla.gyro = true;77 System.out.println("Reporting test results to gyro");78 }79 80 setSystemProperties();81 if (cla.outputDirectory != null && cla.outputDirectory.length() > 0) {82 setOutputDirectory(cla.outputDirectory + "\\results");83 }84 if (cla.browsers == null || cla.browsers.size() == 0) {85 cla.browsers.add("ff");86 }87 if (cla.sites == null || cla.sites.size() == 0) {88 cla.sites.add("us");89 }90 if (cla.environment == null || cla.environment.size() == 0) {91 cla.environment.add("qa");92 }93 cla.wtfBrowsers = WTFConverter.browserConveter(cla.browsers);94 cla.wtfSites = WTFConverter.siteConverter(cla.sites);95 cla.wtfEnvironments = WTFConverter.environmentConverter(cla.environment);96 cla.wtfServers = WTFConverter.serverConverter(cla.server);97 // Remove Duplicates.98 cla.wtfBrowsers =99 new ArrayList <Browser>(new HashSet <Browser>(cla.wtfBrowsers));100 cla.wtfSites = new ArrayList<Country>(new HashSet<Country>(cla.wtfSites));101 cla.wtfEnvironments = new ArrayList<Environment>(new HashSet<Environment>(cla.wtfEnvironments));102 System.setProperty("HIGHLIGHT_ELEMENT", cla.highLightElement.toString());103 //TODO(jevasudevan): Remove this duplicate logic104 WTFTestArgs.commandLineArgs = cla;105 WTFTestConfig.initOnce = true;106 return this;107 }108 public WTFTestNG setMethodSelectorScript(String methodSelectorScript) {109 this.methodSelectorScript = methodSelectorScript;110 return this;111 }112 113 /**114 * Provides method selector bean shell script which will eventually be115 * embedded into programatically generated testng.xml116 * 117 * @param aut118 * Application Under Test119 * @param includedMethods120 * Methods name to consider for test run121 * @param testType122 * Test type 'regression' to run all tests or 'smoke' for P1 tests123 * @param site124 * Site of the application under test125 * 126 * @return String version of the method selector script127 */128 public String methodSelectorScript(String aut, String includedMethods,129 String testType, String site) {130 String beanShellMethodSelectorScript = ""131 + "boolean methodEligibleToRun = false;"132 + "boolean isIncludedMethod = false;"133 + "boolean setupMethod = groups.containsKey(\"all\");"134 + "String testType = \""135 + testType136 + "\";"137 + "String includedMethods = \""138 + includedMethods139 + "\";"140 + "if (includedMethods.equals(\"*\") || includedMethods.contains(method.getName()))"141 + "{"142 + "isIncludedMethod = true;"143 + "}"144 + "if (setupMethod "145 + "|| (groups.containsKey(\"" + aut + "\") "146 + "&& (groups.containsKey(\"allSites\") || groups.containsKey(\"" + site.toUpperCase() + "\")))"147 + ") "148 + "{"149 + " methodEligibleToRun = true; "150 + "} "151 + "methodEligibleToRun = (!setupMethod && testType.equals(\"smoke\"))"152 + "? (methodEligibleToRun && groups.containsKey(\"smoke\")) "153 + ": methodEligibleToRun;"154 + "return setupMethod "155 + "? methodEligibleToRun : (methodEligibleToRun && isIncludedMethod);";156 return beanShellMethodSelectorScript;157 }158 public List<XmlSuite> createXmlSuites() {159 testSuites.add(createXmlSuite()); 160 return testSuites;161 }162 public WTFTestNG setXmlSuites() {163 if (cla.testngXmlFile != null) {164 try {165 setXmlSuites(new ArrayList(new Parser(cla.testngXmlFile).parse()));166 } catch (Exception e) {167 // TODO Auto-generated catch block168 e.printStackTrace();169 }170 } else {171 setXmlSuites(createXmlSuites());172 }173 if (cla.printTestngXml) {174 for (XmlSuite xmlSuite : m_suites) {175 System.out.println(xmlSuite.toXml());176 }177 }178 return this;179 }180 public void run() {181 super.run();182 if (hasFailure()) {183 System.out.println("There are test FAILURES, Please find results at: "184 + getOutputDirectory());185 System.exit(1);186 }187 System.out.println("All tests PASSED. Please find results at: "188 + getOutputDirectory());189 System.exit(0);190 }191 /**192 * Helper function to create Xml suite instance.193 * 194 * @param aut195 * Application Under Test196 * @return Instance of XmlSuite197 */198 public XmlSuite createXmlSuite() {199 XmlSuite suite = new XmlSuite();200 suite.setName("BuyerExperience: Electronics Verticals");201 suite.setParallel("methods");202 suite.setVerbose(1);203 // Global parameters204 Map<String, String> parameters = new HashMap<String, String>();205 parameters.put("pool_type", cla.environment.toString());206 parameters.put("pool", cla.pool);207 suite.setParameters(parameters);208 suite.setListeners(getListeners());209 for (String aut : cla.aut.split(",")) {210 for (Browser browser : cla.wtfBrowsers) { 211 for (Country site : cla.wtfSites) {212 addXmlTest(suite, aut, site.getCountryCode(), browser.browserName);;213 }214 }215 }216 217 return suite;218 }219 public WTFTestNG setSystemProperties() {220 cla.wtfBrowsers = new ArrayList<Browser>(new HashSet<Browser>(cla.wtfBrowsers));221 cla.wtfSites = new ArrayList<Country>(new HashSet<Country>(cla.wtfSites));222 System.setProperty("HIGHLIGHT_ELEMENT", cla.highLightElement.toString());223 System.setProperty("service.url", "http://logsvcs.stratus.qa.ebay.com/testlog/");224 System.setProperty("store", "service");225 226 if (cla.grid) {227 if (System.getenv("tsguid")== null) {228 System.setProperty("tsguid", "BuyerExperienceVerticals: Electronics");229 }230 System.setProperty("stepguid", System.getProperty("tsguid"));231 }232 return this;233 }234 public List<String> getListeners() {235 String[] tempListeners = cla.listener.split(",");236 List<String> listeners = new ArrayList<String>();237 for (String listener : tempListeners) {238 listeners.add(listener);239 }240 return listeners;241 }242 public XmlTest addXmlTest(XmlSuite suite, String aut, String site,243 String browser) {244 Map<String, String> parameters = new HashMap<String, String>();245 parameters.put("site", site.toUpperCase());246 parameters.put("browser-type", browser.toLowerCase());247 XmlTest test = new XmlTest(suite); 248 test.setThreadCount(cla.threadCount);249 String[] includeClasses = cla.testClass.split(",");250 String[] includeMethods = cla.testNames.split(",");251 String packageName = null;252 if (autWithPackageDetails != null && !autWithPackageDetails.isEmpty()) {253 Object[] keys = (Object[]) autWithPackageDetails.keySet().toArray();254 for (Object key : keys) {255 for (String autName : autWithPackageDetails.get(key)) {256 if (autName.equalsIgnoreCase(aut.toLowerCase())) {257 aut = autName;258 packageName = (String) key;259 break;260 }261 }262 if (packageName != null)263 break;264 }265 }266 test.setName(aut + "_" + browser.toLowerCase() + "_" + site.toLowerCase());267 parameters.put("page", aut);268 if (includeMethodSelectorScript) {269 test.setBeanShellExpression(methodSelectorScript != null 270 ? methodSelectorScript :271 methodSelectorScript(aut, cla.testNames, cla.testType, site));272 } 273 test.setParallel("true");274 test.setParameters(parameters);275 if (includeClasses[0].equals("*") && includeMethods[0].equals("*")) {276 List<XmlPackage> testPackages = new ArrayList<XmlPackage>();277 XmlPackage xmlPackage = new XmlPackage();278 xmlPackage.setName(packageName + ".*");279 testPackages.add(xmlPackage);280 test.setXmlPackages(testPackages);281 } else if (!includeClasses[0].equals("*")) {282 List<XmlClass> testClass = new ArrayList<XmlClass>();283 for (String clazz : includeClasses) {284 testClass.add(new XmlClass(packageName + "." + clazz));285 }286 test.setXmlClasses(testClass);287 } else if (!includeMethods[0].equals("*")) {288 List<XmlClass> testClass = new ArrayList<XmlClass>();289 List<XmlInclude> xmlIncluded = new ArrayList<XmlInclude>();290 XmlClass xmlClass = null;291 int index = 0;292 for (String clazzAndMethod : includeMethods) {293 index = clazzAndMethod.indexOf(".");294 xmlIncluded.add(new XmlInclude(clazzAndMethod.substring(index + 1)));295 xmlClass = new XmlClass(packageName + "."296 + clazzAndMethod.substring(0, index));297 xmlClass.setIncludedMethods(xmlIncluded);298 testClass.add(xmlClass);299 }300 test.setXmlClasses(testClass);301 }...
Source:Yaml.java
...54 private static void maybeAdd(StringBuilder sb, String key, Object value, Object def) {55 maybeAdd(sb, "", key, value, def);56 }57 private static void maybeAdd(StringBuilder sb, String sp, String key, Object value, Object def) {58 if (value != null && !value.equals(def)) {59 sb.append(sp).append(key).append(": ").append(value.toString()).append("\n");60 }61 }62 /**63 * The main entry point to convert an XmlSuite into YAML. This method is allowed to be used by64 * external tools (e.g. Eclipse).65 */66 public static StringBuilder toYaml(XmlSuite suite) {67 StringBuilder result = new StringBuilder();68 maybeAdd(result, "name", suite.getName(), null);69 maybeAdd(result, "junit", suite.isJUnit(), XmlSuite.DEFAULT_JUNIT);70 maybeAdd(result, "verbose", suite.getVerbose(), XmlSuite.DEFAULT_VERBOSE);71 maybeAdd(result, "threadCount", suite.getThreadCount(), XmlSuite.DEFAULT_THREAD_COUNT);72 maybeAdd(73 result,74 "dataProviderThreadCount",75 suite.getDataProviderThreadCount(),76 XmlSuite.DEFAULT_DATA_PROVIDER_THREAD_COUNT);77 maybeAdd(result, "timeOut", suite.getTimeOut(), null);78 maybeAdd(result, "parallel", suite.getParallel(), XmlSuite.DEFAULT_PARALLEL);79 maybeAdd(80 result,81 "configFailurePolicy",82 suite.getConfigFailurePolicy().toString(),83 XmlSuite.DEFAULT_CONFIG_FAILURE_POLICY);84 maybeAdd(85 result,86 "skipFailedInvocationCounts",87 suite.skipFailedInvocationCounts(),88 XmlSuite.DEFAULT_SKIP_FAILED_INVOCATION_COUNTS);89 toYaml(result, "parameters", "", suite.getParameters());90 toYaml(result, suite.getPackages());91 if (!suite.getListeners().isEmpty()) {92 result.append("listeners:\n");93 toYaml(result, " ", suite.getListeners());94 }95 if (!suite.getPackages().isEmpty()) {96 result.append("packages:\n");97 toYaml(result, suite.getPackages());98 }99 if (!suite.getTests().isEmpty()) {100 result.append("tests:\n");101 for (XmlTest t : suite.getTests()) {102 toYaml(result, " ", t);103 }104 }105 if (!suite.getChildSuites().isEmpty()) {106 result.append("suite-files:\n");107 toYaml(result, " ", suite.getSuiteFiles());108 }109 return result;110 }111 private static void toYaml(StringBuilder result, String sp, XmlTest t) {112 String sp2 = sp + " ";113 result.append(sp).append("- name: ").append(t.getName()).append("\n");114 maybeAdd(result, sp2, "junit", t.isJUnit(), XmlSuite.DEFAULT_JUNIT);115 maybeAdd(result, sp2, "verbose", t.getVerbose(), XmlSuite.DEFAULT_VERBOSE);116 maybeAdd(result, sp2, "timeOut", t.getTimeOut(), null);117 maybeAdd(result, sp2, "parallel", t.getParallel(), XmlSuite.DEFAULT_PARALLEL);118 maybeAdd(119 result,120 sp2,121 "skipFailedInvocationCounts",122 t.skipFailedInvocationCounts(),123 XmlSuite.DEFAULT_SKIP_FAILED_INVOCATION_COUNTS);124 maybeAdd(result, "preserveOrder", sp2, t.getPreserveOrder(), XmlSuite.DEFAULT_PRESERVE_ORDER);125 toYaml(result, "parameters", sp2, t.getLocalParameters());126 if (!t.getIncludedGroups().isEmpty()) {127 result128 .append(sp2)129 .append("includedGroups: [ ")130 .append(Utils.join(t.getIncludedGroups(), ","))131 .append(" ]\n");132 }133 if (!t.getExcludedGroups().isEmpty()) {134 result135 .append(sp2)136 .append("excludedGroups: [ ")137 .append(Utils.join(t.getExcludedGroups(), ","))138 .append(" ]\n");139 }140 Map<String, List<String>> mg = t.getMetaGroups();141 if (mg.size() > 0) {142 result.append(sp2).append("metaGroups: { ");143 boolean first = true;144 for (Map.Entry<String, List<String>> entry : mg.entrySet()) {145 if (!first) {146 result.append(", ");147 }148 result149 .append(entry.getKey())150 .append(": [ ")151 .append(Utils.join(entry.getValue(), ","))152 .append(" ] ");153 first = false;154 }155 result.append(" }\n");156 }157 if (!t.getXmlPackages().isEmpty()) {158 result.append(sp2).append("xmlPackages:\n");159 for (XmlPackage xp : t.getXmlPackages()) {160 toYaml(result, sp2 + " - ", xp);161 }162 }163 if (!t.getXmlClasses().isEmpty()) {164 result.append(sp2).append("classes:\n");165 for (XmlClass xc : t.getXmlClasses()) {166 toYaml(result, sp2 + " ", xc);167 }168 }169 result.append("\n");170 }171 private static void toYaml(StringBuilder result, String sp2, XmlClass xc) {172 List<XmlInclude> im = xc.getIncludedMethods();173 List<String> em = xc.getExcludedMethods();174 String name = (im.isEmpty() && em.isEmpty()) ? "" : "name: ";175 result.append(sp2).append("- ").append(name).append(xc.getName()).append("\n");176 if (!im.isEmpty()) {177 result.append(sp2).append(" includedMethods:\n");178 for (XmlInclude xi : im) {179 toYaml(result, sp2 + " ", xi);180 }181 }182 if (!em.isEmpty()) {183 result.append(sp2).append(" excludedMethods:\n");184 toYaml(result, sp2 + " ", em);185 }186 }187 private static void toYaml(StringBuilder result, String sp, XmlInclude xi) {188 result.append(sp).append("- name: ").append(xi.getName()).append("\n");189 String sp2 = sp + " ";190 toYaml(result, "parameters", sp2, xi.getLocalParameters());191 }192 private static void toYaml(StringBuilder result, String sp, List<String> strings) {193 for (String l : strings) {194 result.append(sp).append("- ").append(l).append("\n");195 }196 }197 private static void toYaml(StringBuilder sb, List<XmlPackage> packages) {198 if (!packages.isEmpty()) {199 sb.append("packages:\n");200 for (XmlPackage p : packages) {201 toYaml(sb, " ", p);202 }203 }204 for (XmlPackage p : packages) {205 toYaml(sb, " ", p);206 }207 }208 private static void toYaml(StringBuilder sb, String sp, XmlPackage p) {209 sb.append(sp).append("name: ").append(p.getName()).append("\n");210 generateIncludeExclude(sb, sp, "includes", p.getInclude());211 generateIncludeExclude(sb, sp, "excludes", p.getExclude());212 }213 private static void generateIncludeExclude(214 StringBuilder sb, String sp, String key, List<String> includes) {215 if (!includes.isEmpty()) {216 sb.append(sp).append(" ").append(key).append("\n");217 for (String inc : includes) {218 sb.append(sp).append(" ").append(inc);219 }220 }221 }222 private static void mapToYaml(Map<String, String> map, StringBuilder out) {223 if (map.size() > 0) {224 out.append("{ ");225 boolean first = true;226 for (Map.Entry<String, String> e : map.entrySet()) {227 if (!first) {228 out.append(", ");229 }230 first = false;231 out.append(e.getKey()).append(": ").append(e.getValue());232 }233 out.append(" }\n");234 }235 }236 private static void toYaml(237 StringBuilder sb, String key, String sp, Map<String, String> parameters) {238 if (!parameters.isEmpty()) {239 sb.append(sp).append(key).append(": ");240 mapToYaml(parameters, sb);241 }242 }243 private static class TestNGConstructor extends Constructor {244 public TestNGConstructor(Class<?> theRoot) {245 super(theRoot);246 yamlClassConstructors.put(NodeId.scalar, new ConstructParallelMode());247 }248 private class ConstructParallelMode extends ConstructScalar {249 @Override250 public Object construct(Node node) {251 if (node.getType().equals(XmlSuite.ParallelMode.class)) {252 String parallel = (String) constructScalar((ScalarNode) node);253 return XmlSuite.ParallelMode.getValidParallel(parallel);254 }255 if (node.getType().equals(XmlSuite.FailurePolicy.class)) {256 String failurePolicy = (String) constructScalar((ScalarNode) node);257 return XmlSuite.FailurePolicy.getValidPolicy(failurePolicy);258 }259 return super.construct(node);260 }261 }262 }263}...
Source:TestEGMProblem.java
...47 int allTestsNr = tla.getFailedTests().size() + tla.getPassedTests().size()48 + tla.getSkippedTests().size();49 assertThat("One test should have been executed", allTestsNr, is(equalTo(2)));50 assertThat("We should have 1 successful methods of class A",51 tla.getPassedTests().stream().filter(m -> m.getInstance().getClass().equals(TestClassA.class))52 .collect(Collectors.toList()).size(),53 is(equalTo(1)));54 assertThat("We should have 1 successful methods of class B",55 tla.getPassedTests().stream().filter(m -> m.getInstance().getClass().equals(TestClassB.class))56 .collect(Collectors.toList()).size(),57 is(equalTo(1)));58 }59 @Test60 public void testTestClassLevel_NoDescription_DifferentGroups() {61 // Rampup62 TestNG myTestNG = createTestNG();63 TestListenerAdapter tla = fetchTestResultsHandler(myTestNG);64 // Define suites65 XmlSuite mySuite = addSuitToTestNGTest(myTestNG, "Automated Suite EGM Problem Testing");66 // Add listeners67 mySuite.addListener(TestTransformer.class.getTypeName());68 // Create an instance of XmlTest and assign a name for it.69 XmlTest myTest = attachTestToSuite(mySuite, "Test Simple Phased EGM Tests");70 myTest.addIncludedGroup("A");71 //Define packages72 List<XmlPackage> l_packages = new ArrayList<XmlPackage>();73 l_packages.add(new XmlPackage("com.adobe.campaign.tests.case2_fails.*"));74 myTest.setXmlPackages(l_packages);75 myTestNG.run();76 final Set<String> tests = TestTransformer.tests;77 assertThat("Our test Class TestClassC2 should have been accessed",78 tests.contains(TestClassC2.class.getTypeName()));79 assertThat("Our test Class TestClassA2 should have been accessed",80 tests.contains(TestClassA2.class.getTypeName()));81 assertThat("Our test Class TestClassB2 should have been accessed",82 tests.contains(TestClassB2.class.getTypeName()));83 int allTestsNr = tla.getFailedTests().size() + tla.getPassedTests().size()84 + tla.getSkippedTests().size();85 assertThat("One test should have been executed", allTestsNr, is(equalTo(2)));86 assertThat("We should have 1 successful methods of class C",87 tla.getPassedTests().stream()88 .filter(m -> m.getInstance().getClass().equals(TestClassC2.class))89 .collect(Collectors.toList()).size(),90 is(equalTo(1)));91 assertThat("We should have 1 successful methods of class A",92 tla.getPassedTests().stream()93 .filter(m -> m.getInstance().getClass().equals(TestClassA2.class))94 .collect(Collectors.toList()).size(),95 is(equalTo(1)));96 assertThat("We should have 1 successful methods of class B",97 tla.getPassedTests().stream()98 .filter(m -> m.getInstance().getClass().equals(TestClassB2.class))99 .collect(Collectors.toList()).size(),100 is(equalTo(1)));101 }102 @Test103 public void testTestClassLevel_NoDescription_ChangeGroupOfOne() {104 // Rampup105 TestNG myTestNG = createTestNG();106 TestListenerAdapter tla = fetchTestResultsHandler(myTestNG);107 // Define suites108 XmlSuite mySuite = addSuitToTestNGTest(myTestNG, "Automated Suite EGM Problem groups Testing");109 // Add listeners110 mySuite.addListener(TestGroupTransformer.class.getTypeName());111 // Create an instance of XmlTest and assign a name for it.112 XmlTest myTest = attachTestToSuite(mySuite, "Test Simple EGM Problem Tests");113 myTest.addIncludedGroup("MYGROUP");114 //Define packages115 List<XmlPackage> l_packages = new ArrayList<XmlPackage>();116 l_packages.add(new XmlPackage("com.adobe.campaign.tests.case1_fails.*"));117 myTest.setXmlPackages(l_packages);118 myTestNG.run();119 SoftAssert softAssert = new SoftAssert();120 softAssert.assertEquals(tla.getPassedTests().size(), 1,121 "Since we only change the group of TestClassA we should only have one success");122 softAssert.assertFalse(tla.getPassedTests().stream().anyMatch(123 t -> t.getMethod().getRealClass().getTypeName().equals(TestClassB.class.getTypeName())), "TestClassB should not be included");124 125 final ITestResult l_testClassBTestResult = tla.getPassedTests().stream().filter(126 t -> t.getMethod().getRealClass().getTypeName().equals(TestClassB.class.getTypeName())).findFirst().get();127 softAssert.assertEquals(l_testClassBTestResult.getMethod().getGroups().length,4,"We should not have toughed the test groups of TestClassB");128 129 softAssert.assertAll();130 }131 //////////////////Helpers132 /**133 * This method creates a testng test instance with a result listener134 * 135 * @return a TestNG instance136 */137 public static TestNG createTestNG() {138 TestNG myTestNG = new TestNG();139 TestListenerAdapter tla = new TestListenerAdapter();140 myTestNG.addListener((ITestNGListener) tla);...
Source:TestRunner.java
...68 String buildNumber = System.getProperty("RunType");69 String emailSubject = buildNumber + "-" + project + "- Automation Report";70 String emailList = System.getProperty("EmailList");71 try {72 if(ConfigDetails.isEmail.equalsIgnoreCase("true")) {73 Thread.sleep(20000);74 GmailHTMLReport.sendEmailWithHTMLReport(emailList, emailSubject,System.getProperty("user.dir") + "/test-output/custom-report.html");75 }else {76 System.out.println("Email Not Sending , As it is Disabled");77 }78 } catch (MessagingException e) {79 e.printStackTrace();80 } catch (IOException e) {81 e.printStackTrace();82 } catch (InterruptedException e) {83 e.printStackTrace();84 }85 }86 /**87 * @author mdafsarali88 * @param suite89 * @param packages90 * @param country91 * @param userType92 * @param suiteType93 * @throws ParseException94 * @throws IOException95 * @throws FileNotFoundException96 */97 public static void createTest(String project, XmlSuite suite, List<XmlPackage> packages, String country,98 String userType, String suiteType) throws FileNotFoundException, IOException, ParseException {99 String testName = country + "_" + userType + "_Tests";100 String groupName = suiteType + "_" + userType;101 Map<String, String> params = new HashMap<String, String>();102 params.put("country", country);103 params.put("userType", userType);104 XmlTest test = new XmlTest(suite);105 test.setName(testName);106 test.setPackages(packages);107 test.setPreserveOrder(true);108 XmlGroups group = new XmlGroups();109 XmlRun run = new XmlRun();110 111 if(!StringUtils.isEmpty(singleTestName) ) {112 run.onInclude(singleTestName);113 }else {114 run.onInclude(groupName);115 }116 117 List<String> list = FileUtilities.readExcludeJSON(project.toLowerCase(),118 country.toLowerCase() + "_" + userType.toLowerCase());119 for (String arr : list) {120 run.onExclude(arr);121 }122 group.setRun(run);123 test.setGroups(group);124 test.setParameters(params);125 }126 /**127 * @author mdafsarali128 * @param countryList129 * @param userType130 * @param suiteType131 * @param project132 * @param testPackageName133 * @throws ParseException134 * @throws IOException135 * @throws FileNotFoundException136 */137 public static void runSuite(List<String> countryList, List<String> userType, String suiteType, String project,138 String testPackageName) throws FileNotFoundException, IOException, ParseException {139 // New list for the Suites140 List<XmlSuite> suites = new ArrayList<XmlSuite>();141 for (String country : countryList) {142 XmlSuite suite = new XmlSuite();143 suite.addListener("com.automation.reports.EmailableReport");144 if (project.equalsIgnoreCase(GlobalConstant.PROJECT_WEB)145 || project.equalsIgnoreCase(GlobalConstant.PROJECT_ANDROID)146 || project.equalsIgnoreCase(GlobalConstant.PROJECT_IOS)) {147 suite.addListener("com.automation.utilities.AnnotationTransformer");148 suite.addListener("com.automation.utilities.BrowserstackSessionStatus");149 }150 suite.addListener("com.vimalselvam.testng.listener.ExtentTestNgFormatter");151 suite.setName("HOOQ Automation - " + suiteType + " Tests - " + country);152 suite.setPreserveOrder(true);153 Map<String, String> params = new HashMap<String, String>();154 params.put("Project", project);155 params.put("SuiteType", suiteType);156 params.put("country", country);157 suite.setParameters(params);158 // ######### test Packages ############################159 List<XmlPackage> packages = new ArrayList<XmlPackage>();160 packages.add(new XmlPackage(testPackageName));...
Source:TestNGGenerator.java
...13import java.util.Map;14public class TestNGGenerator {15 TestNG newTestNG = new TestNG();16 public TestNGGenerator(String testType, int threadCount) throws Exception {17 if (testType.equalsIgnoreCase("parallel")) {18 createParallelXml(threadCount);19 } else if (testType.equalsIgnoreCase("distribute")) {20 createDistributeXml(threadCount);21 } else {22 throw new Exception("select test type to be parallel or distribute");23 }24 }25 public void runTest() {26 newTestNG.run();27 }28 private void createParallelXml(int threadCount){29 XmlSuite testSuite = new XmlSuite();30 testSuite.setName("MobileAutomation");31 testSuite.setParallel(XmlSuite.ParallelMode.TESTS);32 ArrayList<String> listeners = new ArrayList<>();33 listeners.add("com.automation.mobile.listener.TestNGListener");...
Source:DynamicTestNG.java
...21 String cvsSplitBy = ",";22 try {23 br = new BufferedReader(new FileReader(csvFile));24 while ((line = br.readLine()) != null) {25 if(((br.readLine().split(cvsSplitBy))[2]).equals("email@gmail.com")){26 String[] data = line.split(cvsSplitBy);27 System.out.println("First Name: "+data[0]+" Last Name: "+data[1]+" Activity Level: "+data[7]);28 }29 }30 } catch (FileNotFoundException e) {31 e.printStackTrace();32 } catch (IOException e) {33 e.printStackTrace();34 } finally {35 if (br != null) {36 try {37 br.close();38 } catch (IOException e) {39 e.printStackTrace();...
Source:IssueTest.java
1package test.configuration.issue2254;2import java.util.ArrayList;3import java.util.Collections;4import java.util.List;5import org.testng.Assert;6import org.testng.IInvokedMethod;7import org.testng.IInvokedMethodListener;8import org.testng.ITestResult;9import org.testng.TestNG;10import org.testng.annotations.Test;11import org.testng.xml.XmlPackage;12import org.testng.xml.XmlSuite;13import org.testng.xml.XmlTest;14import test.SimpleBaseTest;15public class IssueTest extends SimpleBaseTest {16 @Test(description = "GITHUB-2254")17 public void ensureConfigurationsAreInvokedOnce() {18 List<XmlPackage> packages = new ArrayList<>();19 XmlPackage xmlPackage = new XmlPackage("test.configuration.issue2254.samples");20 packages.add(xmlPackage);21 XmlTest test = new XmlTest();22 test.setName("MyTest");23 test.setXmlPackages(packages);24 XmlSuite xmlSuite = new XmlSuite();25 xmlSuite.setName("MySuite");26 xmlSuite.setTests(Collections.singletonList(test));27 test.addIncludedGroup("A");28 test.setXmlSuite(xmlSuite);29 MyInvokedMethodListener listener = new MyInvokedMethodListener();30 TestNG tng = new TestNG();31 tng.addListener(listener);32 tng.setXmlSuites(Collections.singletonList(xmlSuite));33 tng.setVerbose(1);34 tng.run();35 Assert.assertEquals(listener.beforeCount, 9);36 Assert.assertEquals(listener.afterCount, 9);37 }38 public static class MyInvokedMethodListener implements IInvokedMethodListener {39 int beforeCount = 0;40 int afterCount = 0;41 @Override42 public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {43 beforeCount++;44 }45 @Override46 public void afterInvocation(IInvokedMethod method, ITestResult testResult) {47 afterCount++;48 }49 }50}...
equals
Using AI Code Generation
1XmlPackage p1 = new XmlPackage("com.example");2XmlPackage p2 = new XmlPackage("com.example");3Assert.assertEquals(p1, p2);4XmlClass c1 = new XmlClass("com.example.TestClass");5XmlClass c2 = new XmlClass("com.example.TestClass");6Assert.assertEquals(c1, c2);7XmlTest t1 = new XmlTest();8t1.setName("Test1");9XmlTest t2 = new XmlTest();10t2.setName("Test1");11Assert.assertEquals(t1, t2);12XmlSuite s1 = new XmlSuite();13s1.setName("Suite1");14XmlSuite s2 = new XmlSuite();15s2.setName("Suite1");16Assert.assertEquals(s1, s2);17XmlGroups g1 = new XmlGroups();18g1.setRunMode(XmlSuite.RUN_MODE_INCLUDE);19g1.setIncludedGroups(Arrays.asList("group1"));20XmlGroups g2 = new XmlGroups();21g2.setRunMode(XmlSuite.RUN_MODE_INCLUDE);22g2.setIncludedGroups(Arrays.asList("group1"));23Assert.assertEquals(g1, g2);24TestNG 6.14.3 by Cédric Beust (
equals
Using AI Code Generation
1import org.testng.xml.XmlPackage;2public class XmlPackageEqualsExample {3 public static void main(String[] args) {4 XmlPackage xmlPackage1 = new XmlPackage();5 xmlPackage1.setName("com.example");6 XmlPackage xmlPackage2 = new XmlPackage();7 xmlPackage2.setName("com.example");8 boolean isEqual = xmlPackage1.equals(xmlPackage2);9 System.out.println("Are XmlPackage objects equal? " + isEqual);10 }11}122. org.testng.xml.XmlPackage.equals()
equals
Using AI Code Generation
1package org.testng.xml;2import java.util.List;3import java.util.ArrayList;4import java.util.Arrays;5import java.util.stream.Collectors;6import java.util.stream.Stream;7public class XmlPackage {8 private String name;9 private String[] includedGroups = new String[0];10 private String[] excludedGroups = new String[0];11 private String[] includedNames = new String[0];12 private String[] excludedNames = new String[0];13 public XmlPackage() {14 }15 public XmlPackage(String name) {16 this.name = name;17 }18 public XmlPackage(String name, String[] includedGroups, String[] excludedGroups) {19 this.name = name;20 this.includedGroups = includedGroups;21 this.excludedGroups = excludedGroups;22 }23 public XmlPackage(String name, String[] includedGroups, String[] excludedGroups, String[] includedNames, String[] excludedNames) {24 this.name = name;25 this.includedGroups = includedGroups;26 this.excludedGroups = excludedGroups;27 this.includedNames = includedNames;28 this.excludedNames = excludedNames;29 }30 public String getName() {31 return name;32 }33 public void setName(String name) {34 this.name = name;35 }36 public String[] getIncludedGroups() {37 return includedGroups;38 }39 public void setIncludedGroups(String[] includedGroups) {40 this.includedGroups = includedGroups;41 }42 public String[] getExcludedGroups() {43 return excludedGroups;44 }45 public void setExcludedGroups(String[] excludedGroups) {46 this.excludedGroups = excludedGroups;47 }48 public String[] getIncludedNames() {49 return includedNames;50 }51 public void setIncludedNames(String[] includedNames) {52 this.includedNames = includedNames;53 }54 public String[] getExcludedNames() {55 return excludedNames;56 }57 public void setExcludedNames(String[] excludedNames) {58 this.excludedNames = excludedNames;59 }60 public boolean equals(Object o) {61 if (this == o) return true;62 if (o == null || getClass() != o.getClass()) return false;63 XmlPackage that = (XmlPackage) o;64 return name.equals(that.name) &&65 Arrays.equals(includedGroups, that.includedGroups) &&66 Arrays.equals(excludedGroups, that.excluded
equals
Using AI Code Generation
1XmlPackage pkg = new XmlPackage("com.example");2pkg.setExcludedGroups("exclude");3XmlTest test = new XmlTest();4test.setGroups("group1,group2");5XmlSuite suite = new XmlSuite();6suite.setName("suite1");7suite.setParallel(XmlSuite.ParallelMode.METHODS);8suite.setThreadCount(3);9XmlClass cls = new XmlClass("com.example.Test");10cls.setExcludedMethods("exclude");11XmlMethodSelector selector = new XmlMethodSelector();12selector.setName("com.example.Test");13selector.setPriority(1);14XmlMethodSelector selector = new XmlMethodSelector();15selector.setName("com.example.Test");16selector.setPriority(1);17XmlMethodSelector selector = new XmlMethodSelector();18selector.setName("com.example.Test");19selector.setPriority(1);20XmlMethodSelector selector = new XmlMethodSelector();21selector.setName("com.example.Test");22selector.setPriority(1);23XmlMethodSelector selector = new XmlMethodSelector();24selector.setName("com.example.Test");25selector.setPriority(1);26XmlMethodSelector selector = new XmlMethodSelector();27selector.setName("com.example.Test");28selector.setPriority(1);29XmlMethodSelector selector = new XmlMethodSelector();30selector.setName("com.example.Test");31selector.setPriority(1);32XmlMethodSelector selector = new XmlMethodSelector();33selector.setName("com.example.Test");34selector.setPriority(1);35XmlMethodSelector selector = new XmlMethodSelector();36selector.setName("com.example.Test");37selector.setPriority(1);
TestNG is a Java-based open-source framework for test automation that includes various test types, such as unit testing, functional testing, E2E testing, etc. TestNG is in many ways similar to JUnit and NUnit. But in contrast to its competitors, its extensive features make it a lot more reliable framework. One of the major reasons for its popularity is its ability to structure tests and improve the scripts' readability and maintainability. Another reason can be the important characteristics like the convenience of using multiple annotations, reliance, and priority that make this framework popular among developers and testers for test design. You can refer to the TestNG tutorial to learn why you should choose the TestNG framework.
You can push your abilities to do automated testing using TestNG and advance your career by earning a TestNG certification. Check out our TestNG certification.
Watch this complete tutorial to learn how you can leverage the capabilities of the TestNG framework for Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!