How to use MethodMap class of org.testng package

Best Testng code snippet using org.testng.MethodMap

Source:TestRequestBuilderSpecGenerator.java Github

copy

Full Screen

1/*2 Copyright (c) 2015 LinkedIn Corp.3 Licensed under the Apache License, Version 2.0 (the "License");4 you may not use this file except in compliance with the License.5 You may obtain a copy of the License at6 http://www.apache.org/licenses/LICENSE-2.07 Unless required by applicable law or agreed to in writing, software8 distributed under the License is distributed on an "AS IS" BASIS,9 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10 See the License for the specific language governing permissions and11 limitations under the License.12*/13package com.linkedin.restli.tools.clientgen;14import com.linkedin.data.DataMap;15import com.linkedin.data.schema.DataSchema;16import com.linkedin.pegasus.generator.CodeUtil;17import com.linkedin.pegasus.generator.DataSchemaParser;18import com.linkedin.pegasus.generator.TemplateSpecGenerator;19import com.linkedin.restli.common.ResourceMethod;20import com.linkedin.restli.internal.common.RestliVersion;21import com.linkedin.restli.restspec.ResourceSchema;22import com.linkedin.restli.tools.clientgen.builderspec.ActionBuilderSpec;23import com.linkedin.restli.tools.clientgen.builderspec.ActionParamBindingMethodSpec;24import com.linkedin.restli.tools.clientgen.builderspec.ActionSetRootBuilderSpec;25import com.linkedin.restli.tools.clientgen.builderspec.BuilderSpec;26import com.linkedin.restli.tools.clientgen.builderspec.CollectionRootBuilderSpec;27import com.linkedin.restli.tools.clientgen.builderspec.FinderBuilderSpec;28import com.linkedin.restli.tools.clientgen.builderspec.PathKeyBindingMethodSpec;29import com.linkedin.restli.tools.clientgen.builderspec.QueryParamBindingMethodSpec;30import com.linkedin.restli.tools.clientgen.builderspec.RestMethodBuilderSpec;31import com.linkedin.restli.tools.clientgen.builderspec.RootBuilderMethodSpec;32import com.linkedin.restli.tools.clientgen.builderspec.RootBuilderSpec;33import com.linkedin.restli.tools.clientgen.builderspec.SimpleRootBuilderSpec;34import java.io.File;35import java.io.IOException;36import java.util.ArrayList;37import java.util.Arrays;38import java.util.Collections;39import java.util.HashMap;40import java.util.HashSet;41import java.util.List;42import java.util.Map;43import java.util.Set;44import org.testng.Assert;45import org.testng.annotations.BeforeClass;46import org.testng.annotations.Test;47/**48 * @author Min Chen49 */50public class TestRequestBuilderSpecGenerator51{52 private static final String FS = File.separator;53 private static final String IDLS_DIR = "src" + FS + "test" + FS + "resources" + FS + "idls";54 private static final String RESOLVER_DIR = "src" + FS + "test" + FS + "resources" + FS + "pegasus";55 // Gradle by default will use the module directory as the working directory56 // IDE such as IntelliJ IDEA may use the project directory instead57 // If you create test in IDE, make sure the working directory is always the module directory58 private String moduleDir;59 @BeforeClass60 public void setUp() throws IOException61 {62 moduleDir = System.getProperty("user.dir");63 }64 private Set<BuilderSpec> generateBuilderSpec(String[] sources)65 {66 final DataSchemaParser schemaParser = new DataSchemaParser.Builder(RESOLVER_DIR).build();67 final TemplateSpecGenerator specGenerator = new TemplateSpecGenerator(schemaParser.getSchemaResolver());68 final RestSpecParser parser = new RestSpecParser();69 final Map<ResourceMethod, String> builderBaseMap = new HashMap<>();70 builderBaseMap.put(ResourceMethod.GET, "GetRequestBuilder");71 builderBaseMap.put(ResourceMethod.DELETE, "DeleteRequestBuilder");72 builderBaseMap.put(ResourceMethod.UPDATE, "UpdateRequestBuilder");73 builderBaseMap.put(ResourceMethod.CREATE, "CreateIdRequestBuilder");74 builderBaseMap.put(ResourceMethod.PARTIAL_UPDATE, "PartialUpdateRequestBuilder");75 builderBaseMap.put(ResourceMethod.GET_ALL, "GetAllRequestBuilder");76 builderBaseMap.put(ResourceMethod.OPTIONS, "OptionsRequestBuilder");77 builderBaseMap.put(ResourceMethod.ACTION, "ActionRequestBuilder");78 builderBaseMap.put(ResourceMethod.FINDER, "FinderRequestBuilder");79 builderBaseMap.put(ResourceMethod.BATCH_GET, "BatchGetRequestBuilder");80 builderBaseMap.put(ResourceMethod.BATCH_UPDATE, "BatchUpdateRequestBuilder");81 builderBaseMap.put(ResourceMethod.BATCH_PARTIAL_UPDATE, "BatchPartialUpdateRequestBuilder");82 builderBaseMap.put(ResourceMethod.BATCH_DELETE, "BatchDeleteRequestBuilder");83 builderBaseMap.put(ResourceMethod.BATCH_CREATE, "BatchCreateIdRequestBuilder");84 final RequestBuilderSpecGenerator builderSpecGenerator =85 new RequestBuilderSpecGenerator(schemaParser.getSchemaResolver(), specGenerator, RestliVersion.RESTLI_2_0_0,86 builderBaseMap);87 // parse idl to ResourceSchemas88 final RestSpecParser.ParseResult parseResult = parser.parseSources(sources);89 // generate Builder specs from ResourceSchema90 for (CodeUtil.Pair<ResourceSchema, File> pair : parseResult.getSchemaAndFiles())91 {92 builderSpecGenerator.generate(pair.first, pair.second);93 }94 return builderSpecGenerator.getBuilderSpec();95 }96 @Test97 public void testSimpleResource() throws Exception98 {99 String idl = moduleDir + FS + IDLS_DIR + FS + "testSimple.restspec.json";100 Set<BuilderSpec> builderSpecs = generateBuilderSpec(new String[] {idl});101 Assert.assertNotNull(builderSpecs);102 Assert.assertTrue(builderSpecs.size() == 6);103 Map<String, String> methodMap = new HashMap<>();104 methodMap.put("get", "Gets the greeting.");105 methodMap.put("delete","Deletes the greeting.");106 methodMap.put("update", "Updates the greeting.");107 for (BuilderSpec spec : builderSpecs)108 {109 Assert.assertTrue(spec instanceof RootBuilderSpec || spec instanceof RestMethodBuilderSpec);110 if (spec instanceof RootBuilderSpec)111 {112 Assert.assertTrue(spec instanceof SimpleRootBuilderSpec);113 SimpleRootBuilderSpec simpleSpec = (SimpleRootBuilderSpec) spec;114 if (simpleSpec.getResourcePath().indexOf('/') >= 0)115 {116 Assert.assertEquals(simpleSpec.getSourceIdlName(), idl);117 Assert.assertEquals(simpleSpec.getResourcePath(), "testSimple/testSimpleSub");118 Assert.assertNotNull(simpleSpec.getRestMethods());119 Assert.assertTrue(simpleSpec.getRestMethods().size() == 1);120 Assert.assertEquals("get", simpleSpec.getRestMethods().get(0).getName());121 Assert.assertTrue(simpleSpec.getResourceActions().isEmpty());122 Assert.assertTrue(simpleSpec.getSubresources().isEmpty());123 }124 else125 {126 Assert.assertTrue(simpleSpec.getResourceActions().isEmpty());127 Assert.assertTrue(simpleSpec.getSubresources().size() == 1);128 Assert.assertEquals(simpleSpec.getSourceIdlName(), idl);129 Assert.assertEquals(simpleSpec.getResourcePath(), "testSimple");130 Assert.assertNotNull(simpleSpec.getRestMethods());131 Assert.assertTrue(simpleSpec.getRestMethods().size() == 3);132 List<RootBuilderMethodSpec> restMethods = simpleSpec.getRestMethods();133 for (RootBuilderMethodSpec method : restMethods)134 {135 Assert.assertTrue(method.getReturn() instanceof RestMethodBuilderSpec);136 Assert.assertEquals(method.getReturn().getRootBuilderMethod(), method);137 Assert.assertTrue(methodMap.containsKey(method.getName()));138 Assert.assertEquals(methodMap.get(method.getName()), method.getDoc());139 }140 }141 }142 else if (spec instanceof RestMethodBuilderSpec)143 {144 RestMethodBuilderSpec builderSpec = (RestMethodBuilderSpec) spec;145 ResourceMethod method = builderSpec.getResourceMethod();146 Assert.assertTrue(methodMap.containsKey(method.toString()));147 Assert.assertFalse(builderSpec.hasBindingMethods());148 }149 }150 }151 @Test152 public void testCollectionResource() throws Exception153 {154 String idl = moduleDir + FS + IDLS_DIR + FS + "testCollection.restspec.json";155 Set<BuilderSpec> builderSpecs = generateBuilderSpec(new String[] {idl});156 Assert.assertNotNull(builderSpecs);157 Assert.assertTrue(builderSpecs.size() == 15);158 List<String> expectedMethods = Arrays.asList("actionAnotherAction", "actionSomeAction", "actionVoidAction", "batchGet", "create", "delete", "findBySearch", "get", "getAll", "partialUpdate", "update");159 List<String> actualMethods = new ArrayList<>();160 CollectionRootBuilderSpec rootBuilder = null;161 CollectionRootBuilderSpec subRootBuilder = null;162 FinderBuilderSpec finderBuilder = null;163 List<ActionBuilderSpec> actionBuilders = new ArrayList<>();164 List<RestMethodBuilderSpec> basicMethodBuilders = new ArrayList<>();165 for (BuilderSpec spec : builderSpecs)166 {167 if (spec instanceof RootBuilderSpec)168 {169 Assert.assertTrue(spec instanceof CollectionRootBuilderSpec);170 CollectionRootBuilderSpec collSpec = (CollectionRootBuilderSpec)spec;171 if (collSpec.getResourcePath().indexOf('/') >= 0 )172 {173 subRootBuilder = collSpec;174 }175 else176 {177 rootBuilder = collSpec;178 }179 }180 else if (spec instanceof FinderBuilderSpec)181 {182 finderBuilder = (FinderBuilderSpec) spec;183 }184 else if (spec instanceof ActionBuilderSpec)185 {186 actionBuilders.add((ActionBuilderSpec) spec);187 }188 else if (spec instanceof RestMethodBuilderSpec)189 {190 basicMethodBuilders.add((RestMethodBuilderSpec) spec);191 }192 else193 {194 Assert.fail("There should not be any other builder spec generated!");195 }196 }197 // assert sub resource root builder spec198 Assert.assertNotNull(subRootBuilder);199 Assert.assertEquals(subRootBuilder.getSourceIdlName(), idl);200 Assert.assertEquals(subRootBuilder.getResourcePath(), "testCollection/{testCollectionId}/testCollectionSub");201 Assert.assertEquals(subRootBuilder.getParentRootBuilder(), rootBuilder);202 Assert.assertNotNull(subRootBuilder.getRestMethods());203 Assert.assertTrue(subRootBuilder.getRestMethods().size() == 2);204 Assert.assertTrue(subRootBuilder.getFinders().isEmpty());205 Assert.assertTrue(subRootBuilder.getResourceActions().isEmpty());206 Assert.assertTrue(subRootBuilder.getEntityActions().isEmpty());207 Assert.assertTrue(subRootBuilder.getSubresources().isEmpty());208 // assert root builder spec209 Assert.assertNotNull(rootBuilder);210 Assert.assertEquals(rootBuilder.getSourceIdlName(), idl);211 Assert.assertEquals(rootBuilder.getResourcePath(), "testCollection");212 Assert.assertNotNull(rootBuilder.getRestMethods());213 Assert.assertTrue(rootBuilder.getRestMethods().size() == 7);214 for (RootBuilderMethodSpec method : rootBuilder.getRestMethods())215 {216 actualMethods.add(method.getName());217 Assert.assertEquals(method.getReturn().getRootBuilderMethod(), method);218 }219 Assert.assertNotNull(rootBuilder.getFinders());220 Assert.assertTrue(rootBuilder.getFinders().size() == 1);221 actualMethods.add(rootBuilder.getFinders().get(0).getName());222 Assert.assertNotNull(rootBuilder.getResourceActions());223 Assert.assertTrue(rootBuilder.getResourceActions().size() == 1);224 actualMethods.add(rootBuilder.getResourceActions().get(0).getName());225 Assert.assertNotNull(rootBuilder.getEntityActions());226 Assert.assertTrue(rootBuilder.getEntityActions().size() == 2);227 actualMethods.add(rootBuilder.getEntityActions().get(0).getName());228 actualMethods.add(rootBuilder.getEntityActions().get(1).getName());229 Assert.assertNotNull(rootBuilder.getSubresources());230 Assert.assertTrue(rootBuilder.getSubresources().size() == 1);231 Collections.sort(actualMethods);232 Assert.assertEquals(actualMethods, expectedMethods);233 // assert finder builder spec234 Assert.assertNotNull(finderBuilder);235 Assert.assertEquals("search", finderBuilder.getFinderName());236 Assert.assertNotNull(finderBuilder.getQueryParamMethods());237 Assert.assertTrue(finderBuilder.hasBindingMethods());238 Assert.assertEquals(finderBuilder.getMetadataType().getFullName(),239 "com.linkedin.restli.tools.test.TestRecord");240 Assert.assertTrue(finderBuilder.getQueryParamMethods().size() == 1);241 QueryParamBindingMethodSpec finderQuery = finderBuilder.getQueryParamMethods().get(0);242 Assert.assertEquals(finderQuery.getParamName(), "tone");243 Assert.assertEquals(finderQuery.getMethodName(), "toneParam");244 Assert.assertEquals(finderQuery.getArgType().getFullName(), "com.linkedin.restli.tools.test.TestEnum");245 Assert.assertFalse(finderQuery.isNeedAddParamMethod());246 Assert.assertTrue(finderQuery.isOptional());247 // assert action builder spec248 Assert.assertNotNull(actionBuilders);249 Assert.assertTrue(actionBuilders.size() == 3);250 for (ActionBuilderSpec spec : actionBuilders)251 {252 Assert.assertTrue(spec.getActionName().equals("someAction") || spec.getActionName().equals("anotherAction") || spec.getActionName().equals("voidAction"));253 if (spec.getActionName().equals("voidAction"))254 {255 Assert.assertFalse(spec.hasBindingMethods());256 }257 else258 {259 Assert.assertTrue(spec.hasBindingMethods());260 }261 }262 // assert get method builder query method263 Assert.assertNotNull(basicMethodBuilders);264 Assert.assertTrue(basicMethodBuilders.size() == 9); // 7 for root resource, 2 for sub resource265 for (RestMethodBuilderSpec spec : basicMethodBuilders)266 {267 if (spec.getResourceMethod() == ResourceMethod.GET)268 {269 Assert.assertNotNull(spec.getQueryParamMethods());270 Assert.assertTrue(spec.getQueryParamMethods().size() == 1);271 Assert.assertTrue(spec.hasBindingMethods());272 QueryParamBindingMethodSpec getQuery = spec.getQueryParamMethods().get(0);273 Assert.assertEquals(getQuery.getParamName(), "message");274 Assert.assertEquals(getQuery.getMethodName(), "messageParam");275 Assert.assertEquals(getQuery.getArgType().getSchema().getType(), DataSchema.Type.STRING);276 Assert.assertFalse(getQuery.isNeedAddParamMethod());277 Assert.assertTrue(getQuery.isOptional());278 if (spec.getResource().getName().equals("testCollection"))279 {280 DataMap expected = new DataMap();281 expected.put("someAnnotation", new DataMap());282 Assert.assertEquals(spec.getAnnotations(), expected);283 }284 }285 else if (spec.getResourceMethod() == ResourceMethod.DELETE && spec.getClassName().startsWith("TestCollectionSub"))286 {287 // sub resource delete method should have path keys288 List<PathKeyBindingMethodSpec> pathKeys = spec.getPathKeyMethods();289 Assert.assertNotNull(pathKeys);290 Assert.assertTrue(pathKeys.size() == 1);291 Assert.assertTrue(spec.hasBindingMethods());292 PathKeyBindingMethodSpec pathKeyMethod = pathKeys.get(0);293 Assert.assertEquals(pathKeyMethod.getPathKey(), "testCollectionId");294 Assert.assertEquals(pathKeyMethod.getMethodName(), "testCollectionIdKey");295 Assert.assertEquals(pathKeyMethod.getArgType().getSchema().getType(), DataSchema.Type.LONG);296 }297 else if (spec.getResourceMethod() == ResourceMethod.CREATE)298 {299 Assert.assertEquals(spec.getQueryParamMethods().size(), 1);300 Assert.assertTrue(spec.hasBindingMethods());301 QueryParamBindingMethodSpec queryParam = spec.getQueryParamMethods().get(0);302 Assert.assertEquals(queryParam.getParamName(), "isNullId");303 Assert.assertEquals(queryParam.isOptional(), true);304 DataMap expected = new DataMap();305 expected.put("someOtherAnnotation", new DataMap());306 Assert.assertEquals(spec.getAnnotations(), expected);307 }308 }309 }310 @Test311 public void testActionResource() throws Exception312 {313 String idl = moduleDir + FS + IDLS_DIR + FS + "testAction.restspec.json";314 Set<BuilderSpec> builderSpecs = generateBuilderSpec(new String[] {idl});315 Assert.assertNotNull(builderSpecs);316 Assert.assertEquals(builderSpecs.size(), 27);317 ActionSetRootBuilderSpec rootBuilder = null;318 List<ActionBuilderSpec> actionBuilders = new ArrayList<>();319 for (BuilderSpec spec : builderSpecs)320 {321 if (spec instanceof RootBuilderSpec)322 {323 Assert.assertTrue(spec instanceof ActionSetRootBuilderSpec);324 rootBuilder = (ActionSetRootBuilderSpec) spec;325 }326 else if (spec instanceof ActionBuilderSpec)327 {328 actionBuilders.add((ActionBuilderSpec) spec);329 }330 else331 {332 Assert.fail("There should not be any other builder spec generated!");333 }334 }335 Assert.assertNotNull(rootBuilder);336 Assert.assertEquals(rootBuilder.getSourceIdlName(), idl);337 Assert.assertEquals(rootBuilder.getResourcePath(), "testAction");338 Assert.assertNotNull(rootBuilder.getResourceActions());339 Assert.assertEquals(rootBuilder.getResourceActions().size(), 26);340 for (RootBuilderMethodSpec methodSpec : rootBuilder.getMethods())341 {342 Assert.assertTrue(methodSpec.getReturn() instanceof ActionBuilderSpec);343 Assert.assertEquals(methodSpec.getReturn().getRootBuilderMethod(), methodSpec);344 }345 Assert.assertNotNull(actionBuilders);346 Assert.assertEquals(actionBuilders.size(), 26);347 Set<String> actionNames = new HashSet<>(Arrays.asList("arrayPromise", "echo", "echoRecord", "echoRecordArray", "echoStringArray",348 "echoEnumArray", "failCallbackCall", "failCallbackThrow", "failPromiseCall", "failPromiseThrow",349 "failTaskCall", "failTaskThrow", "failThrowInTask", "get", "nullPromise",350 "nullTask", "parseq", "parseq3", "returnBool", "returnBoolOptionalParam",351 "returnInt", "returnIntOptionalParam", "returnVoid", "timeout", "timeoutCallback",352 "ultimateAnswer"));353 for (ActionBuilderSpec spec : actionBuilders)354 {355 Assert.assertTrue(actionNames.contains(spec.getActionName()));356 actionNames.remove(spec.getActionName());357 if (spec.getActionName().equals("parseq"))358 {359 List<ActionParamBindingMethodSpec> params = spec.getActionParamMethods();360 for (ActionParamBindingMethodSpec param : params)361 {362 if (param.getParamName().equals("a"))363 {364 Assert.assertEquals(param.getArgType().getSchema().getType(), DataSchema.Type.INT);365 }366 else if (param.getParamName().equals("b"))367 {368 Assert.assertEquals(param.getArgType().getSchema().getType(), DataSchema.Type.STRING);369 }370 else if (param.getParamName().equals("c"))371 {372 Assert.assertEquals(param.getArgType().getSchema().getType(), DataSchema.Type.BOOLEAN);373 }374 else375 {376 Assert.fail("There should not be any other param method spec generated!");377 }378 }379 Assert.assertEquals(spec.getValueClass().getSchema().getType(), DataSchema.Type.STRING);380 }381 }382 Assert.assertTrue(actionNames.isEmpty());383 }384}...

Full Screen

Full Screen

Source:DataPreparator.java Github

copy

Full Screen

1package report.realtime.datahandler;2import java.lang.reflect.InvocationTargetException;3import java.lang.reflect.Method;4import java.text.DateFormat;5import java.text.SimpleDateFormat;6import java.util.ArrayList;7import java.util.Arrays;8import java.util.Collection;9import java.util.Date;10import java.util.List;11import java.util.Map;12import java.util.Random;13import java.util.Set;14import java.util.concurrent.ConcurrentSkipListSet;15import org.testng.IInvokedMethod;16import org.testng.ISuite;17import org.testng.ITestNGMethod;18import org.testng.ITestResult;19import org.testng.annotations.DataProvider;20import org.testng.annotations.Test;21import org.testng.xml.XmlSuite;22import report.realtime.result.ExMethodResultDTO;23import report.realtime.result.MethodResultDTO;24public class DataPreparator {25 synchronized public static String prepareSuiteName(ISuite suite) {26 return suite.getName();27 }28 synchronized public static Set<String> prepareSuiteNameList(ISuite suite) {29 XmlSuite xSuite = suite.getXmlSuite();30 listSuitesName(xSuite);31 return suiteNames;32 }33 private static Set<String> suiteNames = new ConcurrentSkipListSet<>();34 private static void listSuitesName(XmlSuite suite) {35 if (suite.getParentSuite() != null) {36 for (XmlSuite childSuite : suite.getParentSuite().getChildSuites()) {37 if (childSuite.getChildSuites().size() != 0) {38 listSuitesName(childSuite);39 } else {40 suiteNames.add(childSuite.getName());41 }42 }43 }44 }45 synchronized public static String prepareRemoteHost(ISuite suite) {46 return suite.getHost();47 }48 synchronized public static List<String> prepareExcludedMethodList(ISuite suite) {49 List<String> exMethods = new ArrayList<String>();50 for (ITestNGMethod testngMethod : suite.getExcludedMethods()) {51 exMethods.add(testngMethod.getMethodName());52 }53 return (exMethods.isEmpty()) ? null : exMethods;54 }55 synchronized public static String pepareSuiteRunState(ISuite suite) {56 return (suite.getSuiteState().isFailed()) ? "Fail" : "Pass";57 }58 synchronized public static String prepareReportOutputDirectory(ISuite suite) {59 return suite.getOutputDirectory();60 }61 synchronized public static String prepareParallelTestFor(ISuite suite) {62 return suite.getParallel();63 }64 synchronized public static List<String> prepareTestMethodList(ISuite suite) {65 List<String> testMethods = new ArrayList<String>();66 for (ITestNGMethod testNGMethod : suite.getAllMethods()) {67 testMethods.add(testNGMethod.getMethodName());68 }69 return (testMethods.isEmpty()) ? null : testMethods;70 }71 synchronized public static List<String> prepareInvokedMethodList(ISuite suite) {72 List<String> invokedMethods = new ArrayList<String>();73 for (IInvokedMethod invokedMethod : suite.getAllInvokedMethods()) {74 invokedMethods.add(invokedMethod.getTestMethod().getMethodName());75 }76 return (invokedMethods.isEmpty()) ? null : invokedMethods;77 }78 synchronized public static int getDataProvider(ITestNGMethod testNGMethod) {79 int dp = 1;80 Method testMethod = testNGMethod.getConstructorOrMethod().getMethod();81 if (testMethod.isAnnotationPresent(Test.class)) {// &&82 // testMethod.isAnnotationPresent(Count.class))83 // {84 Test testMethodTestAnnotation = testMethod.getAnnotation(Test.class);85 String dataProviderName = testMethodTestAnnotation.dataProvider();86 if (dataProviderName != null && !dataProviderName.isEmpty()) {87 Object instance = null;88 Class<?> dataProviderClass = testMethodTestAnnotation.dataProviderClass(); // my89 if (!dataProviderClass.isInstance(testNGMethod.getInstance())) { // check90 // if91 // dataprovider92 // class93 // is94 // test95 // class96 // itself97 } else {98 dataProviderClass = testNGMethod.getInstance().getClass();99 }100 try {101 instance = dataProviderClass.newInstance();102 } catch (InstantiationException | IllegalAccessException e1) {103 e1.getStackTrace();104 }105 Method[] allTestClassMethods = dataProviderClass.getMethods();106 for (Method m : allTestClassMethods) {107 if (m.isAnnotationPresent(DataProvider.class)) {108 DataProvider dataProviderAnnotation = m.getAnnotation(DataProvider.class);109 String dataProviderMethodName = m.getName(); // my110 String thisDataProviderName = dataProviderAnnotation.name();111 if (dataProviderName.equals(thisDataProviderName)112 || dataProviderName.equals(dataProviderMethodName)) {113 try {114 Object[][] theData = (Object[][]) m.invoke(instance);115 Integer numberOfDataProviderRows = theData.length;116 dp = numberOfDataProviderRows;117 } catch (IllegalAccessException e) {118 e.printStackTrace();119 } catch (InvocationTargetException e) {120 e.printStackTrace();121 }122 }123 }124 }125 } else {126 }127 } else {128 }129 return dp;130 }131 synchronized public static List<MethodResultDTO> prepareTestMethod(ISuite suite) {132 List<MethodResultDTO> resultDTOs = new ArrayList<MethodResultDTO>();133 MethodResultDTO dto;134 for (ITestNGMethod iTestNGMethod : suite.getAllMethods()) {135 dto = new MethodResultDTO();136 dto.setDataProvider(getDataProvider(iTestNGMethod));137 dto.setTestMethod(iTestNGMethod.getMethodName());138 resultDTOs.add(dto);139 }140 return resultDTOs;141 }142 synchronized public static List<ExMethodResultDTO> prepareExcludedTestMethod(ISuite suite) {143 List<ExMethodResultDTO> resultDTOs = new ArrayList<ExMethodResultDTO>();144 ExMethodResultDTO dto;145 for (ITestNGMethod iTestNGMethod : suite.getExcludedMethods()) {146 dto = new ExMethodResultDTO();147 dto.setDataProvider(getDataProvider(iTestNGMethod));148 dto.setExcludedMethod(iTestNGMethod.getMethodName());149 resultDTOs.add(dto);150 }151 return resultDTOs;152 }153 synchronized public static List<String> prepareMethodGroupSet(ISuite suite) {154 List<String> groupSet = new ArrayList<String>();155 Map<String, Collection<ITestNGMethod>> methodMap = suite.getMethodsByGroups();156 if (!methodMap.isEmpty()) {157 groupSet.addAll(methodMap.keySet());158 }159 return groupSet;160 }161 synchronized public static String prepareId(ITestResult tr) {162 String id = "";163 for (String grp : prepareContextGroupList(tr)) {164 if (grp.contains(" ")) {165 grp = grp.replaceAll(" ", "-");166 }167 id = id + "_" + grp;168 }169 for (String grp : prepareMethodGroupList(tr)) {170 if (grp.contains(" ")) {171 grp = grp.replaceAll(" ", "-");172 }173 id = id + "_" + grp;174 }175 if (DataMap.testClassMap.containsKey(tr.getTestClass())) {176 id = id + "@" + DataMap.testClassMap.get(tr.getTestClass());177 } else {178 int classId = generateRandomInt();179 DataMap.testClassMap.put(tr.getTestClass(), classId);180 id = id + "@" + classId;181 }182 return id;183 }184 synchronized public static String prepareSuiteName(ITestResult tr) {185 return tr.getTestContext().getSuite().getName();186 }187 synchronized public static String prepareClassName(ITestResult tr) {188 return tr.getTestClass().getName(); // might be same as tr.getTestName()189 }190 synchronized public static String prepareContext(ITestResult tr) {191 return tr.getTestContext().toString();192 }193 synchronized public static String prepareLatestSuiteState(ITestResult tr) {194 return (tr.getTestContext().getSuite().getSuiteState().isFailed()) ? "Fail" : "Pass";195 }196 synchronized public static String prepareInstance(ITestResult tr) {197 return tr.getInstanceName(); // might be same as198 // tr.getInstance().toString()199 }200 synchronized public static List<String> prepareContextGroupList(ITestResult tr) {201 return Arrays.asList(tr.getTestContext().getIncludedGroups());202 }203 synchronized public static String prepareMethodName(ITestResult tr) {204 return tr.getMethod().getMethodName();205 }206 synchronized public static List<String> prepareMethodParameterList(ITestResult tr) {207 List<String> params = new ArrayList<String>();208 for (Object param : tr.getParameters()) {209 params.add(param.toString());210 }211 return (params.isEmpty()) ? null : params;212 }213 synchronized public static List<String> prepareMethodGroupList(ITestResult tr) {214 return Arrays.asList(tr.getMethod().getGroups());215 }216 synchronized public static int prepareMethodInvocationTotalCount(ITestResult tr) {217 return tr.getMethod().getInvocationCount();218 }219 synchronized public static int prepareThreadCount(ITestResult tr) {220 return tr.getMethod().getThreadPoolSize();221 }222 synchronized public static int prepareCurrentInvocationCount(ITestResult tr) {223 return tr.getMethod().getCurrentInvocationCount();224 }225 synchronized public static String prepareMethodStatus(ITestResult tr) {226 int status_int = 0;227 String status = null;228 status_int = tr.getStatus();229 switch (status_int) {230 case 1:231 status = "PASS";232 break;233 case 2:234 status = "FAIL";235 break;236 default:237 status = "SKIP";238 break;239 }240 return status;241 }242 synchronized public static String prepareMethodStartTime(ITestResult tr) {243 return convertMilisecondsToTimeString(tr.getStartMillis());244 }245 synchronized public static String prepareMethodEndTime(ITestResult tr) {246 return convertMilisecondsToTimeString(tr.getEndMillis());247 }248 synchronized public static long prepareMethodExecutionTime(ITestResult tr) {249 long time = tr.getEndMillis() - tr.getStartMillis();250 return time;251 }252 synchronized public static String prepareErrorCause(ITestResult tr) {253 String error = null;254 if (tr.getThrowable() != null) {255 error = getStackStraceInformation(tr.getThrowable());256 }257 return error;258 }259 /*260 * synchronized public static String prepareScreenshotFile(ITestResult tr){261 * String path = null; ITestContext key = tr.getTestContext();262 * if(ScreenshotDataMap.dataMap.containsKey(key)){ path =263 * ScreenshotDataMap.dataMap.get(key); } return path; }264 */265 private static String convertMilisecondsToTimeString(long miliseconds) {266 String time = null;267 Date date = new Date(miliseconds);268 DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");269 time = dateFormat.format(date);270 return time;271 }272 private static String getStackStraceInformation(Throwable th){273 String stack = null;274 StringBuilder sb = new StringBuilder();275 String message = th.getMessage();276 if(message != null){277 sb.append(message+"\n");278 }279 for (StackTraceElement iTestStackTrace : th.getStackTrace()) {280 sb.append(iTestStackTrace.toString()+"\n");281 }282 stack = sb.toString();283 return stack;284 }285 /*286 * private static String formatedTimeDuration(long duration) { int hrs =287 * (int) TimeUnit.MILLISECONDS.toHours(duration) % 24; int min = (int)288 * TimeUnit.MILLISECONDS.toMinutes(duration) % 60; int sec = (int)289 * TimeUnit.MILLISECONDS.toSeconds(duration) % 60; int milli = (int)290 * TimeUnit.MILLISECONDS.toMillis(duration)%1000; return291 * String.format("%02d:%02d:%02d.%02d", hrs, min, sec, milli); }292 */293 public static int generateRandomInt() {294 int otp = 10000;295 Random r = new Random(System.currentTimeMillis());296 otp = (1 + r.nextInt(2)) * 10000 + r.nextInt(10000);297 return otp;298 }299 synchronized public static String prepareAnnoatationName(ITestResult tr) {300 String annoatationName = null;301 if (tr.getMethod().isAfterClassConfiguration())302 annoatationName = "AfterClassConfiguration_Method";303 else if (tr.getMethod().isAfterGroupsConfiguration())304 annoatationName = "AfterClassConfiguration_Method";305 else if (tr.getMethod().isAfterGroupsConfiguration())306 annoatationName = "AfterClassConfiguration_Method";307 else if (tr.getMethod().isAfterSuiteConfiguration())308 annoatationName = "AfterSuiteConfiguration_Method";309 else if (tr.getMethod().isAfterTestConfiguration())310 annoatationName = "AfterTestConfiguration_Method";311 else if (tr.getMethod().isBeforeClassConfiguration())312 annoatationName = "BeforeClassConfiguration_Method";313 else if (tr.getMethod().isBeforeGroupsConfiguration())314 annoatationName = "BeforeGroupsConfiguration_Method";315 else if (tr.getMethod().isBeforeMethodConfiguration())316 annoatationName = "BeforeMethodConfiguration_Method";317 else if (tr.getMethod().isBeforeSuiteConfiguration())318 annoatationName = "BeforeSuiteConfiguration_Method";319 else if (tr.getMethod().isBeforeTestConfiguration())320 annoatationName = "BeforeTestConfiguration_Method";321 else if (tr.getMethod().isTest())322 annoatationName = "Test_Method";323 else324 annoatationName = "Unknown";325 return annoatationName;326 }327}...

Full Screen

Full Screen

Source:PrepareMethodInvokerUtils.java Github

copy

Full Screen

1/**2 * http://www.163.com3 * Copyright (c) 1997-2018 All Rights Reserved.4 */5package com.netease.cloudqa.nlb.api.test.utils;6import static org.testng.Assert.assertEquals;7import java.lang.reflect.InvocationTargetException;8import java.lang.reflect.Method;9import java.util.HashMap;10import java.util.Map;11import java.util.concurrent.TimeUnit;12import com.alibaba.fastjson.JSONObject;13import com.netease.cloudqa.nlb.api.test.framework.common.runtime.ApiRuntimeContext;14import com.netease.cloudqa.nlb.api.test.framework.driver.FrameWorkDriver;15import com.netease.cloudqa.nlb.api.test.framework.model.DataUnit;16import com.netease.cloudqa.nlb.api.test.framework.model.Response;17import com.netease.cloudqa.nlb.api.test.framework.utils.HttpClientUtils;18import com.netease.cloudqa.nlb.api.test.model.Listener;19import com.netease.cloudqa.nlb.api.test.model.LoadBalancer;20import com.netease.cloudqa.nlb.api.test.model.NlbModel;21import com.netease.cloudqa.nlb.api.test.model.Order;22/**23 *24 * @author hzzhangyan25 * @version $Id: PrepareMethodInvokerUtils.java, v 0.1 2018-5-16 下午1:04:43 hzzhangyan Exp $26 */27public class PrepareMethodInvokerUtils extends FrameWorkDriver {28 private static Map<String, Method> methodMap = new HashMap<String, Method>();29 final private static String NLB_MODEL = "NLB_MODEL";30 static {31 try {32 methodMap.put("PrepareMethodInvokerUtils.prepareListener",33 PrepareMethodInvokerUtils.class.getMethod("prepareListener", Map.class,34 HttpClientUtils.class, String.class));35 methodMap.put("PrepareMethodInvokerUtils.prepareListenerIng",36 PrepareMethodInvokerUtils.class.getMethod("prepareListenerIng", Map.class,37 HttpClientUtils.class, String.class));38 methodMap.put("PrepareMethodInvokerUtils.prepareIngress",39 PrepareMethodInvokerUtils.class.getMethod("prepareIngress", Map.class,40 HttpClientUtils.class, String.class));41 methodMap.put("PrepareMethodInvokerUtils.prepareIngressAndOrder",42 PrepareMethodInvokerUtils.class.getMethod("prepareIngressAndOrder", Map.class,43 HttpClientUtils.class, String.class, String.class));44 methodMap.put("PrepareMethodInvokerUtils.prepareIngressAndUpdateOrder",45 PrepareMethodInvokerUtils.class.getMethod("prepareIngressAndUpdateOrder",46 Map.class, HttpClientUtils.class, String.class, String.class));47 methodMap.put("PrepareMethodInvokerUtils.prepareIngressWithoutWaiting",48 PrepareMethodInvokerUtils.class.getMethod("prepareIngressWithoutWaiting",49 Map.class, HttpClientUtils.class, String.class));50 methodMap.put("PrepareMethodInvokerUtils.prepareCreateOrder",51 PrepareMethodInvokerUtils.class.getMethod("prepareCreateOrder", Map.class,52 HttpClientUtils.class, String.class, String.class));53 methodMap.put("PrepareMethodInvokerUtils.prepareIngressAndListener",54 PrepareMethodInvokerUtils.class.getMethod("prepareIngressAndListener", Map.class,55 HttpClientUtils.class, String.class));56 } catch (NoSuchMethodException e) {57 e.printStackTrace();58 } catch (SecurityException e) {59 e.printStackTrace();60 }61 }62 public static void invokeMethod(String methodName, Object... args) {63 try {64 NlbModel nlbModel = (NlbModel) methodMap.get(methodName).invoke(65 new PrepareMethodInvokerUtils(), args);66 DataUnit unit = new DataUnit(NLB_MODEL, nlbModel);67 ApiRuntimeContext.CaseContext.addPrameter(unit);68 } catch (IllegalAccessException e) {69 e.printStackTrace();70 } catch (IllegalArgumentException e) {71 e.printStackTrace();72 } catch (InvocationTargetException e) {73 e.printStackTrace();74 }75 }76 public NlbModel prepareListener(Map<String, String> headers, HttpClientUtils httpClient,77 String prepareBody) {78 JSONObject jsonBody = JSONObject.parseObject(prepareBody);79 Response res = CommonApi.createLn(headers, jsonBody, httpClient);80 assertEquals(res.getCode(), 200, "Prepare Lb listener failed!");81 logger.info("Prepare data successfully!");82 Response res1 = CommonApi83 .getLbDetail(headers, httpClient, jsonBody.getString("InstanceId"));84 NlbModel nlbModel = new NlbModel();85 JSONObject listener = CommonApi.findListenerByName(JSONObject.parseObject(res1.getHtml()),86 "testln1");87 nlbModel.setListener(new Listener(listener.getString("ListenerId")));88 return nlbModel;89 }90 public NlbModel prepareListenerIng(Map<String, String> headers, HttpClientUtils httpClient,91 String prepareBody) {92 JSONObject jsonBody = JSONObject.parseObject(prepareBody);93 Response res = CommonApi.createLnIng(headers, jsonBody, httpClient);94 assertEquals(res.getCode(), 204, "Prepare ing listener failed!");95 logger.info("Prepare data successfully!");96 NlbModel nlbModel = new NlbModel();97 nlbModel.setListener(new Listener(jsonBody.getString("Name")));98 try {99 TimeUnit.SECONDS.sleep(10);100 } catch (InterruptedException e) {101 System.out.println("error");102 }103 return nlbModel;104 }105 public NlbModel prepareIngressAndListener(Map<String, String> headers,106 HttpClientUtils httpClient, String prepareBody) {107 JSONObject jsonBody = JSONObject.parseObject(prepareBody);108 JSONObject createBody = jsonBody.getJSONObject("CreateBody");109 JSONObject listenerBody = jsonBody.getJSONObject("ListenerBody");110 Response res = CommonApi.createLbIng(headers, createBody, httpClient);111 JSONObject resJson = JSONObject.parseObject(res.getHtml());112 assertEquals(res.getCode(), 200, "Prepare ingress failed!");113 String instanceId = resJson.getString("InstanceId");114 listenerBody.put("InstanceId", instanceId);115 String status = CommonApi.waitIng(headers, httpClient, instanceId);116 assertEquals(status, "WORKING", "create ingress failed!");117 res = CommonApi.createLnIng(headers, listenerBody, httpClient);118 assertEquals(res.getCode(), 204, "Prepare listener failed!");119 NlbModel nlbModel = new NlbModel();120 nlbModel.setLoadBalancer(new LoadBalancer(instanceId));121 return nlbModel;122 }123 public NlbModel prepareIngress(Map<String, String> headers, HttpClientUtils httpClient,124 String prepareBody) {125 JSONObject jsonBody = JSONObject.parseObject(prepareBody);126 Response res = CommonApi.createLbIng(headers, jsonBody, httpClient);127 JSONObject resJson = JSONObject.parseObject(res.getHtml());128 assertEquals(res.getCode(), 200, "Prepare ingress failed!");129 String instanceId = resJson.getString("InstanceId");130 String status = CommonApi.waitIng(headers, httpClient, instanceId);131 assertEquals(status, "WORKING", "create ingress failed!");132 NlbModel nlbModel = new NlbModel();133 nlbModel.setLoadBalancer(new LoadBalancer(instanceId));134 return nlbModel;135 }136 public NlbModel prepareIngressWithoutWaiting(Map<String, String> headers,137 HttpClientUtils httpClient, String prepareBody) {138 JSONObject jsonBody = JSONObject.parseObject(prepareBody);139 Response res = CommonApi.createLbIng(headers, jsonBody, httpClient);140 JSONObject resJson = JSONObject.parseObject(res.getHtml());141 assertEquals(res.getCode(), 200, "Prepare ingress failed!");142 String instanceId = resJson.getString("InstanceId");143 NlbModel nlbModel = new NlbModel();144 nlbModel.setLoadBalancer(new LoadBalancer(instanceId));145 return nlbModel;146 }147 public NlbModel prepareCreateOrder(Map<String, String> headers, HttpClientUtils httpClient,148 String prepareBody, String tenantId) {149 headers.put("X-Account-Type", "primary");150 headers.put("X-ORIGIN-GW", "G0");151 headers.put("X-Bill-TenantId", tenantId);152 JSONObject orderBodyJson = JSONObject.parseObject(prepareBody);153 String orderId = CommonApi.createOrderAndPay(headers, orderBodyJson, httpClient);154 NlbModel nlbModel = new NlbModel();155 nlbModel.setOrder(new Order(orderId));156 return nlbModel;157 }158 public NlbModel prepareUpdateOrder(Map<String, String> headers, HttpClientUtils httpClient,159 String prepareBody, String tenantId) {160 headers.put("X-Account-Type", "primary");161 headers.put("X-ORIGIN-GW", "G0");162 headers.put("X-Bill-TenantId", tenantId);163 JSONObject orderBodyJson = JSONObject.parseObject(prepareBody);164 String orderId = CommonApi.createUpOrderAndPay(headers, orderBodyJson, httpClient);165 NlbModel nlbModel = new NlbModel();166 nlbModel.setOrder(new Order(orderId));167 return nlbModel;168 }169 public NlbModel prepareIngressAndOrder(Map<String, String> headers, HttpClientUtils httpClient,170 String prepareBody, String tenantId) {171 JSONObject jsonBody = JSONObject.parseObject(prepareBody);172 JSONObject createBody = jsonBody.getJSONObject("CreateBody");173 NlbModel nlbModel = new NlbModel();174 if (jsonBody.containsKey("OrderBody")) {175 JSONObject orderBody = jsonBody.getJSONObject("OrderBody");176 nlbModel = prepareCreateOrder(headers, httpClient, orderBody.toJSONString(), tenantId);177 }178 Response res = CommonApi.createLbIng(headers, createBody, httpClient);179 JSONObject resJson = JSONObject.parseObject(res.getHtml());180 assertEquals(res.getCode(), 200, "Prepare ingress failed!");181 String instanceId = resJson.getString("InstanceId");182 String status = CommonApi.waitIng(headers, httpClient, instanceId);183 assertEquals(status, "WORKING", "create ingress failed!");184 nlbModel.setLoadBalancer(new LoadBalancer(instanceId));185 return nlbModel;186 }187 public NlbModel prepareIngressAndUpdateOrder(Map<String, String> headers,188 HttpClientUtils httpClient, String prepareBody,189 String tenantId) {190 JSONObject jsonBody = JSONObject.parseObject(prepareBody);191 JSONObject createBody = jsonBody.getJSONObject("CreateBody");192 Response res = CommonApi.createLbIng(headers, createBody, httpClient);193 JSONObject resJson = JSONObject.parseObject(res.getHtml());194 assertEquals(res.getCode(), 200, "Prepare ingress failed!");195 String instanceId = resJson.getString("InstanceId");196 String status = CommonApi.waitIng(headers, httpClient, instanceId);197 assertEquals(status, "WORKING", "create ingress failed!");198 NlbModel nlbModel = new NlbModel();199 if (jsonBody.containsKey("OrderBody")) {200 JSONObject orderBody = jsonBody.getJSONObject("OrderBody");201 orderBody.put("InstanceId", instanceId);202 nlbModel = prepareUpdateOrder(headers, httpClient, orderBody.toJSONString(), tenantId);203 }204 nlbModel.setLoadBalancer(new LoadBalancer(instanceId));205 return nlbModel;206 }207}...

Full Screen

Full Screen

Source:SingleTestJUnitReporter.java Github

copy

Full Screen

1package com.baidu.selenium.listener;2import java.io.PrintWriter;3import java.io.StringWriter;4import java.lang.reflect.Method;5import java.net.InetAddress;6import java.net.UnknownHostException;7import java.text.DecimalFormat;8import java.util.ArrayList;9import java.util.Calendar;10import java.util.Collections;11import java.util.Comparator;12import java.util.Date;13import java.util.HashMap;14import java.util.List;15import java.util.Map;16import java.util.Properties;17import java.util.Set;18import org.testng.IReporter;19import org.testng.ISuite;20import org.testng.ISuiteResult;21import org.testng.ITestContext;22import org.testng.ITestListener;23import org.testng.ITestResult;24import org.testng.collections.Lists;25import org.testng.collections.Maps;26import org.testng.internal.Utils;27import org.testng.internal.annotations.Sets;28import org.testng.reporters.XMLConstants;29import org.testng.reporters.XMLStringBuffer;30import org.testng.xml.XmlSuite;31/**32 * 用于生成一个简易JUnit格式报告的IReporter。<br />33 * 适用于TestNG配置中只包含一个Test的情况。<br />34 * 默认输出到TestNG配置的output目录/junit-results.xml35 * @author xuwenhao36 *37 */38public class SingleTestJUnitReporter implements IReporter, ITestListener {39 private class InnerTestResult {40 public ITestResult result;41 public int invocationCount;42 public InnerTestResult(ITestResult testResult, int invocationCount) {43 this.result = testResult;44 this.invocationCount = invocationCount;45 }46 public String toString() {47 return String.format("Class: %s, Method: %s, InvocationCount: %s", this.result.getInstance().getClass().getName(), this.result48 .getMethod().getMethodName(), this.invocationCount);49 }50 }51 private class InnerTestResultComparator implements Comparator<InnerTestResult> {52 @Override53 public int compare(InnerTestResult o1, InnerTestResult o2) {54 return o1.invocationCount - o2.invocationCount;55 }56 }57 private HashMap<Class<?>, HashMap<Method, List<InnerTestResult>>> resultMap = new HashMap<Class<?>, HashMap<Method, List<InnerTestResult>>>();58 private InnerTestResultComparator comparator = new InnerTestResultComparator();59 60 /**61 * 默认的输出文件名62 */63 private static final String DEFAULT_OUTPUT_FILE = "junit-results.xml";64 private class TestTag {65 public Properties properties;66 public String message;67 public String type;68 public String stackTrace;69 public String errorTag;70 }71 @SuppressWarnings("deprecation")72 @Override73 public void onTestStart(ITestResult testResult) {74 InnerTestResult innerResult = new InnerTestResult(testResult, testResult.getMethod().getCurrentInvocationCount());75 Class<?> testClass = testResult.getInstance().getClass();76 Method testMethod = testResult.getMethod().getMethod();77 if (!resultMap.containsKey(testClass)) {78 resultMap.put(testClass, new HashMap<Method, List<InnerTestResult>>());79 }80 HashMap<Method, List<InnerTestResult>> methodMap = resultMap.get(testClass);81 if (!methodMap.containsKey(testMethod)) {82 methodMap.put(testMethod, new ArrayList<InnerTestResult>());83 }84 List<InnerTestResult> testResultList = methodMap.get(testMethod);85 testResultList.add(innerResult);86 }87 @SuppressWarnings("deprecation")88 @Override89 public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String defaultOutputDirectory) {90 Map<Class<?>, Set<ITestResult>> failedConfigurations = Maps.newHashMap();91 for (ISuite suite : suites) {92 Map<String, ISuiteResult> suiteResults = suite.getResults();93 for (ISuiteResult sr : suiteResults.values()) {94 ITestContext tc = sr.getTestContext();95 addResults(tc.getFailedConfigurations().getAllResults(), failedConfigurations);96 }97 }98 XMLStringBuffer xsb = new XMLStringBuffer();99 xsb.addComment("Generated by " + getClass().getName());100 xsb.push(XMLConstants.TESTSUITES);101 for (Map.Entry<Class<?>, HashMap<Method, List<InnerTestResult>>> testClassEntry : this.resultMap.entrySet()) {102 Class<?> cls = testClassEntry.getKey();103 Properties p1 = new Properties();104 Date timeStamp = Calendar.getInstance().getTime();105 p1.setProperty(XMLConstants.ATTR_TIMESTAMP, timeStamp.toGMTString());106 List<TestTag> testCases = Lists.newArrayList();107 int failures = 0;108 int errors = 0;109 int testCount = 0;110 float totalTime = 0;111 HashMap<Method, List<InnerTestResult>> testMethodResultMap = testClassEntry.getValue();112 for (Map.Entry<Method, List<InnerTestResult>> testMethodEntry : testMethodResultMap.entrySet()) {113 List<InnerTestResult> resultList = testMethodEntry.getValue();114 Collections.sort(resultList, this.comparator);115 116 for (InnerTestResult innerTestResult : resultList) {117 ITestResult tr = innerTestResult.result;118 TestTag testTag = new TestTag();119 boolean isSuccess = tr.getStatus() == ITestResult.SUCCESS;120 if (!isSuccess) {121 if (tr.getThrowable() instanceof AssertionError) {122 errors++;123 } else {124 failures++;125 }126 }127 Properties p2 = new Properties();128 p2.setProperty(XMLConstants.ATTR_CLASSNAME, cls.getName());129 p2.setProperty(XMLConstants.ATTR_NAME, getTestName(tr));130 long time = tr.getEndMillis() - tr.getStartMillis();131 p2.setProperty(XMLConstants.ATTR_TIME, "" + formatTime(time));132 Throwable t = getThrowable(tr, failedConfigurations);133 if (!isSuccess && t != null) {134 StringWriter sw = new StringWriter();135 PrintWriter pw = new PrintWriter(sw);136 t.printStackTrace(pw);137 testTag.message = t.getMessage();138 testTag.type = t.getClass().getName();139 testTag.stackTrace = sw.toString();140 testTag.errorTag = tr.getThrowable() instanceof AssertionError ? "error" : "failure";141 }142 totalTime += time;143 testCount++;144 testTag.properties = p2;145 testCases.add(testTag);146 }147 }148 p1.setProperty(XMLConstants.ATTR_FAILURES, "" + failures);149 p1.setProperty(XMLConstants.ATTR_ERRORS, "" + errors);150 p1.setProperty(XMLConstants.ATTR_NAME, cls.getSimpleName());151 p1.setProperty(XMLConstants.ATTR_PACKAGE, cls.getPackage().getName());152 p1.setProperty(XMLConstants.ATTR_TESTS, "" + testCount);153 p1.setProperty(XMLConstants.ATTR_TIME, "" + formatTime(totalTime));154 try {155 p1.setProperty(XMLConstants.ATTR_HOSTNAME, InetAddress.getLocalHost().getHostName());156 } catch (UnknownHostException e) {157 // ignore158 }159 //160 // Now that we have all the information we need, generate the file161 //162 xsb.push(XMLConstants.TESTSUITE, p1);163 for (TestTag testTag : testCases) {164 if (testTag.stackTrace == null) {165 xsb.addEmptyElement(XMLConstants.TESTCASE, testTag.properties);166 } else {167 xsb.push(XMLConstants.TESTCASE, testTag.properties);168 Properties p = new Properties();169 if (testTag.message != null) {170 p.setProperty(XMLConstants.ATTR_MESSAGE, testTag.message);171 }172 p.setProperty(XMLConstants.ATTR_TYPE, testTag.type);173 xsb.push(testTag.errorTag, p);174 xsb.addCDATA(testTag.stackTrace);175 xsb.pop(testTag.errorTag);176 xsb.pop(XMLConstants.TESTCASE);177 }178 }179 xsb.pop(XMLConstants.TESTSUITE);180 }181 182 xsb.pop(XMLConstants.TESTSUITES);183 Utils.writeUtf8File(defaultOutputDirectory, getOutputFileName(), xsb.toXML());184 }185 protected String getOutputFileName() {186 return DEFAULT_OUTPUT_FILE;187 }188 protected String getTestName(ITestResult testResult) {189 return testResult.getMethod().getMethodName(); 190 }191 private String formatTime(float time) {192 DecimalFormat format = new DecimalFormat("#.###");193 format.setMinimumFractionDigits(3);194 return format.format(time / 1000.0f);195 }196 private Throwable getThrowable(ITestResult tr, Map<Class<?>, Set<ITestResult>> failedConfigurations) {197 Throwable result = tr.getThrowable();198 if (result == null && tr.getStatus() == ITestResult.SKIP) {199 // Attempt to grab the stack trace from the configuration failure200 for (Set<ITestResult> failures : failedConfigurations.values()) {201 for (ITestResult failure : failures) {202 // Naive implementation for now, eventually, we need to try to find203 // out if it's this failure that caused the skip since (maybe by204 // seeing if the class of the configuration method is assignable to205 // the class of the test method, although that's not 100% fool proof206 if (failure.getThrowable() != null) {207 return failure.getThrowable();208 }209 }210 }211 }212 return result;213 }214 private void addResults(Set<ITestResult> allResults, Map<Class<?>, Set<ITestResult>> out) {215 for (ITestResult tr : allResults) {216 Class<?> cls = tr.getMethod().getTestClass().getRealClass();217 Set<ITestResult> l = out.get(cls);218 if (l == null) {219 l = Sets.newHashSet();220 out.put(cls, l);221 }222 l.add(tr);223 }224 }225 226 @Override227 public void onFinish(ITestContext arg0) {228 // TODO Auto-generated method stub229 }230 @Override231 public void onStart(ITestContext arg0) {232 // TODO Auto-generated method stub233 }234 @Override235 public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {236 // TODO Auto-generated method stub237 }238 @Override239 public void onTestFailure(ITestResult arg0) {240 // TODO Auto-generated method stub241 }242 @Override243 public void onTestSkipped(ITestResult arg0) {244 // TODO Auto-generated method stub245 }246 @Override247 public void onTestSuccess(ITestResult arg0) {248 // TODO Auto-generated method stub249 }250}...

Full Screen

Full Screen

Source:TTestReportListener.java Github

copy

Full Screen

1package com.time.ttest.report;2import com.google.gson.Gson;3import com.google.inject.Inject;4import com.time.ttest.context.TTestApplicationContext;5import com.time.ttest.event.AbsReportEvent;6import com.time.ttest.event.ApplicationEndEvent;7import com.time.ttest.event.ApplicationReportEvent;8import com.time.ttest.http.HttpSummary;9import com.time.ttest.listener.ApplicationListener;10import com.time.ttest.util.AttributesUtil;11import lombok.extern.slf4j.Slf4j;12import org.joda.time.DateTime;13import org.testng.*;14import org.testng.collections.Lists;15import org.testng.xml.XmlClass;16import java.lang.annotation.Annotation;17import java.lang.reflect.InvocationTargetException;18import java.util.Collection;19import java.util.HashMap;20import java.util.List;21import java.util.Map;22/**23 * @Auther guoweijie24 * @Date 2020-02-26 20:4225 */26@Slf4j27public class TTestReportListener implements ApplicationListener<AbsReportEvent> {28 private static final String START_TIME = "startTime";29 private static final String END_TIME = "endTime";30 private static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";31 private TTestReport report = new TTestReport();32 @Inject33 private TTestApplicationContext context;34 @Override35 public void onApplicationEvent(AbsReportEvent event) {36 if (event.getSource() instanceof TestNGReport){37 report.setTime(DateTime.now().toString(STANDARD_FORMAT));38 TestNGReport testNGReport = (TestNGReport) event.getSource();39 List<ISuite> suites = testNGReport.getSuites();40 List<TTestSuite> suiteList = Lists.newArrayList();41 suites.forEach(iSuite -> {42 if (iSuite.getResults().size() > 0){43 suiteList.add(getSuite(iSuite));44 }45 });46 report.setTestsCount(suites.stream().mapToInt(iSuite-> iSuite.getAllMethods().size()).sum());47 report.setSuites(suiteList);48 report.setPassTestsCount(suiteList.stream().mapToInt(TTestSuite::getPassTestsCount).sum());49 report.setFailedTestsCount(suiteList.stream().mapToInt(TTestSuite::getFailedTestsCount).sum());50 report.setSkippedTestsCount(suiteList.stream().mapToInt(TTestSuite::getSkippedTestsCount).sum());51 report.setIgnoredTestsCount(suiteList.stream().mapToInt(TTestSuite::getIgnoredTestsCount).sum());52 report.setDurationTime(suiteList.stream().mapToLong(TTestSuite::getDurationTime).sum());53 log.info("json report :{}",new Gson().toJson(report));54 context.publishEvent(new ApplicationEndEvent(report));55 }56 if (event.getSource() instanceof HttpSummary){57 HttpSummary httpSummary = (HttpSummary) event.getSource();58 if (report.getHttpSummaries() == null){59 report.setHttpSummaries(Lists.newArrayList(httpSummary));60 }else {61 report.getHttpSummaries().add(httpSummary);62 }63 }64 }65 protected TTestSuite getSuite(ISuite iSuite){66 TTestSuite suite = new TTestSuite();67 List<TTestContext> tTestContexts = loaderResult(iSuite);68 suite.setName(iSuite.getName());69 suite.setStartTime(new DateTime(iSuite.getAttribute(START_TIME)).toString(STANDARD_FORMAT));70 suite.setEndTime(new DateTime(iSuite.getAttribute(END_TIME)).toString(STANDARD_FORMAT));71 suite.setDurationTime((long) iSuite.getAttribute(END_TIME) - (long)iSuite.getAttribute(START_TIME));72 suite.setPassTestsCount(tTestContexts.stream().mapToInt(TTestContext::getPassTestsCount).sum());73 suite.setFailedTestsCount(tTestContexts.stream().mapToInt(TTestContext::getFailedTestsCount).sum());74 suite.setSkippedTestsCount(tTestContexts.stream().mapToInt(TTestContext::getSkippedTestsCount).sum());75 suite.setIgnoredTestsCount(tTestContexts.stream().mapToInt(TTestContext::getIgnoredTestsCount).sum());76 suite.setResult(tTestContexts);77 return suite;78 }79 private List<TTestContext> loaderResult(ISuite iSuite) {80 Map<String, ISuiteResult> iResults = iSuite.getResults();81 List<TTestContext> results = Lists.newArrayList();82 iResults.forEach((resultName,result)->{83 results.add(getContext(result));84 });85 return results;86 }87 private TTestContext getContext(ISuiteResult iResult) {88 TTestContext context = new TTestContext();89 context.setName(iResult.getTestContext().getName());90 context.setStartTime(new DateTime(iResult.getTestContext().getStartDate().getTime()).toString(STANDARD_FORMAT));91 context.setEndTime(new DateTime(iResult.getTestContext().getEndDate().getTime()).toString(STANDARD_FORMAT));92 context.setDurationTime(iResult.getTestContext().getEndDate().getTime() - iResult.getTestContext().getStartDate().getTime());93 context.setPassTestsCount(iResult.getTestContext().getPassedTests().size());94 context.setFailedTestsCount(iResult.getTestContext().getFailedTests().size());95 context.setSkippedTestsCount(iResult.getTestContext().getSkippedTests().size());96 context.setIgnoredTestsCount(iResult.getTestContext().getExcludedMethods().size());97 context.setTests(loaderTests(iResult.getTestContext()));98 context.setAttributes(AttributesUtil.getAll(iResult.getTestContext()));99 return context;100 }101 private List<TTestResult> loaderTests(ITestContext testContext) {102 List<TTestResult> tTestResults = Lists.newArrayList();103 List<XmlClass> testClasses = testContext.getCurrentXmlTest().getClasses();104 HashMap<String,List<TTestMethod>> classMethod = loaderMethod(testContext);105 testClasses.forEach(xmlClass -> {106 Annotation[] annotations = xmlClass.getSupportClass().getAnnotations();107 List<TTestMethod> tTestMethods = classMethod.get(xmlClass.getName());108 TTestResult tTestResult = new TTestResult();109 tTestResult.setName(xmlClass.getName());110 tTestResult.setMethods(classMethod.get(xmlClass.getName()));111 tTestResult.setPassTestsCount((int) tTestMethods.stream()112 .filter(method -> method.getStatus() == ReportStatus.SUCCESS)113 .map(TTestMethod::getStatus).count());114 tTestResult.setFailedTestsCount((int) tTestMethods.stream()115 .filter(method -> method.getStatus() == ReportStatus.FAILURE)116 .map(TTestMethod::getStatus).count());117 tTestResult.setSkippedTestsCount((int) tTestMethods.stream()118 .filter(method -> method.getStatus() == ReportStatus.SKIP)119 .map(TTestMethod::getStatus).count());120 tTestResult.setIgnoredTestsCount((int) tTestMethods.stream()121 .filter(method -> method.getStatus() == ReportStatus.IGNORED)122 .map(TTestMethod::getStatus).count());123 tTestResult.setDurationTime(tTestMethods.stream().mapToLong(TTestMethod::getDurationTime).sum());124 try {125 AttributesUtil.setAllureAnnotation(tTestResult,annotations);126 } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {127 e.printStackTrace();128 }129 tTestResults.add(tTestResult);130 });131 return tTestResults;132 }133 private HashMap<String, List<TTestMethod>> loaderMethod(ITestContext testContext) {134 HashMap<String, List<TTestMethod>> methodMap = new HashMap<String, List<TTestMethod>>();135 List<IResultMap> allResultMap = Lists.newArrayList(testContext.getPassedTests(),136 testContext.getFailedTests(),137 testContext.getSkippedTests());138 testContext.getExcludedMethods().forEach(iTestNGMethod -> {139 TTestMethod tTestMethod = new TTestMethod();140 tTestMethod.setGroups(iTestNGMethod.getGroups());141 tTestMethod.setName(iTestNGMethod.getMethodName());142 tTestMethod.setStatus(ReportStatus.IGNORED);143 String className = iTestNGMethod.getRealClass().getName();144 if (methodMap.containsKey(className)){145 methodMap.get(className).add(tTestMethod);146 }else {147 methodMap.put(className,Lists.newArrayList(tTestMethod));148 }149 });150 allResultMap.forEach(iResultMap -> {151 iResultMap.getAllResults().forEach(iTestResult -> {152 iTestResult.getMethod().getGroups();153 TTestMethod tTestMethod = new TTestMethod();154 tTestMethod.setGroups(iTestResult.getMethod().getGroups());155 tTestMethod.setName(iTestResult.getName());156 tTestMethod.setStatus(ReportStatus.of(iTestResult.getStatus()));157 tTestMethod.setRetried(iTestResult.wasRetried());158 tTestMethod.setStartTime(new DateTime(iTestResult.getStartMillis()).toString(STANDARD_FORMAT));159 tTestMethod.setEndTime(new DateTime(iTestResult.getEndMillis()).toString(STANDARD_FORMAT));160 tTestMethod.setDurationTime(iTestResult.getEndMillis() - iTestResult.getStartMillis());161 tTestMethod.setThrowable(iTestResult.getThrowable());162 tTestMethod.setAttributes(AttributesUtil.getAll(iTestResult));163 String className = iTestResult.getMethod().getRealClass().getName();164 if (methodMap.containsKey(className)){165 methodMap.get(className).add(tTestMethod);166 }else {167 methodMap.put(className,Lists.newArrayList(tTestMethod));168 }169 });170 });171 return methodMap;172 }173}...

Full Screen

Full Screen

Source:TestngXml.java Github

copy

Full Screen

1package com.ui.automation.framework.testng;2import com.library.common.XmlHelper;3import com.ui.automation.framework.TestCaseBase;4import org.dom4j.Element;5import org.reflections.Reflections;6import org.springframework.core.io.ClassPathResource;7import org.testng.annotations.Test;8import java.io.File;9import java.io.IOException;10import java.lang.annotation.Annotation;11import java.lang.reflect.Method;12import java.text.SimpleDateFormat;13import java.util.*;14/**15 * The type Testng xml generator.16 */17public class TestngXml {18 private static List<Map<String, Object>> methodListMap = new ArrayList<Map<String, Object>>();19 /**20 * System.setProperty("browser","chrome");21 * System.setProperty("hubURL","http://192.168.20.196:4444/wd/hub");22 * autoGenerate("1");23 *24 * @param args the input arguments25 */26 public static void main(String[] args) {27 if (args.length > 1) {28 autoGenerate(args[0], Integer.parseInt(args[1]));29 } else {30 autoGenerate(Integer.parseInt(args[0]));31 }32 }33 /**34 * Auto generate.35 *36 * @param path the path37 * @param threadCnt the thread cnt38 */39 public static String autoGenerate(String path, int threadCnt) {40 methodListMap.clear();41 Reflections reflections = new Reflections("");42 Set<Class<? extends TestCaseBase>> testCaseClassSet = reflections.getSubTypesOf(TestCaseBase.class);43 for (Class<? extends TestCaseBase> testCaseClass : testCaseClassSet) {44 Method[] methods = testCaseClass.getDeclaredMethods();45 for (Method method : methods) {46 Annotation[] annotations = method.getDeclaredAnnotations();47 for (Annotation annotation : annotations) {48 if (annotation.annotationType().equals(Test.class)) {49 Map<String, Object> methodMap = new HashMap<>();50 methodMap.put("className", testCaseClass.getSimpleName());51 methodMap.put("packageName", testCaseClass.getPackage().getName());52 methodMap.put("methodName", method.getName());53 methodListMap.add(methodMap);54 }55 }56 }57 }58 XmlHelper xml = new XmlHelper();59 xml.createDocument();60 Element root = xml.createDocumentRoot("suite");61 xml.addAttribute(root, "name", "suite_" + threadCnt);62 xml.addAttribute(root, "thread-count", String.valueOf(threadCnt));63 xml.addAttribute(root, "parallel", "tests");64 xml.addAttribute(root, "verbose", "1");65 Element listeners = xml.addChildElement(root, "listeners");66 Element listener = xml.addChildElement(listeners, "listener");67 xml.addAttribute(listener, "class-name", "com.ui.automation.framework.testng.listener.RetryListener");68 for (Map<String, Object> methodMap : methodListMap) {69 Element test = xml.addChildElement(root, "test");70 xml.addAttribute(test, "name", methodMap.get("className").toString() + "_" + methodMap.get("methodName").toString());71 xml.addAttribute(test, "timeout", "600000");72 if (System.getProperty("browser") != null) {73 Element parameter = xml.addChildElement(test, "parameter");74 xml.addAttribute(parameter, "name", "browser");75 xml.addAttribute(parameter, "value", System.getProperty("browser"));76 }77 if (System.getProperty("hubURL") != null) {78 Element parameter = xml.addChildElement(test, "parameter");79 xml.addAttribute(parameter, "name", "hubURL");80 xml.addAttribute(parameter, "value", System.getProperty("hubURL"));81 }82 Element classes = xml.addChildElement(test, "classes");83 Element cls = xml.addChildElement(classes, "class");84 xml.addAttribute(cls, "name", methodMap.get("packageName").toString() + "." + methodMap.get("className").toString());85 Element methods = xml.addChildElement(cls, "methods");86 Element include = xml.addChildElement(methods, "include");87 xml.addAttribute(include, "name", methodMap.get("methodName").toString());88 }89 String t = new SimpleDateFormat("MM-dd-HH-mm-ss").format(new Date());90 String xmlSuiteFile = path + File.separator + "testng_suite_" + threadCnt + "_" + t + ".xml";91 xml.saveTo(xmlSuiteFile);92 return xmlSuiteFile;93 }94 /**95 * Auto generate.96 *97 * @param threadCnt the thread cnt98 */99 public static String autoGenerate(int threadCnt) {100 ClassPathResource res = new ClassPathResource(".");101 String basePath = null;102 try {103 //get target dir104 basePath = res.getFile().getParent();105 } catch (IOException e) {106 e.printStackTrace();107 }108 if (basePath == null) {109 basePath = System.getProperty("user.dir");110 }111 return autoGenerate(basePath, threadCnt);112 }113}...

Full Screen

Full Screen

Source:CleanMethodInvokerUtils.java Github

copy

Full Screen

1package com.netease.cloudqa.nlb.api.test.utils;2import com.alibaba.fastjson.JSONObject;3import com.netease.cloudqa.nlb.api.test.framework.common.runtime.ApiRuntimeContext;4import com.netease.cloudqa.nlb.api.test.framework.driver.FrameWorkDriver;5import com.netease.cloudqa.nlb.api.test.framework.model.Response;6import com.netease.cloudqa.nlb.api.test.framework.utils.HttpClientUtils;7import com.netease.cloudqa.nlb.api.test.model.NlbModel;8import java.lang.reflect.InvocationTargetException;9import java.lang.reflect.Method;10import java.util.HashMap;11import java.util.Map;12import java.util.concurrent.TimeUnit;13import static org.testng.Assert.assertEquals;14public class CleanMethodInvokerUtils extends FrameWorkDriver {15 private static Map<String, Method> methodMap = new HashMap<String, Method>();16 private static NlbModel nlbModel;17 final private static String NLB_MODEL = "NLB_MODEL";18 static {19 try {20 methodMap.put("CleanMethodInvokerUtils.cleanListener",21 CleanMethodInvokerUtils.class.getMethod("cleanListener", Map.class,22 HttpClientUtils.class, String.class));23 methodMap.put("CleanMethodInvokerUtils.cleanIngress",24 CleanMethodInvokerUtils.class.getMethod("cleanIngress", Map.class,25 HttpClientUtils.class));26 methodMap.put("CleanMethodInvokerUtils.cleanIngressWithWaiting",27 CleanMethodInvokerUtils.class.getMethod("cleanIngressWithWaiting", Map.class,28 HttpClientUtils.class));29 } catch (NoSuchMethodException e) {30 e.printStackTrace();31 } catch (SecurityException e) {32 e.printStackTrace();33 }34 }35 public static void invokeMethod(String methodName, Object... args) {36 try {37 nlbModel = (NlbModel) ApiRuntimeContext.CaseContext.getPrameter(NLB_MODEL);38 methodMap.get(methodName).invoke(new CleanMethodInvokerUtils(), args);39 } catch (IllegalAccessException e) {40 e.printStackTrace();41 } catch (IllegalArgumentException e) {42 e.printStackTrace();43 } catch (InvocationTargetException e) {44 e.printStackTrace();45 }46 }47 public void cleanListener(Map<String, String> headers, HttpClientUtils httpClient, String instanceId) {48 if (nlbModel != null) {49 Response res = CommonApi.deleteLn(headers, httpClient, instanceId, nlbModel.getListener().getListenerId());50 assertEquals(res.getCode(), 200, "Clean Lb listener failed!");51 }52 try {53 TimeUnit.SECONDS.sleep(5);54 } catch (InterruptedException e) {55 System.out.println("error");56 }57 }58 public void cleanIngress(Map<String, String> headers, HttpClientUtils httpClient) {59 if (nlbModel != null) {60 Response res = CommonApi.deleteLbIngAdmin(headers, httpClient, nlbModel.getLoadBalancer().getInstanceId());61 assertEquals(res.getCode(), 200, "Clean ing failed!");62 JSONObject resJson = JSONObject.parseObject(res.getHtml());63 String status = CommonApi.waitLbDeleteIng(headers, httpClient, resJson.getString("InstanceId"));64 assertEquals(status, "DELETED", "Delete ing failed!");65 logger.info("Clean ingress successfully!");66 }67 }68 public void cleanIngressWithWaiting(Map<String, String> headers, HttpClientUtils httpClient) {69 if (nlbModel != null) {70 String status = CommonApi.waitIng(headers, httpClient, nlbModel.getLoadBalancer().getInstanceId());71 assertEquals(status, "WORKING", "Ingress status is not WORKING!");72 Response res = CommonApi.deleteLbIngAdmin(headers, httpClient, nlbModel.getLoadBalancer().getInstanceId());73 assertEquals(res.getCode(), 200, "Clean ing failed!");74 logger.info("Clean data successfully!");75 }76 }77}...

Full Screen

Full Screen

Source:OrderUtils.java Github

copy

Full Screen

1package base;2import org.testng.IMethodInstance;3import org.testng.IMethodInterceptor;4import org.testng.ITestContext;5import java.util.*;6import java.util.function.Function;7import java.util.stream.Collectors;8public class OrderUtils implements IMethodInterceptor {9 private static <T> void orderMethod(10 T currentMethod, Map<String, T> methodMap, Map<String, Set<T>> dependedMap, Set<T> usedSet,11 List<T> destinationList, Function<T, String> getNameFunction, Function<T, String[]> getDependencyFunction)12 {13 usedSet.add(currentMethod);14 for (String methodName : getDependencyFunction.apply(currentMethod)) {15 methodMap.computeIfPresent(methodName, (k, method) -> {16 if (!usedSet.contains(method)) {17 orderMethod(method, methodMap, dependedMap, usedSet, destinationList,18 getNameFunction, getDependencyFunction);19 }20 return method;21 });22 }23 destinationList.add(currentMethod);24 dependedMap.computeIfPresent(getNameFunction.apply(currentMethod), (k, v) -> {25 for (T method : v) {26 if (!usedSet.contains(method)) {27 orderMethod(method, methodMap, dependedMap, usedSet, destinationList,28 getNameFunction, getDependencyFunction);29 }30 }31 return v;32 });33 }34 public static <T> List<List<T>> orderMethods(35 List<T> sourceList, Function<T, String> getNameFunction, Function<T, String[]> getDependencyFunction)36 {37 Map<String, Set<T>> dependedMap = new HashMap<>();38 for (T method : sourceList) {39 for (String dependedName : getDependencyFunction.apply(method)) {40 dependedMap.computeIfAbsent(dependedName, key -> new HashSet<>()).add(method);41 }42 }43 Map<String, T> methodMap = sourceList.stream().collect(Collectors.toMap(getNameFunction, Function.identity()));44 Set<T> usedSet = new HashSet<>();45 List<List<T>> resultList = new ArrayList<>();46 for (T method : sourceList) {47 if (!usedSet.contains(method)) {48 List<T> destinationList = new ArrayList<>();49 resultList.add(destinationList);50 orderMethod(method, methodMap, dependedMap, usedSet, destinationList,51 getNameFunction, getDependencyFunction);52 }53 }54 return resultList;55 }56 public static <T> Optional<List<T>> find(List<List<T>> list, T method) {57 for (List<T> item : list) {58 if (item.contains(method)) {59 return Optional.of(item);60 }61 }62 return Optional.empty();63 }64 @Override65 public List<IMethodInstance> intercept(List<IMethodInstance> list, ITestContext iTestContext) {66 return orderMethods(list, m -> m.getMethod().getQualifiedName(), m -> m.getMethod().getMethodsDependedUpon())67 .stream().flatMap(List::stream).collect(Collectors.toList());68 }69}...

Full Screen

Full Screen

MethodMap

Using AI Code Generation

copy

Full Screen

1MethodMap m = new MethodMap();2m.add("test1", "testMethod1");3m.add("test2", "testMethod2");4m.add("test3", "testMethod3");5m.add("test4", "testMethod4");6m.add("test5", "testMethod5");7m.add("test6", "testMethod6");8m.add("test7", "testMethod7");9m.add("test8", "testMethod8");10m.add("test9", "testMethod9");11m.add("test10", "testMethod10");12m.add("test11", "testMethod11");13m.add("test12", "testMethod12");14m.add("test13", "testMethod13");15m.add("test14", "testMethod14");16m.add("test15", "testMethod15");17m.add("test16", "testMethod16");18m.add("test17", "testMethod17");19m.add("test18", "testMethod18");20m.add("test19", "testMethod19");21m.add("test20", "testMethod20");22m.add("test21", "testMethod21");23m.add("test22", "testMethod22");24m.add("test23", "testMethod23");25m.add("test24", "testMethod24");26m.add("test25", "testMethod25");27m.add("test26", "testMethod26");28m.add("test27", "testMethod27");29m.add("test28", "testMethod28");30m.add("test29", "testMethod29");31m.add("test30", "testMethod30");32m.add("test31", "testMethod31");33m.add("test32", "testMethod32");34m.add("test33", "testMethod33");35m.add("test34", "testMethod34");36m.add("test35", "testMethod35");37m.add("test36", "testMethod36");38m.add("test37", "testMethod37");39m.add("test38", "testMethod38");40m.add("test39", "testMethod39");41m.add("test40", "testMethod40");42m.add("test41", "testMethod41");43m.add("test42", "testMethod42");44m.add("test43", "testMethod43");45m.add("test44", "testMethod44");46m.add("test45",

Full Screen

Full Screen

MethodMap

Using AI Code Generation

copy

Full Screen

1MethodMap<String, String> map = new MethodMap<String, String>();2map.put("key1", "value1");3map.put("key2", "value2");4map.put("key3", "value3");5map.put("key4", "value4");6map.put("key5", "value5");7map.put("key6", "value6");8map.put("key7", "value7");9map.put("key8", "value8");10map.put("key9", "value9");11map.put("key10", "value10");12map.put("key11", "value11");13map.put("key12", "value12");14map.put("key13", "value13");15map.put("key14", "value14");16map.put("key15", "value15");17map.put("key16", "value16");18map.put("key17", "value17");19map.put("key18", "value18");20map.put("key19", "value19");21map.put("key20", "value20");22map.put("key21", "value21");23map.put("key22", "value22");24map.put("key23", "value23");25map.put("key24", "value24");26map.put("key25", "value25");27map.put("key26", "value26");28map.put("key27", "value27");29map.put("key28", "value28");30map.put("key29", "value29");31map.put("key30", "value30");32map.put("key31", "value31");33map.put("key32", "value32");34map.put("key33", "value33");35map.put("key34", "value34");36map.put("key35", "value35");37map.put("key36", "value36");38map.put("key37", "value37");39map.put("key38", "value38");40map.put("key39", "value39");41map.put("key40", "value40");42map.put("key41", "value41");43map.put("key42", "value42");44map.put("key43", "value43");45map.put("key44", "value44");46map.put("key45", "value45");47map.put("key46", "value46");48map.put("key47", "value47");49map.put("key48

Full Screen

Full Screen

MethodMap

Using AI Code Generation

copy

Full Screen

1import org.testng.*;2import org.testng.annotations.*;3import org.testng.collections.*;4import org.testng.internal.*;5import org.testng.internal.annotations.*;6import org.testng.internal.annotations.IAnnotationFinder.AnnotationFinder;7import org.testng.internal.annotations.IAnnotationFinder.Finder;8import org.testng.internal.annotations.IAnnotationFinder.MethodAnnotationInfo;9import org.testng.internal.annotations.IAnnotationFinder.MethodAnnotationInfo.AnnotationInfo;10import org.testng.internal.annotations.IAnnotationFinder.ParameterAnnotationInfo;11import org.testng.internal.annotations.IAnnotationFinder.ParameterAnnotationInfo.ParameterInfo;12import org.testng.internal.annotations.IAnnotationFinder.TypeAnnotationInfo;13import org.testng.internal.annotations.IAnnotationFinder.TypeAnnotationInfo.TypeInfo;14import org.testng.internal.annotations.IAnnotationFinder.MethodAnnotationInfo;15import org.testng.internal.annotations.IAnnotationFinder.MethodAnnotationInfo.AnnotationInfo;16import org.testng.internal.annotations.IAnnotationFinder.ParameterAnnotationInfo;17import org.testng.internal.annotations.IAnnotationFinder.ParameterAnnotationInfo.ParameterInfo;18import org.testng.internal.annotations.IAnnotationFinder.TypeAnnotationInfo;19import org.testng.internal.annotations.IAnnotationFinder.TypeAnnotationInfo.TypeInfo;20import org.testng.internal.annotations.IAnnotationFinder.MethodAnnotationInfo;21import org.testng.internal.annotations.IAnnotationFinder.MethodAnnotationInfo.AnnotationInfo;22import org.testng.internal.annotations.IAnnotationFinder.ParameterAnnotationInfo;23import org.testng.internal.annotations.IAnnotationFinder.ParameterAnnotationInfo.ParameterInfo;24import org.testng.internal.annotations.IAnnotationFinder.TypeAnnotationInfo;25import org.testng.internal.annotations.IAnnotationFinder.TypeAnnotationInfo.TypeInfo;26import org.testng.internal.annotations.IAnnotationFinder.MethodAnnotationInfo;27import org.testng.internal.annotations.IAnnotationFinder.MethodAnnotationInfo.AnnotationInfo;28import org.testng.internal.annotations.IAnnotationFinder.ParameterAnnotationInfo;29import org.testng.internal.annotations.IAnnotationFinder.ParameterAnnotationInfo.ParameterInfo;30import org.testng.internal.annotations.IAnnotationFinder.TypeAnnotationInfo;31import org.testng.internal.annotations.IAnnotationFinder.TypeAnnotationInfo.TypeInfo;32import org.testng.internal.annotations.IAnnotationFinder.MethodAnnotationInfo;33import org.testng.internal.annotations.IAnnotationFinder.MethodAnnotationInfo.AnnotationInfo;34import org.testng.internal.annotations.IAnnotationFinder.ParameterAnnotationInfo;35import org.testng.internal.annotations.IAnnotationFinder.ParameterAnnotationInfo.ParameterInfo;36import org.testng.internal.annotations.IAnnotationFinder.TypeAnnotationInfo;37import org.testng.internal.annotations.IAnnotationFinder.TypeAnnotationInfo.TypeInfo;38import org.testng.internal.annotations.IAnnotationFinder.MethodAnnotationInfo;39import org.testng.internal.annotations.IAnnotationFinder.MethodAnnotationInfo.AnnotationInfo;40import org.testng.internal.annotations.IAnnotationFinder.ParameterAnnotationInfo;41import org.testng.internal.annotations.IAnnotationFinder.ParameterAnnotationInfo.ParameterInfo;42import org.testng.internal.annotations.IAnnotationFinder.Type

Full Screen

Full Screen

MethodMap

Using AI Code Generation

copy

Full Screen

1MethodMap methodMap = new MethodMap();2String testName = methodMap.getTestName();3String testDescription = methodMap.getTestDescription();4String methodName = methodMap.getMethodName();5String methodDescription = methodMap.getMethodDescription();6Reporter.log("Test Name: " + testName, true);7Reporter.log("Test Description: " + testDescription, true);8Reporter.log("Method Name: " + methodName, true);9Reporter.log("Method Description: " + methodDescription, true);10String methodName = methodMap.getMethodName();11String methodDescription = methodMap.getMethodDescription();12Reporter.log("Method Name: " + methodName, true);13Reporter.log("Method Description: " + methodDescription, true);14String testName = methodMap.getTestName();15String testDescription = methodMap.getTestDescription();16Reporter.log("Test Name: " + testName, true);17Reporter.log("Test Description: " + testDescription, true);18String testName = methodMap.getTestName();19String testDescription = methodMap.getTestDescription();20String methodName = methodMap.getMethodName();21String methodDescription = methodMap.getMethodDescription();22Reporter.log("Test Name: " + testName, true);23Reporter.log("Test Description: " + testDescription, true);24Reporter.log("Method Name: " + methodName, true);25Reporter.log("Method Description: " + methodDescription, true);26String methodName = methodMap.getMethodName();27String methodDescription = methodMap.getMethodDescription();28Reporter.log("Method Name: " + methodName, true);29Reporter.log("Method Description: " + methodDescription, true);30String testName = methodMap.getTestName();31String testDescription = methodMap.getTestDescription();32Reporter.log("Test Name: " + testName, true);33Reporter.log("Test Description: " + testDescription, true);

Full Screen

Full Screen
copy
1Map<String,List<String>> yourMap = new HashMap<String,List<String>>();23List<String> info = new ArrayList<String>();4info.add(number);5info.add(name);6info.add(address);7info.add(phone);89yourMap.put(key, info);10
Full Screen
copy
1public class User implements Serializable {23 private String firstName;4 private String lastNumber;5 private String address;6 private String phoneNumber;78 //Generated getters and setters here....9}10
Full Screen

TestNG tutorial

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.

Chapters

  1. JUnit 5 vs. TestNG: Compare and explore the core differences between JUnit 5 and TestNG from the Selenium WebDriver viewpoint.
  2. Installing TestNG in Eclipse: Start installing the TestNG Plugin and learn how to set up TestNG in Eclipse to begin constructing a framework for your test project.
  3. Create TestNG Project in Eclipse: Get started with creating a TestNG project and write your first TestNG test script.
  4. Automation using TestNG: Dive into how to install TestNG in this Selenium TestNG tutorial, the fundamentals of developing an automation script for Selenium automation testing.
  5. Parallel Test Execution in TestNG: Here are some essential elements of parallel testing with TestNG in this Selenium TestNG tutorial.
  6. Creating TestNG XML File: Here is a step-by-step tutorial on creating a TestNG XML file to learn why and how it is created and discover how to run the TestNG XML file being executed in parallel.
  7. Automation with Selenium, Cucumber & TestNG: Explore for an in-depth tutorial on automation using Selenium, Cucumber, and TestNG, as TestNG offers simpler settings and more features.
  8. JUnit Selenium Tests using TestNG: Start running your regular and parallel tests by looking at how to run test cases in Selenium using JUnit and TestNG without having to rewrite the tests.
  9. Group Test Cases in TestNG: Along with the explanation and demonstration using relevant TestNG group examples, learn how to group test cases in TestNG.
  10. Prioritizing Tests in TestNG: Get started with how to prioritize test cases in TestNG for Selenium automation testing.
  11. Assertions in TestNG: Examine what TestNG assertions are, the various types of TestNG assertions, and situations that relate to Selenium automated testing.
  12. DataProviders in TestNG: Deep dive into learning more about TestNG's DataProvider and how to effectively use it in our test scripts for Selenium test automation.
  13. Parameterization in TestNG: Here are the several parameterization strategies used in TestNG tests and how to apply them in Selenium automation scripts.
  14. TestNG Listeners in Selenium WebDriver: Understand the various TestNG listeners to utilize them effectively for your next plan when working with TestNG and Selenium automation.
  15. TestNG Annotations: Learn more about the execution order and annotation attributes, and refer to the prerequisites required to set up TestNG.
  16. TestNG Reporter Log in Selenium: Find out how to use the TestNG Reporter Log and learn how to eliminate the need for external software with TestNG Reporter Class to boost productivity.
  17. TestNG Reports in Jenkins: Discover how to generate TestNG reports in Jenkins if you want to know how to create, install, and share TestNG reports in Jenkins.

Certification

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.

YouTube

Watch this complete tutorial to learn how you can leverage the capabilities of the TestNG framework for Selenium automation testing.

Run Testng automation tests on LambdaTest cloud grid

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

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful