Best Testng code snippet using org.testng.xml.XmlScript
Source:QAFTestNGListener.java
...53import org.testng.xml.XmlClass;54import org.testng.xml.XmlInclude;55import org.testng.xml.XmlMethodSelector;56import org.testng.xml.XmlMethodSelectors;57import org.testng.xml.XmlScript;58import org.testng.xml.XmlSuite;59import org.testng.xml.XmlTest;6061import com.qmetry.qaf.automation.core.ConfigurationManager;62import com.qmetry.qaf.automation.core.HtmlCheckpointResultFormatter;63import com.qmetry.qaf.automation.core.QAFTestBase;64import com.qmetry.qaf.automation.core.TestBaseProvider;65import com.qmetry.qaf.automation.keys.ApplicationProperties;66import com.qmetry.qaf.automation.step.client.Scenario;67import com.qmetry.qaf.automation.step.client.text.BDDTestFactory;68import com.qmetry.qaf.automation.testng.MethodPriorityComparator;69import com.qmetry.qaf.automation.util.ClassUtil;70import com.qmetry.qaf.automation.util.ReportUtils;71import com.qmetry.qaf.automation.util.StringUtil;7273/**74 * All in one Listener for ISFW.75 * 76 * @author Chirag Jayswal.77 */78public class QAFTestNGListener {79 // original listener is spited to separate classes to fix multiple time80 // execution of listener method81 private final Log logger = LogFactoryImpl.getLog(getClass());8283 public void onStart(final ISuite suite) {84 }8586 public void onFinish(ISuite suite) {87 try {88 generateTestFailedXML(suite);89 } catch (Throwable e) {90 logger.debug(e.getStackTrace());91 logger.info("Unable to create testng-failed-qas.xml: " + e.getMessage());92 }93 }9495 public void onTestStart(ITestResult paramITestResult) {96 logger.debug("onTestStart: start");9798 }99100 public void onStart(ITestContext testContext) {101 }102103 public void onFinish(ITestContext testContext) {104 logger.debug("onfinish testcntext: start");105106 }107108 public void onTestFailedButWithinSuccessPercentage(ITestResult tr) {109 onTestFailure(tr);110 }111112 public void onTestFailure(ITestResult tr) {113 report(tr);114 }115116 public void onTestSkipped(ITestResult tr) {117 report(tr);118 }119120 public void onTestSuccess(ITestResult tr) {121 report(tr);122 }123124 public void onConfigurationFailure(ITestResult itr) {125 // report all configuration failures even from the ISFW126 report(itr);127 }128129 public void onConfigurationSkip(ITestResult itr) {130 if (!itr.getMethod().getConstructorOrMethod().getDeclaringClass().getPackage()131 .getName().startsWith("com.qmetry.qaf.automation")) {132 report(itr);133 }134 }135136 public void onConfigurationSuccess(ITestResult itr) {137 if (!itr.getMethod().getConstructorOrMethod().getDeclaringClass().getPackage()138 .getName().startsWith("com.qmetry.qaf.automation")) {139 report(itr);140 }141 }142143 public void transform(IDataProviderAnnotation arg0, Method method) {144 boolean parallel = false;145 if (getBundle().containsKey(method.getName() + ".parallel")) {146 parallel = getBundle().getBoolean(method.getName() + ".parallel");147 } else {148 parallel = getBundle().getBoolean("global.datadriven.parallel", false);149 }150151 arg0.setParallel(parallel);152 }153154 public void transform(IFactoryAnnotation factory, Method method) {155 }156157 @SuppressWarnings("rawtypes")158 public void transform(IConfigurationAnnotation iConfigurationAnnotation, Class arg1,159 Constructor arg2, Method arg3) {160 }161162 public List<IMethodInstance> intercept(List<IMethodInstance> lst,163 ITestContext context) {164 logger.debug("Method Order interceptor called");165 String order = context.getCurrentXmlTest().getParameter("groupOrder");166 MethodPriorityComparator comparator = new MethodPriorityComparator(order);167 Collections.sort(lst, comparator);168 return lst;169 }170171 public void beforeInvocation(IInvokedMethod method, ITestResult tr,172 ITestContext context) {173 QAFTestBase stb = TestBaseProvider.instance().get();174 stb.getLog().clear();175 stb.clearVerificationErrors();176 stb.getCheckPointResults().clear();177 logger.debug("beforeInvocation: " + method.getTestMethod().getMethodName());178 tr.setAttribute("context", context);179 ConfigurationManager.getBundle().setProperty(ApplicationProperties.CURRENT_TEST_CONTEXT.key, context);180181 ConfigurationManager.getBundle().setProperty(ApplicationProperties.CURRENT_TEST_NAME.key,182 tr.getName());183 ConfigurationManager.getBundle().setProperty(ApplicationProperties.CURRENT_TEST_DESCRIPTION.key,184 tr.getMethod().getDescription());185 ConfigurationManager.getBundle().setProperty(ApplicationProperties.CURRENT_TEST_RESULT.key,186 tr);187 }188189 public void beforeInvocation(IInvokedMethod method, ITestResult tr) {190 }191192 public void afterInvocation(IInvokedMethod method, ITestResult tr) {193194 }195196 public void afterInvocation(final IInvokedMethod method, final ITestResult tr,197 final ITestContext context) {198 logger.debug("afterInvocation: " + method.getTestMethod().getMethodName()199 + " - " + method.getTestMethod().getConstructorOrMethod()200 .getDeclaringClass().getName()201 + " is test:" + method.isTestMethod());202 // if (method.isTestMethod()) {203 processResult(tr, context);204 // }205206 logger.debug("afterInvocation: Done");207 }208209210211 protected void report(ITestResult tr) {212 String[] groups = tr.getMethod().getGroups();213 if (null != groups && Arrays.asList(groups).contains("cucumber"))214 return;215 QAFTestBase stb = TestBaseProvider.instance().get();216 tr.setAttribute("browser", stb.getDriverName());217218 org.testng.Reporter.setCurrentTestResult(tr);219 if (getBundle().getBoolean("report.log.testngoutput", false)) {220 HtmlCheckpointResultFormatter checkpointResultFormatter = new HtmlCheckpointResultFormatter();221 org.testng.Reporter.log(checkpointResultFormatter.getResults(stb.getCheckPointResults()));222 }223 }224225 protected void processResult(ITestResult tr, ITestContext context) {226 QAFTestBase stb = TestBaseProvider.instance().get();227 int varificationFailures = stb.getVerificationErrors();228 if (varificationFailures > 0229 && (tr.getStatus() == ITestResult.SUCCESS)) {230 setFailure(tr, context);231 if(tr.getThrowable()==null ){232 // Gradle runner internal listener is throwing null pointer exception!... 233 tr.setThrowable(new AssertionError(varificationFailures + " verification failed."));234 }235 }236237 if (tr.getStatus() == ITestResult.FAILURE) {238 ReportUtils.setScreenshot(tr.getThrowable());239 }240 }241242 protected void setFailure(ITestResult tr, ITestContext context) {243244 if (getBundle().getInt("testng.version", 6) > 5) {245 // Fix for testNG 6246 // IResultMap resultMap = context.getPassedTests();247 // resultMap.248 if ((null != context.getPassedTests())) {249250 if (context.getPassedTests().getResults(tr.getMethod()).size() > 1) {251 context.getPassedTests().removeResult(tr);252 } else {253 context.getPassedTests().removeResult(tr.getMethod());254 } // removeResult(tr.getMethod());255 }256 tr.setStatus(ITestResult.FAILURE);257 if (null != context.getFailedTests()) {258 context.getFailedTests().addResult(tr, tr.getMethod());259 }260 } else {261 tr.setStatus(ITestResult.FAILURE);262263 }264 }265266 protected void setSkip(ITestResult tr, ITestContext context) {267268 if (getBundle().getInt("testng.version", 6) > 5) {269270 // Fix for testNG 6271 if ((null != context.getFailedTests())) {272 if (((null != context.getFailedTests().getResults(tr.getMethod())))273 && (context.getFailedTests().getResults(tr.getMethod())274 .size() > 1)) {275 context.getFailedTests().getResults(tr.getMethod()).remove(tr);276 } else {277 context.getFailedTests().removeResult(tr.getMethod());278 }279 }280 tr.setStatus(ITestResult.SKIP);281 if (null != context.getSkippedTests()) {282 context.getSkippedTests().addResult(tr, tr.getMethod());283 }284 } else {285 tr.setStatus(ITestResult.SKIP);286 }287 }288289 /**290 * @param suite291 * @throws IOException292 * This method creates testng-failed-qas.xml file, which is293 * useful to rerun failed testcases for BDD scenarios.294 */295 private void generateTestFailedXML(ISuite suite) throws IOException {296 Map<String, ISuiteResult> suiteResults = suite.getResults();297 XmlSuite xmlSuite = null;298 for (Entry<String, ISuiteResult> suiteResult : suiteResults.entrySet()) {299 IResultMap failedTests =300 suiteResult.getValue().getTestContext().getFailedTests();301 IResultMap skippedTests =302 suiteResult.getValue().getTestContext().getSkippedTests();303 Set<ITestNGMethod> failedOrSkipppedMethods = new HashSet<ITestNGMethod>();304 failedOrSkipppedMethods.addAll(failedTests.getAllMethods());305 failedOrSkipppedMethods.addAll(skippedTests.getAllMethods());306 if (!failedOrSkipppedMethods.isEmpty() && Scenario.class.isAssignableFrom(307 failedOrSkipppedMethods.iterator().next().getRealClass())) {308 if (xmlSuite == null) {309 xmlSuite = new XmlSuite();310 xmlSuite.setName(suite.getName());311 xmlSuite.setParallel(XmlSuite.ParallelMode.getValidParallel(suite.getParallel()));312 313 xmlSuite.setThreadCount(suite.getXmlSuite().getThreadCount());314 xmlSuite.setListeners(suite.getXmlSuite().getListeners());315 xmlSuite.setParameters(suite.getXmlSuite().getParameters());316 }317 XmlTest test = new XmlTest(xmlSuite);318 test.setName(suiteResult.getValue().getTestContext().getName());319 test.setPreserveOrder(true);320 test.setParameters(suiteResult.getValue().getTestContext()321 .getCurrentXmlTest().getLocalParameters());322 XmlMethodSelectors methodSelectors = new XmlMethodSelectors();323 XmlMethodSelector methodSelector = new XmlMethodSelector();324 methodSelectors.setMethodSelector(methodSelector);325 XmlScript xmlScript = new XmlScript();326 xmlScript.setLanguage("beanshell");327 String scriptDataPart = "";328 for (ITestNGMethod testMethod : failedOrSkipppedMethods) {329 if (Scenario.class.isAssignableFrom(testMethod.getRealClass())) {330 if (StringUtil.isNotEmpty(scriptDataPart)) {331 scriptDataPart = scriptDataPart + "||";332 }333 if (testMethod.getInstance() instanceof Scenario) {334 Scenario scenario = (Scenario) testMethod.getInstance();335 scriptDataPart = scriptDataPart + String.format(336 "testngMethod.getMethodName().equalsIgnoreCase(\"%s\")",337 scenario.getTestName());338 }339 }340 }341 setScript(xmlScript,scriptDataPart);342 methodSelector.setScript(xmlScript);343 ArrayList<XmlMethodSelector> selectors =344 new ArrayList<XmlMethodSelector>();345 selectors.add(methodSelector);346 XmlClass testClass = null;347 ArrayList<XmlClass> classes = new ArrayList<XmlClass>();348 ArrayList<XmlInclude> methodsToRun = new ArrayList<XmlInclude>();349 testClass = new XmlClass();350 testClass.setName(BDDTestFactory.class.getName());351 testClass.setIncludedMethods(methodsToRun);352 classes.add(testClass);353 test.setMethodSelectors(selectors);354 test.setXmlClasses(classes);355 }356 }357 if (xmlSuite != null) {358 File file = new File(suite.getOutputDirectory().replace(suite.getName(), "")359 + "testng-failed-qas.xml");360 FileWriter writer = new FileWriter(file);361 writer.write(xmlSuite.toXml());362 writer.close();363 }364 }365 366 private void setScript(XmlScript xmlScript, String script) {367 try {368 Method setter = null;369 try {370 setter = ClassUtil.getMethod(XmlScript.class, "setScript");371 } catch (NoSuchMethodException e) {372 //tng - 7.1.1+373 setter = ClassUtil.getMethod(XmlScript.class, "setExpression");374 }375 setter.invoke(xmlScript, script);376 } catch (Exception e) {377 throw new RuntimeException(e);378 }379 }380381}
...
Source:Yaml.java
...3import org.testng.util.Strings;4import org.testng.xml.XmlClass;5import org.testng.xml.XmlInclude;6import org.testng.xml.XmlPackage;7import org.testng.xml.XmlScript;8import org.testng.xml.XmlSuite;9import org.testng.xml.XmlTest;10import org.yaml.snakeyaml.TypeDescription;11import org.yaml.snakeyaml.constructor.Constructor;12import org.yaml.snakeyaml.nodes.MappingNode;13import org.yaml.snakeyaml.nodes.Node;14import org.yaml.snakeyaml.nodes.NodeId;15import org.yaml.snakeyaml.nodes.NodeTuple;16import org.yaml.snakeyaml.nodes.ScalarNode;17import java.io.File;18import java.io.FileInputStream;19import java.io.FileNotFoundException;20import java.io.InputStream;21import java.util.List;22import java.util.Map;23/** YAML support for TestNG. */24public final class Yaml {25 private Yaml() {}26 public static XmlSuite parse(String filePath, InputStream is) throws FileNotFoundException {27 Constructor constructor = new TestNGConstructor(XmlSuite.class);28 {29 TypeDescription suiteDescription = new TypeDescription(XmlSuite.class);30 suiteDescription.addPropertyParameters("packages", XmlPackage.class);31 suiteDescription.addPropertyParameters("listeners", String.class);32 suiteDescription.addPropertyParameters("tests", XmlTest.class);33 suiteDescription.addPropertyParameters("method-selectors", XmlMethodSelector.class);34 constructor.addTypeDescription(suiteDescription);35 }36 {37 TypeDescription testDescription = new TypeDescription(XmlTest.class);38 testDescription.addPropertyParameters("classes", XmlClass.class);39 testDescription.addPropertyParameters("metaGroups", String.class, List.class);40 testDescription.addPropertyParameters("method-selectors", XmlMethodSelector.class);41 constructor.addTypeDescription(testDescription);42 }43 org.yaml.snakeyaml.Yaml y = new org.yaml.snakeyaml.Yaml(constructor);44 if (is == null) {45 is = new FileInputStream(new File(filePath));46 }47 XmlSuite result = y.load(is);48 result.setFileName(filePath);49 // Adjust XmlTest parents and indices50 for (XmlTest t : result.getTests()) {51 t.setSuite(result);52 int index = 0;53 for (XmlClass c : t.getClasses()) {54 c.setIndex(index++);55 }56 }57 return result;58 }59 private static void maybeAdd(StringBuilder sb, String key, Object value, Object def) {60 maybeAdd(sb, "", key, value, def);61 }62 private static void maybeAdd(StringBuilder sb, String sp, String key, Object value, Object def) {63 if (value != null && !value.equals(def)) {64 sb.append(sp).append(key).append(": ").append(value.toString()).append("\n");65 }66 }67 /*68 * The main entry point to convert an XmlSuite into YAML. This method is allowed to be used by69 * external tools (e.g. Eclipse).70 */71 public static StringBuilder toYaml(XmlSuite suite) {72 StringBuilder result = new StringBuilder();73 maybeAdd(result, "name", suite.getName(), null);74 maybeAdd(result, "junit", suite.isJUnit(), XmlSuite.DEFAULT_JUNIT);75 maybeAdd(result, "verbose", suite.getVerbose(), XmlSuite.DEFAULT_VERBOSE);76 maybeAdd(result, "threadCount", suite.getThreadCount(), XmlSuite.DEFAULT_THREAD_COUNT);77 maybeAdd(78 result,79 "dataProviderThreadCount",80 suite.getDataProviderThreadCount(),81 XmlSuite.DEFAULT_DATA_PROVIDER_THREAD_COUNT);82 maybeAdd(result, "timeOut", suite.getTimeOut(), null);83 maybeAdd(result, "parallel", suite.getParallel(), XmlSuite.DEFAULT_PARALLEL);84 maybeAdd(85 result,86 "configFailurePolicy",87 suite.getConfigFailurePolicy().toString(),88 XmlSuite.DEFAULT_CONFIG_FAILURE_POLICY);89 maybeAdd(90 result,91 "skipFailedInvocationCounts",92 suite.skipFailedInvocationCounts(),93 XmlSuite.DEFAULT_SKIP_FAILED_INVOCATION_COUNTS);94 toYaml(result, "", suite.getParameters());95 toYaml(result, suite.getPackages());96 if (!suite.getListeners().isEmpty()) {97 result.append("listeners:\n");98 toYaml(result, " ", suite.getListeners());99 }100 if (!suite.getPackages().isEmpty()) {101 result.append("packages:\n");102 toYaml(result, suite.getPackages());103 }104 if (!suite.getTests().isEmpty()) {105 result.append("tests:\n");106 for (XmlTest t : suite.getTests()) {107 toYaml(result, t);108 }109 }110 if (!suite.getChildSuites().isEmpty()) {111 result.append("suite-files:\n");112 toYaml(result, " ", suite.getSuiteFiles());113 }114 return result;115 }116 /**117 * Convert a XmlTest into YAML118 */119 private static void toYaml(StringBuilder result, XmlTest t) {120 String sp2 = Strings.repeat(" ", 2);121 result.append(" ").append("- name: ").append(t.getName()).append("\n");122 maybeAdd(result, sp2, "junit", t.isJUnit(), XmlSuite.DEFAULT_JUNIT);123 maybeAdd(result, sp2, "verbose", t.getVerbose(), XmlSuite.DEFAULT_VERBOSE);124 maybeAdd(result, sp2, "timeOut", t.getTimeOut(), null);125 maybeAdd(result, sp2, "parallel", t.getParallel(), XmlSuite.DEFAULT_PARALLEL);126 maybeAdd(127 result,128 sp2,129 "skipFailedInvocationCounts",130 t.skipFailedInvocationCounts(),131 XmlSuite.DEFAULT_SKIP_FAILED_INVOCATION_COUNTS);132 maybeAdd(result, "preserveOrder", sp2, t.getPreserveOrder(), XmlSuite.DEFAULT_PRESERVE_ORDER);133 toYaml(result, sp2, t.getLocalParameters());134 if (!t.getIncludedGroups().isEmpty()) {135 result136 .append(sp2)137 .append("includedGroups: [ ")138 .append(Utils.join(t.getIncludedGroups(), ","))139 .append(" ]\n");140 }141 if (!t.getExcludedGroups().isEmpty()) {142 result143 .append(sp2)144 .append("excludedGroups: [ ")145 .append(Utils.join(t.getExcludedGroups(), ","))146 .append(" ]\n");147 }148 if (!t.getXmlDependencyGroups().isEmpty()) {149 result150 .append(sp2).append(sp2)151 .append("xmlDependencyGroups:\n");152 t153 .getXmlDependencyGroups()154 .forEach((k, v) ->155 result156 .append(sp2).append(sp2).append(sp2)157 .append(k + ": " + v + "\n"));158 }159 Map<String, List<String>> mg = t.getMetaGroups();160 if (mg.size() > 0) {161 result.append(sp2).append("metaGroups: { ");162 boolean first = true;163 for (Map.Entry<String, List<String>> entry : mg.entrySet()) {164 if (!first) {165 result.append(", ");166 }167 result168 .append(entry.getKey())169 .append(": [ ")170 .append(Utils.join(entry.getValue(), ","))171 .append(" ] ");172 first = false;173 }174 result.append(" }\n");175 }176 if (!t.getXmlPackages().isEmpty()) {177 result.append(sp2).append(sp2).append("xmlPackages:\n");178 for (XmlPackage xp : t.getXmlPackages()) {179 toYaml(result, sp2 + " - ", xp);180 }181 }182 if (!t.getXmlClasses().isEmpty()) {183 result.append(sp2).append("classes:\n");184 for (XmlClass xc : t.getXmlClasses()) {185 toYaml(result, sp2 + " ", xc);186 }187 }188 result.append("\n");189 }190 private static void toYaml(StringBuilder result, String sp2, XmlClass xc) {191 List<XmlInclude> im = xc.getIncludedMethods();192 List<String> em = xc.getExcludedMethods();193 String name = (im.isEmpty() && em.isEmpty()) ? "" : "name: ";194 result.append(sp2).append("- ").append(name).append(xc.getName()).append("\n");195 if (!im.isEmpty()) {196 result.append(sp2).append(" includedMethods:\n");197 for (XmlInclude xi : im) {198 toYaml(result, sp2 + " ", xi);199 }200 }201 if (!em.isEmpty()) {202 result.append(sp2).append(" excludedMethods:\n");203 toYaml(result, sp2 + " ", em);204 }205 }206 private static void toYaml(StringBuilder result, String sp, XmlInclude xi) {207 result.append(sp).append("- name: ").append(xi.getName()).append("\n");208 String sp2 = sp + " ";209 toYaml(result, sp2, xi.getLocalParameters());210 }211 private static void toYaml(StringBuilder result, String sp, List<String> strings) {212 for (String l : strings) {213 result.append(sp).append("- ").append(l).append("\n");214 }215 }216 private static void toYaml(StringBuilder sb, List<XmlPackage> packages) {217 if (!packages.isEmpty()) {218 sb.append("packages:\n");219 for (XmlPackage p : packages) {220 toYaml(sb, " ", p);221 }222 }223 for (XmlPackage p : packages) {224 toYaml(sb, " ", p);225 }226 }227 private static void toYaml(StringBuilder sb, String sp, XmlPackage p) {228 sb.append(sp).append("name: ").append(p.getName()).append("\n");229 generateIncludeExclude(sb, sp, "includes", p.getInclude());230 generateIncludeExclude(sb, sp, "excludes", p.getExclude());231 }232 private static void generateIncludeExclude(233 StringBuilder sb, String sp, String key, List<String> includes) {234 if (!includes.isEmpty()) {235 sb.append(sp).append(" ").append(key).append("\n");236 for (String inc : includes) {237 sb.append(sp).append(" ").append(inc);238 }239 }240 }241 private static void mapToYaml(Map<String, String> map, StringBuilder out) {242 if (map.size() > 0) {243 out.append("{ ");244 boolean first = true;245 for (Map.Entry<String, String> e : map.entrySet()) {246 if (!first) {247 out.append(", ");248 }249 first = false;250 out.append(e.getKey()).append(": ").append(e.getValue());251 }252 out.append(" }\n");253 }254 }255 private static void toYaml(256 StringBuilder sb, String sp, Map<String, String> parameters) {257 if (!parameters.isEmpty()) {258 sb.append(sp).append("parameters").append(": ");259 mapToYaml(parameters, sb);260 }261 }262 private static class TestNGConstructor extends Constructor {263 public TestNGConstructor(Class<?> theRoot) {264 super(theRoot);265 yamlClassConstructors.put(NodeId.scalar, new ConstructParallelMode());266 yamlClassConstructors.put(NodeId.mapping, new ConstructXmlScript());267 }268 private class ConstructXmlScript extends ConstructMapping {269 @Override270 public Object construct(Node node) {271 if (node.getType().equals(org.testng.xml.XmlMethodSelector.class)) {272 final XmlScript xmlScript = new XmlScript();273 org.testng.xml.XmlMethodSelector selector = new org.testng.xml.XmlMethodSelector();274 MappingNode mappingNode = ((MappingNode) node);275 List<NodeTuple> tuples = mappingNode.getValue();276 for (NodeTuple tuple : tuples) {277 setValue(tuple, "expression", xmlScript::setExpression);278 setValue(tuple, "language", xmlScript::setLanguage);279 setValue(tuple, "className", selector::setClassName);280 setValue(tuple, "priority", text -> selector.setPriority(Integer.parseInt(text)));281 }282 selector.setScript(xmlScript);283 return selector;284 }285 return super.construct(node);286 }...
Source:Main.java
...9import org.testng.TestNG;10import org.testng.log4testng.Logger;11import org.testng.xml.XmlMethodSelector;12import org.testng.xml.XmlPackage;13import org.testng.xml.XmlScript;14import org.testng.xml.XmlSuite;15import org.testng.xml.XmlTest;16//TODO: 1. set threadcount to maximum17// 2. The exception in beforeclass doen't show up in the terminal, need to revisit and fix18/**19 * The Main class for test20 * @author hzou21 *22 */23public class Main {24 private static final String GROUPS = "testng-groups";25 private static final String EXGROUPS = "excludegroups";26 private static final String METHODS = "testng-methods";27 private static final Pattern pattern = Pattern.compile("(.*xml)(\\(?)(.*\\))");28 /**29 * Logger instance for this class.30 */31 private static final Logger log = Logger.getLogger(Main.class);32 public static final String SUITE_NAME = "suiteName";33 34 public static HashMap<String, AmbariConfiguration> cache = new HashMap<String, AmbariConfiguration>();35 36 public static void main(String [ ] args) throws Exception {37 List<XmlSuite> suites = new ArrayList<XmlSuite>();38 Matcher matcher;39 int count = 0;40 for (String value : System.getProperty("testng.configure", "machine.xml").split(",")) {41 count++;42 value = value.trim();43 String fileName;44 String suiteName;45 String properties = null;46 matcher = pattern.matcher(value);47 if (value.contains("(")) {48 if (matcher.find()) {49 fileName = matcher.group(1);50 properties = matcher.group(3).substring(0, matcher.group(3).length()-1);51 } else {52 throw new RuntimeException("not correct input");53 }54 } else {55 fileName = value;56 }57 AmbariConfiguration configure = new AmbariConfiguration(fileName);58 59 if (properties != null) {60 for (String property : properties.split(";")) {61 configure.setProperty(property.substring(0, property.indexOf("=")),62 property.substring(property.indexOf("=")+2, property.length()-1));63 }64 }65 66 log.info("using configure file " + fileName);67 68 List<String> groups = new ArrayList<String>();69 for (String group : configure.getProperty(GROUPS, "smoke").split(" "))70 groups.add(group.trim());71 List<String> exgroups = null; 72 if (configure.getProperty(EXGROUPS, null) != null) {73 exgroups = new ArrayList<String>();74 for (String group : configure.getProperty(GROUPS).split(" "))75 exgroups.add(group.trim());76 }77 78 suiteName = fileName.split("\\.")[0] + count;79 cache.put(suiteName, configure);80 XmlSuite suite = new XmlSuite();81 suite.setName(suiteName);82 suite.setDataProviderThreadCount(configure.getPropertyInt("dataProviderThreadCount", 20));83 //TODO: add listener84 //suite.addListener("io.pivotal.ambari_automation.testng.AmbariTestListener");85 Map<String, String> parameters = new HashMap<String, String>();86 parameters.put(SUITE_NAME, suiteName);87 suite.setParameters(parameters);88 XmlTest test = new XmlTest(suite);89 test.setName(suiteName);90 test.setPreserveOrder("true");91 test.setParallel("methods");92 test.setThreadCount(configure.getPropertyInt("threadCount", 20));93 ArrayList<XmlPackage> packages = new ArrayList<XmlPackage>();94 packages.add(new XmlPackage("io.pivotal.ambari_automation.testcases.*"));95 test.setPackages(packages);96 97 // support running only the specified test method, will ignore the included or excluded groups98 if (configure.getProperty(METHODS) != null) {99 String beanShellScript = "false";100 String methods = "";101 for (String method : configure.getProperty(METHODS).split(" ")) {102 method = String.format("(testngMethod.getTestClass().getName().contains(\"%s\") && testngMethod.getMethodName().matches(\"%s\"))", 103 method.contains("#") ? method.split("#")[0] : "", method.contains("#") ? method.split("#")[1] : method.split("#")[0]);104 methods += " || " + method;105 }106 beanShellScript += methods;107 ArrayList<XmlMethodSelector> selectors = new ArrayList<>();108 XmlMethodSelector methodSelector = new XmlMethodSelector();109 XmlScript script = new XmlScript();110 script.setLanguage("beanshell");111 script.setScript(beanShellScript);112 methodSelector.setScript(script);113 selectors.add(methodSelector);114 test.setMethodSelectors(selectors);115 }116 117 test.setIncludedGroups(groups);118 if (exgroups != null)119 test.setExcludedGroups(exgroups);120 suites.add(suite); 121 System.out.println(suite.toXml());122 123 }...
Source:XmlMethodSelector.java
...10 // Either this:11 private String m_className;12 private int m_priority;13 // Or that:14 private XmlScript m_script;15 // For YAML16 public void setClassName(String s) {17 m_className = s;18 }19 public String getClassName() {20 return m_className;21 }22 // For YAML23 @OnElement(24 tag = "selector-class",25 attributes = {"name", "priority"})26 public void setElement(String name, String priority) {27 setName(name);28 setPriority(Integer.parseInt(priority));29 }30 public void setName(String name) {31 m_className = name;32 }33 public XmlScript getScript() {34 return m_script;35 }36 public void setScript(XmlScript script) {37 m_script = script;38 }39 /**40 * @return Returns the expression.41 * @deprecated Use {@link #getScript()} instead.42 */43 @Deprecated44 public String getExpression() {45 if (m_script == null) {46 return null;47 }48 return m_script.getExpression();49 }50 /**51 * @param expression The expression to set.52 * @deprecated Use {@link #setScript(XmlScript)} instead.53 */54 @Deprecated55 public void setExpression(String expression) {56 if (m_script == null) {57 m_script = new XmlScript();58 }59 m_script.setExpression(expression);60 }61 /**62 * @return Returns the language.63 * @deprecated Use {@link #getScript()} instead64 */65 @Deprecated66 public String getLanguage() {67 if (m_script == null) {68 return null;69 }70 return m_script.getLanguage();71 }72 /**73 * @param language The language to set.74 * @deprecated Use {@link #setScript(XmlScript)} instead75 */76 // @OnElement(tag = "script", attributes = "language")77 @Deprecated78 public void setLanguage(String language) {79 if (m_script == null) {80 m_script = new XmlScript();81 }82 m_script.setLanguage(language);83 }84 public int getPriority() {85 return m_priority;86 }87 public void setPriority(int priority) {88 m_priority = priority;89 }90 public String toXml(String indent) {91 XMLStringBuffer xsb = new XMLStringBuffer(indent);92 xsb.push("method-selector");93 if (null != m_className) {94 Properties clsProp = new Properties();...
Source:ScriptNegativeTest.java
...4import org.testng.annotations.AfterMethod;5import org.testng.annotations.BeforeMethod;6import org.testng.annotations.Test;7import org.testng.xml.XmlMethodSelector;8import org.testng.xml.XmlScript;9import org.testng.xml.XmlSuite;10import org.testng.xml.XmlTest;11import test.SimpleBaseTest;12import java.util.ArrayList;13import java.util.Arrays;14import java.util.Collections;15public class ScriptNegativeTest extends SimpleBaseTest {16 private static final String LANGUAGE_NAME = "MissingLanguage";17 @BeforeMethod18 public void setup() {19 System.setProperty("skip.caller.clsLoader", Boolean.TRUE.toString());20 }21 @AfterMethod22 public void cleanup() {23 System.setProperty("skip.caller.clsLoader", Boolean.FALSE.toString());24 }25 @Test (expectedExceptions = TestNGException.class,26 expectedExceptionsMessageRegExp = ".*No engine found for language: " + LANGUAGE_NAME + ".*")27 public void testNegativeScenario() {28 XmlSuite suite = createXmlSuite("suite");29 XmlTest test = createXmlTest(suite, "test", "test.methodselectors.SampleTest");30 XmlScript script = new XmlScript();31 script.setLanguage(LANGUAGE_NAME);32 script.setExpression("expression");33 XmlMethodSelector selector = new XmlMethodSelector();34 selector.setScript(script);35 test.setMethodSelectors(Collections.singletonList(selector));36 TestNG tng = create(suite);37 tng.run();38 }39}...
Source:XmlScript.java
1package org.testng.xml;2import org.testng.xml.dom.TagContent;3public class XmlScript {4 private String m_language;5 private String m_script;6 public void setLanguage(String language) {7 m_language = language;8 }9 @TagContent(name = "script")10 public void setScript(String script) {11 m_script = script;12 }13 public String getScript() {14 return m_script;15 }16 public String getLanguage() {17 return m_language;...
XmlScript
Using AI Code Generation
1XmlSuite suite = new XmlSuite(); 2suite.setName("Sample Suite"); 3XmlTest test = new XmlTest(suite); 4test.setName("Sample Test"); 5List<XmlClass> classes = new ArrayList<XmlClass>(); 6classes.add(new XmlClass("testcases.SampleTest")); 7test.setXmlClasses(classes) ; 8List<XmlSuite> suites = new ArrayList<XmlSuite>(); 9suites.add(suite); 10TestNG tng = new TestNG(); 11tng.setXmlSuites(suites); 12tng.run();
XmlScript
Using AI Code Generation
1import org.testng.xml.XmlClass;2import org.testng.xml.XmlPackage;3import org.testng.xml.XmlSuite;4import org.testng.xml.XmlTest;5import org.testng.xml.XmlSuite.ParallelMode;6import org.testng.xml.XmlSuite.FailurePolicy;7import org.testng.xml.XmlClass;8import org.testng.xml.XmlPackage;9import org.testng.xml.XmlSuite;10import org.testng.xml.XmlTest;11import org.testng.xml.XmlSuite.ParallelMode;12import org.testng.xml.XmlSuite.FailurePolicy;13import org.testng.xml.XmlClass;14import org.testng.xml.XmlPackage;15import org.testng.xml.XmlSuite;16import org.testng.xml.XmlTest;17import org.testng.xml.XmlSuite.ParallelMode;18import org.testng.xml.XmlSuite.FailurePolicy;19import org.testng.xml.XmlClass;20import org.testng.xml.XmlPackage;21import org.testng.xml.XmlSuite;22import org.testng.xml.XmlTest;23import org.testng.xml.XmlSuite.ParallelMode;24import org.testng.xml.XmlSuite.FailurePolicy;25import org.testng.xml.XmlClass;26import org.testng.xml.XmlPackage;27import org.testng.xml.XmlSuite;28import org.testng.xml.XmlTest;29import org.testng.xml.XmlSuite.ParallelMode;30import org.testng.xml.XmlSuite.FailurePolicy;31import org.testng.xml.XmlClass;32import org.testng.xml.XmlPackage;33import org.testng.xml.XmlSuite;34import org.testng.xml.XmlTest;35import org.testng.xml.XmlSuite.ParallelMode;36import org.testng.xml.XmlSuite.FailurePolicy;37import org.testng.xml.XmlClass;38import org.testng.xml.XmlPackage;39import org.testng.xml.XmlSuite;40import org.testng.xml.XmlTest;41import org.testng.xml.XmlSuite.ParallelMode;42import org.testng.xml.XmlSuite.FailurePolicy;43import org.testng.xml.XmlClass;44import org.testng.xml.XmlPackage;45import org.testng.xml.XmlSuite;46import org.testng.xml.XmlTest;47import org.testng.xml.XmlSuite.ParallelMode;48import org.testng.xml.XmlSuite.FailurePolicy;49import org.testng.xml.XmlClass;50import org.testng.xml.XmlPackage;51import org.testng.xml.XmlSuite;52import org.testng.xml.XmlTest;53import org.testng.xml.XmlSuite.ParallelMode;54import org.testng.xml.XmlSuite.FailurePolicy;55import org.testng.xml.XmlClass;56import org.testng.xml.XmlPackage;57import org.testng.xml.XmlSuite;58import org.testng.xml.XmlTest;59import org.testng.xml.XmlSuite.ParallelMode;60import org.testng.xml.XmlSuite.FailurePolicy;61import org.testng.xml.XmlClass;62import org.testng.xml.XmlPackage;63import org.testng.xml.XmlSuite;64import
XmlScript
Using AI Code Generation
1String xmlFilePath = System.getProperty("user.dir") + "\\src\\test\\resources\\testng.xml";2XmlScript xmlScript = new XmlScript(xmlFilePath);3String xmlContent = xmlScript.getXmlContent();4System.out.println(xmlContent);5XmlScript xmlScript = new XmlScript(xmlFilePath);6String xmlContent = xmlScript.getXmlContent();7List<String> testNames = xmlScript.getTestNames();8List<String> classNames = xmlScript.getClassNames();9List<String> packageNames = xmlScript.getPackageNames();10List<String> testNames = xmlScript.getTestNames();
XmlScript
Using AI Code Generation
1XmlScript xmlScript = new XmlScript();2xmlScript.setFilePath("C:\\Users\\admin\\Desktop\\testng.xml");3XmlTest xmlTest = new XmlTest();4xmlTest.setName("test");5xmlTest.setXmlScript(xmlScript);6XmlSuite xmlSuite = new XmlSuite();7xmlSuite.setName("suite");8xmlSuite.addTest(xmlTest);9List<XmlSuite> suites = new ArrayList<XmlSuite>();10suites.add(xmlSuite);11TestNG testNG = new TestNG();12testNG.setXmlSuites(suites);13testNG.run();
XmlScript
Using AI Code Generation
1XmlScript script = new XmlScript();2script.setScript("com.example.MyTestNGScript");3script.setLanguage("groovy");4XmlSuite suite = new XmlSuite();5suite.setName("My Suite");6XmlTest test = new XmlTest(suite);7test.setName("My Test");8test.setScript(script);9List<XmlSuite> suites = new ArrayList<XmlSuite>();10suites.add(suite);11TestNG tng = new TestNG();12tng.setXmlSuites(suites);13tng.run();14XmlScript script = new XmlScript();15script.setScript("com.example.MyTestNGScript");16script.setLanguage("groovy");17XmlTest test = new XmlTest();18test.setName("My Test");19test.setScript(script);20List<XmlSuite> suites = new ArrayList<XmlSuite>();21suites.add(suite);22TestNG tng = new TestNG();23tng.setXmlSuites(suites);24tng.run();25XmlScript script = new XmlScript();26script.setScript("com.example.MyTestNGScript");27script.setLanguage("groovy");28XmlSuite suite = new XmlSuite();29suite.setName("My Suite");30suite.setScript(script);31List<XmlSuite> suites = new ArrayList<XmlSuite>();32suites.add(suite);33TestNG tng = new TestNG();34tng.setXmlSuites(suites);35tng.run();36XmlScript script = new XmlScript();37script.setScript("com.example.MyTestNGScript");38script.setLanguage("groovy");39XmlClass xmlClass = new XmlClass();40xmlClass.setScript(script);41XmlScript script = new XmlScript();42script.setScript("com.example.MyTestNGScript");43script.setLanguage("groovy");44XmlInclude xmlInclude = new XmlInclude();45xmlInclude.setScript(script);46XmlScript script = new XmlScript();47script.setScript("com.example.MyTestNGScript");48script.setLanguage("groovy");49XmlMethodSelector xmlMethodSelector = new XmlMethodSelector();50xmlMethodSelector.setScript(script);51XmlScript script = new XmlScript();52script.setScript("com.example.MyTestNGScript");
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!!