Java Code Examples for org.testng.ITestResult#getParameters()

The following examples show how to use org.testng.ITestResult#getParameters() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestNGRunner.java    From buck with Apache License 2.0 6 votes vote down vote up
/** Compute the "full name" of a test method, including its parameters, if any. */
private static String getTestMethodNameWithParameters(ITestResult iTestResult) {
  Object[] parameters = iTestResult.getParameters();
  String name = iTestResult.getName();

  if (parameters == null || parameters.length == 0) {
    return name;
  }

  StringBuilder builder = new StringBuilder(name).append(" (");
  builder.append(
      Arrays.stream(parameters)
          .map(
              parameter -> {
                try {
                  return String.valueOf(parameter);
                } catch (Exception e) {
                  return "Unstringable object";
                }
              })
          .collect(Collectors.joining(", ")));
  builder.append(")");
  return builder.toString();
}
 
Example 2
Source File: TestNG_ConsoleRunner.java    From Selenium-Framework-Design-in-Data-Driven-Testing with MIT License 6 votes vote down vote up
/**
 * getTestParams method
 *
 * @param tr
 * @return String
 */
public String getTestParams(ITestResult tr) {
    int iLength = tr.getParameters().length;
    String message = "";

    try {
        if ( tr.getParameters().length > 0 ) {
            message = tr.getParameters()[0].toString();

            for ( int iCount = 0; iCount < iLength; iCount++ ) {
                if ( iCount == 0 ) {
                    message = tr.getParameters()[0].toString();
                }
                else {
                    message = message + ", " + tr.getParameters()[iCount].toString();
                }
            }
        }
    }

    catch(Exception e) {
        // do nothing...
    }

    return message;
}
 
Example 3
Source File: TestNG_ConsoleRunner.java    From Selenium-Framework-Design-in-Data-Driven-Testing with MIT License 6 votes vote down vote up
/**
 * getTestDescription method
 *
 * @param tr
 * @return String
 */
public String getTestDescription(ITestResult tr) {
    String message = "";

    try {
        if ( tr.getParameters().length > 0 ) {
            message = ": " + tr.getParameters()[1].toString();
        }
    }

    catch(Exception e) {
        // do nothing...
    }

    return message;
}
 
Example 4
Source File: TestListener.java    From appium-parallel-execution with MIT License 6 votes vote down vote up
private String composeTestName(ITestResult iTestResult) {
    StringBuffer completeFileName = new StringBuffer();

    completeFileName.append(iTestResult.getTestClass().getRealClass().getSimpleName()); // simplified class name
    completeFileName.append("_");
    completeFileName.append(iTestResult.getName()); // method name

    // all the parameters information
    Object[] parameters = iTestResult.getParameters();
    for(Object parameter : parameters) {
        completeFileName.append("_");
        completeFileName.append(parameter);
    }

    // return the complete name and replace : by - (in the case the emulator have port as device name)
    return completeFileName.toString().replace(":", "-");
}
 
Example 5
Source File: FDSeparateCompilationTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@AfterMethod
public void printCaseError(ITestResult result) {
    if (result.getStatus() == ITestResult.FAILURE) {
        Hierarchy hs = (Hierarchy)result.getParameters()[0];
        System.out.println("Separate compilation case " + hs);
        printCaseDetails(hs);
    }
}
 
Example 6
Source File: TestListener.java    From PatatiumWebUi with Apache License 2.0 5 votes vote down vote up
@Override
public void onTestSuccess(ITestResult tr) {
	for(int i=0;i<Assertion.messageList.size();i++)
	{
		if (tr.getParameters().length>0) {
			sb2.append("<pass_assert_info"+"   method=\""+tr.getTestClass().getName()+"."+tr.getMethod().getMethodName()+"."+tr.getEndMillis()+"\">\n");
		}
		else {
			sb2.append("<pass_assert_info"+"   method=\""+tr.getTestClass().getName()+"."+tr.getMethod().getMethodName()+"\">\n");
		}
		sb2.append("<span class=\"pass_span\">"+Assertion.messageList.get(i)+"</span></br>\n");

		sb2.append("</pass_assert_info>\n");
	}
	/*try {
		//fileWriter2=new FileWriter(file2, true);
		if(file2.exists())
		{
			file2.delete();;
		}
		//fileWriter2=new FileWriter(file2);
		//BufferedWriter output = new BufferedWriter(fileWriter2);
		//output.write(sb2.toString()+"</passed>");
		//output.write("</passed>");
		//output.flush();
		//output.close();

	} catch (IOException e2) {
		// TODO 自动生成的 catch 块
		e2.printStackTrace();
	}*/
	if(file2.exists())
	{
		file2.delete();;
	}
	fileManger.writeWithEncode(file2,"utf-8",true,sb2.toString()+"</passed>");
	log.info("测试用例: "+tr.getMethod().getDescription()+"--passed");
	log.info("测试用例:"+tr.getMethod().getDescription()+"---end");

}
 
Example 7
Source File: AbstractDifidoReporter.java    From difido-reports with Apache License 2.0 5 votes vote down vote up
private List<String> getTestParameters(ITestResult result) {
	List<String> testParameters = new ArrayList<String>();
	if (result.getParameters() != null) {
		for (Object parameter : result.getParameters()) {
			if (parameter != null) {
				testParameters.add(parameter.toString());
			}
		}
	}
	return testParameters;
}
 
Example 8
Source File: CustomTestNgListener.java    From heat with Apache License 2.0 5 votes vote down vote up
/**
 * This method is useful to print the output console log in case of test failed.
 * We are assuming that we put in the context an attribute whose name is the complete test case ID (example: TEST_SUITE.001) and whose value is
 * 'PASSED' or 'SKIPPED' or 'FAILED'.
 * @param tr test case result - testNG handling
 */
@Override
public void onTestFailure(ITestResult tr) {
    if (tr.getParameters().length > 0) {
        Map<String, String> paramMap = (HashMap<String, String>) tr.getParameters()[0];
        ITestContext testContext = tr.getTestContext();
        //testCaseCompleteID - Example: TEST_SUITE.001
        String testCaseCompleteID = testContext.getName() + TestBaseRunner.TESTCASE_ID_SEPARATOR + testContext.getAttribute(TestBaseRunner.ATTR_TESTCASE_ID);
        logger.error("[{}][{}][{}] -- FAILED", testCaseCompleteID,
                    testContext.getAttribute(TestBaseRunner.SUITE_DESCRIPTION_CTX_ATTR).toString(),
                    testContext.getAttribute(TestBaseRunner.TC_DESCRIPTION_CTX_ATTR).toString());

        if (testContext.getAttribute(FAILED_TEST_CASES) == null) {
            failedTc = new ArrayList();
        } else {
            failedTc = (List<ITestResult>) testContext.getAttribute(FAILED_TEST_CASES);
        }
        failedTc.add(tr);
        testContext.setAttribute(FAILED_TEST_CASES, failedTc);

    } else {
        super.onTestFailure(tr);
    }
}
 
Example 9
Source File: ReportListener.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void logMeasurements(ITestResult tr) {
    Object[] parameters = tr.getParameters();
    MeasuredTestContext measuredTestContext;
    if (parameters == null || parameters.length == 0) {
        return;
    } else if (parameters[0] instanceof MeasuredTestContext) {
        measuredTestContext = (MeasuredTestContext) parameters[0];
    } else {
        return;
    }
    tr.setAttribute(tr.getName() + MEASUREMENTS, measuredTestContext.getMeasure());
}
 
Example 10
Source File: FDSeparateCompilationTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@AfterMethod
public void printCaseError(ITestResult result) {
    if (result.getStatus() == ITestResult.FAILURE) {
        Hierarchy hs = (Hierarchy)result.getParameters()[0];
        System.out.println("Separate compilation case " + hs);
        printCaseDetails(hs);
    }
}
 
Example 11
Source File: TestListener.java    From PatatiumAppUi with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onTestSuccess(ITestResult tr) {
	for(int i=0;i<Assertion.messageList.size();i++)
	{
		if (tr.getParameters().length>0) {
			sb2.append("<pass_assert_info"+"   method=\""+tr.getTestClass().getName()+"."+tr.getMethod().getMethodName()+"."+tr.getEndMillis()+"\">\n");
		}
		else {
			sb2.append("<pass_assert_info"+"   method=\""+tr.getTestClass().getName()+"."+tr.getMethod().getMethodName()+"\">\n");
		}
		sb2.append("<span class=\"pass_span\">"+Assertion.messageList.get(i)+"</span></br>\n");

		sb2.append("</pass_assert_info>\n");
	}
	/*try {
		//fileWriter2=new FileWriter(file2, true);
		if(file2.exists())
		{
			file2.delete();;
		}
		//fileWriter2=new FileWriter(file2);
		//BufferedWriter output = new BufferedWriter(fileWriter2);
		//output.write(sb2.toString()+"</passed>");
		//output.write("</passed>");
		//output.flush();
		//output.close();

	} catch (IOException e2) {
		// TODO 自动生成的 catch 块
		e2.printStackTrace();
	}*/
	if(file2.exists())
	{
		file2.delete();;
	}
	fileManger.writeWithEncode(file2,"utf-8",true,sb2.toString()+"</passed>");
	log.info("测试用例: "+tr.getMethod().getDescription()+"--passed");
	log.info("测试用例:"+tr.getMethod().getDescription()+"---end");

}
 
Example 12
Source File: SingleConsumerQueueTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
/** Free memory by clearing unused resources after test execution. */
static void cleanUp(ITestResult testResult) {
  Object[] params = testResult.getParameters();
  for (int i = 0; i < params.length; i++) {
    Object param = params[i];
    if ((param instanceof SingleConsumerQueue<?>)) {
      boolean linearizable =
          (((SingleConsumerQueue<?>) param).factory.apply(null) instanceof LinearizableNode<?>);
      params[i] = param.getClass().getSimpleName() + "_"
          + (linearizable ? "linearizable" : "optimistic");
    } else {
      params[i] = Objects.toString(param);
    }
  }
}
 
Example 13
Source File: ReporterUtil.java    From qaf with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static String getMethodIdentifier(ITestResult result){

	if(result.getAttribute(QAF_TEST_IDENTIFIER)!=null){
		return (String) result.getAttribute(QAF_TEST_IDENTIFIER);
	}
	
	String id = getMethodName(result);
	String identifierKey = ApplicationProperties.TESTCASE_IDENTIFIER_KEY.getStringVal("testCaseId");

	Map<String, Object> metadata =
			new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);

	if (result.getMethod() instanceof TestNGScenario) {
		TestNGScenario scenario = (TestNGScenario) result.getMethod();
		metadata.putAll(scenario.getMetaData());
	}
	if(result.getParameters()!=null && result.getParameters().length>0){
		if(result.getParameters()[0] instanceof Map<?, ?>){
			metadata.putAll((Map<String, Object>)result.getParameters()[0]);
		}
	}
	String idFromMetaData = metadata.getOrDefault(identifierKey,"").toString();
	if (StringUtil.isNotBlank(idFromMetaData) ) {
		id = idFromMetaData;
	}
	id=StringUtil.toTitleCaseIdentifier(id);
	
	if(id.length()>45){
		id=id.substring(0, 45);
	}
	result.setAttribute(QAF_TEST_IDENTIFIER,id);
	return (String) result.getAttribute(QAF_TEST_IDENTIFIER);
}
 
Example 14
Source File: FDSeparateCompilationTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@AfterMethod
public void printCaseError(ITestResult result) {
    if (result.getStatus() == ITestResult.FAILURE) {
        Hierarchy hs = (Hierarchy)result.getParameters()[0];
        System.out.println("Separate compilation case " + hs);
        printCaseDetails(hs);
    }
}
 
Example 15
Source File: ExtentTestManager.java    From extentreports-testng-adapter with Apache License 2.0 5 votes vote down vote up
public static synchronized ExtentTest createMethod(ITestResult result, Boolean createAsChild) {
    if (!createAsChild)
        return createMethod(result);

    String className = result.getInstance().getClass().getSimpleName();
    String methodName = result.getMethod().getMethodName();
    String desc = result.getMethod().getDescription();
    ExtentTest classTest;

    if (classTestMap.containsKey(className)) {
        classTest = classTestMap.get(className);
    } else {
        classTest = ExtentService.getInstance().createTest(className, desc);
        classTestMap.put(className, classTest);
    }

    Optional<Test> test = classTest.getModel().getNodeContext().getAll().stream()
            .filter(x -> x.getName().equals(methodName)).findFirst();

    if (result.getParameters().length > 0) {
        if (!test.isPresent()) {
            createTest(result, classTest);
        }
        String paramName = Arrays.asList(result.getParameters()).toString();
        ExtentTest paramTest = methodTest.get().createNode(paramName);
        dataProviderTest.set(paramTest);
    } else {
        dataProviderTest.set(null);
        createTest(result, classTest);
    }

    return methodTest.get();
}
 
Example 16
Source File: TestNGTestResultProcessorAdapter.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private String calculateTestCaseName(ITestResult iTestResult) {
    Object[] parameters = iTestResult.getParameters();
    String name = iTestResult.getName();
    if (parameters != null && parameters.length > 0) {
        StringBuilder builder = new StringBuilder(name).
                append("[").
                append(iTestResult.getMethod().getCurrentInvocationCount()).
                append("]");

        StringBuilder paramsListBuilder = new StringBuilder("(");
        int i = 0;
        for (Object parameter : parameters) {
            if (parameter == null) {
                paramsListBuilder.append("null");
            } else {
                try {
                    paramsListBuilder.append(parameter.toString());
                } catch (Exception e) {
                    // This may be thrown by the caller of this method at a later time
                    iTestResult.setThrowable(new UnrepresentableParameterException(iTestResult, i, e));
                    return builder.toString();
                }
            }
            if (++i < parameters.length) {
                paramsListBuilder.append(", ");
            }
        }
        paramsListBuilder.append(")");
        return builder.append(paramsListBuilder.toString()).toString();
    } else {
        return name;
    }
}
 
Example 17
Source File: AbstractTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
@AfterMethod(alwaysRun = true)
public void validateIfSuccessful(ITestResult result) {
  try {
    if (result.isSuccess()) {
      for (Object param : result.getParameters()) {
        validate(param);
      }
    }
  } catch (AssertionError caught) {
    result.setStatus(ITestResult.FAILURE);
    result.setThrowable(caught);
  }
  initMocks(this);
}
 
Example 18
Source File: TestNGTestResultProcessorAdapter.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private String calculateTestCaseName(ITestResult iTestResult) {
    Object[] parameters = iTestResult.getParameters();
    String name = iTestResult.getName();
    if (parameters != null && parameters.length > 0) {
        StringBuilder builder = new StringBuilder(name).
                append("[").
                append(iTestResult.getMethod().getCurrentInvocationCount()).
                append("]");

        StringBuilder paramsListBuilder = new StringBuilder("(");
        int i = 0;
        for (Object parameter : parameters) {
            if (parameter == null) {
                paramsListBuilder.append("null");
            } else {
                try {
                    paramsListBuilder.append(parameter.toString());
                } catch (Exception e) {
                    // This may be thrown by the caller of this method at a later time
                    iTestResult.setThrowable(new UnrepresentableParameterException(iTestResult, i, e));
                    return builder.toString();
                }
            }
            if (++i < parameters.length) {
                paramsListBuilder.append(", ");
            }
        }
        paramsListBuilder.append(")");
        return builder.append(paramsListBuilder.toString()).toString();
    } else {
        return name;
    }
}
 
Example 19
Source File: TestResultListener.java    From WebAndAppUITesting with GNU General Public License v3.0 4 votes vote down vote up
private int getId(ITestResult result) {
	int id = result.getTestClass().getName().hashCode();
	id = id + result.getMethod().getMethodName().hashCode();
	id = id + (result.getParameters() != null ? Arrays.hashCode(result.getParameters()) : 0);
	return id;
}
 
Example 20
Source File: QAFTestNGListener2.java    From qaf with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private void deployResult(ITestResult tr) {
	try {
		if (ResultUpdator.getResultUpdatorsCnt()>0 && (tr.getMethod() instanceof TestNGScenario) && ((tr.getStatus() == ITestResult.FAILURE)
				|| (tr.getStatus() == ITestResult.SUCCESS || tr.getStatus() == ITestResult.SKIP))) {

			TestCaseRunResult.Status status = tr.getStatus() == ITestResult.SUCCESS ? TestCaseRunResult.Status.PASS
					: tr.getStatus() == ITestResult.FAILURE ? TestCaseRunResult.Status.FAIL
							: TestCaseRunResult.Status.SKIPPED;

			TestNGScenario scenario = (TestNGScenario) tr.getMethod();
			Map<String, Object> params = new HashMap<String, Object>(scenario.getMetaData());
			params.put("duration", tr.getEndMillis() - tr.getStartMillis());

			Map<String, Object> executionInfo = new HashMap<String, Object>();
			executionInfo.put("testName", tr.getTestContext().getCurrentXmlTest().getName());
			executionInfo.put("suiteName", tr.getTestContext().getSuite().getName());
			
			Map<String, Object> runPrams = new HashMap<String, Object>(
					tr.getTestContext().getCurrentXmlTest().getAllParameters());
			runPrams.putAll(ConfigurationConverter.getMap(getBundle().subset("env")));
			executionInfo.put("env", runPrams);
			int retryCount = getBundle().getInt(RetryAnalyzer.RETRY_INVOCATION_COUNT, 0);
			boolean willRetry =  getBundle().getBoolean(RetryAnalyzer.WILL_RETRY, false);
			getBundle().clearProperty(RetryAnalyzer.WILL_RETRY);
			if(retryCount>0) {
				executionInfo.put("retryCount", retryCount);
			}
			TestCaseRunResult testCaseRunResult = new TestCaseRunResult(status, scenario.getMetaData(),
					tr.getParameters(), executionInfo, scenario.getSteps(), tr.getStartMillis(),willRetry,scenario.isTest() );
			testCaseRunResult.setClassName(scenario.getClassOrFileName());
			if (scenario.getGroups() != null && scenario.getGroups().length > 0) {
				testCaseRunResult.getMetaData().put("groups", scenario.getGroups());
			}
			testCaseRunResult.getMetaData().put("description",scenario.getDescription());
			testCaseRunResult.setThrowable(tr.getThrowable());
			ResultUpdator.updateResult(testCaseRunResult);
		}
	} catch (Exception e) {
		logger.warn("Unable to deploy result", e);
	}
}