下面列出了org.testng.annotations.BeforeTest#org.testng.ITestContext 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected void setSkip(ITestResult tr, ITestContext context) {
if (getBundle().getInt("testng.version", 6) > 5) {
// Fix for testNG 6
if ((null != context.getFailedTests())) {
if (((null != context.getFailedTests().getResults(tr.getMethod())))
&& (context.getFailedTests().getResults(tr.getMethod())
.size() > 1)) {
context.getFailedTests().getResults(tr.getMethod()).remove(tr);
} else {
context.getFailedTests().removeResult(tr.getMethod());
}
}
tr.setStatus(ITestResult.SKIP);
if (null != context.getSkippedTests()) {
context.getSkippedTests().addResult(tr, tr.getMethod());
}
} else {
tr.setStatus(ITestResult.SKIP);
}
}
public static Measure collectMeasurements(ITestContext iTestContext) {
if (iTestContext == null) {
throw new IllegalArgumentException("No testng testcontext is given.");
}
IResultMap failed = iTestContext.getFailedTests();
IResultMap success = iTestContext.getPassedTests();
MeasureAll allMeasurement = new MeasureAll();
failed.getAllResults().stream().forEach(
getiTestResultConsumer(allMeasurement)
);
success.getAllResults().stream().forEach(
getiTestResultConsumer(allMeasurement)
);
return allMeasurement;
}
@Test(timeOut = 10_000)
public void testReadInterleaved(ITestContext context) throws Exception {
TransactionManager tm = newTransactionManager(context);
TTable table = new TTable(connection, TEST_TABLE);
// Put some data on the DB
Transaction t1 = tm.begin();
Transaction t2 = tm.begin();
Put put = new Put(row);
put.addColumn(family, col, data);
table.put(t1, put);
tm.commit(t1);
Get get = new Get(row);
Result result = table.get(t2, get);
assertFalse(result.containsColumn(family, col), "Should be unable to read column");
}
private void addPendingMethods(ITestContext iTestContext) {
for (ITestNGMethod method : iTestContext.getExcludedMethods()) {
if (method.isTest() && !method.getEnabled() && isInActiveGroup(method, iTestContext)) {
Description description = new Description().withValue(method.getDescription());
String suiteUid = getSuiteUid(iTestContext);
TestCaseStartedEvent event = new TestCaseStartedEvent(suiteUid, method.getMethodName());
if (description.getValue() != null) {
event.setDescription(description);
}
Annotation[] annotations = method.getConstructorOrMethod().getMethod().getAnnotations();
AnnotationManager am = new AnnotationManager(annotations);
am.setDefaults(method.getInstance().getClass().getAnnotations());
am.update(event);
getLifecycle().fire(event);
getLifecycle().fire(new TestCasePendingEvent());
fireFinishTest();
}
}
}
@Override
public void beforeInvocation(IInvokedMethod method, ITestResult testResult, ITestContext context) {
int failed = findFailed(context);
if (failed > 0) {
LOG.error("Masking will not proceed. {} Configurations have failed",failed);
return;
}
Method rmethod = method.getTestMethod().getConstructorOrMethod().getMethod();
if (rmethod.getAnnotation(Test.class) != null ||
rmethod.getAnnotation(BeforeClass.class) != null ||
rmethod.getAnnotation(BeforeTest.class) != null) {
if (rmethod.getAnnotation(RunsWithController.class) != null ||
rmethod.getDeclaringClass().getAnnotation(RunsWithController.class) != null) {
LOG.warn("Method or Class of {} asks Controller to be masked", rmethod.getName());
AnnotationsHelper p = SteviaContext.getSpringContext().getBean(AnnotationsHelper.class);
try {
p.maskExistingController(rmethod);
masked = true;
} catch (Throwable e) {
throw new IllegalStateException("failed to replace controller",e);
}
}
}
}
@BeforeSuite
public void initTestSuite(ITestContext context) throws Exception {
SecurityProviderUtility.installBCProvider();
logger.info("Invoked initTestSuite of '{}'", context.getCurrentXmlTest().getName());
//Properties with the file: preffix will point to real .json files stored under src/test/resources folder
String properties = context.getCurrentXmlTest().getParameter("file");
Properties prop = new Properties();
prop.load(Files.newBufferedReader(Paths.get(properties), DEFAULT_CHARSET)); //do not bother much about IO issues here
Map<String, String> parameters = new Hashtable<>();
//do not bother about empty keys... but
//If a value is found null, this will throw a NPE since we are using a Hashtable
prop.forEach((Object key, Object value) -> parameters.put(key.toString(), decodeFileValue(value.toString())));
// Override test parameters
context.getSuite().getXmlSuite().setParameters(parameters);
if (client==null) {
setupClient(context.getSuite().getXmlSuite().getParameters());
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
}
@Override
public void onFinish(ITestContext context) {
LOGGER.info("PASSED TEST CASES");
context.getPassedTests()
.getAllResults()
.forEach(result -> {
LOGGER.info(result.getName());
});
LOGGER.info("FAILED TEST CASES");
context.getFailedTests()
.getAllResults()
.forEach(result -> {
LOGGER.info(result.getName());
});
LOGGER.info("Test completed on: " + context.getEndDate()
.toString());
}
@Test(timeOut = 10_000)
public void testMultipleCellChangesOnSameRow(ITestContext context) throws Exception {
TransactionManager tm = newTransactionManager(context);
TTable tt = new TTable(connection, TEST_TABLE);
Transaction t1 = tm.begin();
Transaction t2 = tm.begin();
LOG.info("Transactions created " + t1 + " " + t2);
byte[] row = Bytes.toBytes("row");
byte[] fam = Bytes.toBytes(TEST_FAMILY);
byte[] col1 = Bytes.toBytes("testdata1");
byte[] col2 = Bytes.toBytes("testdata2");
byte[] data = Bytes.toBytes("testWrite-1");
Put p2 = new Put(row);
p2.addColumn(fam, col1, data);
tt.put(t2, p2);
tm.commit(t2);
Put p1 = new Put(row);
p1.addColumn(fam, col2, data);
tt.put(t1, p1);
tm.commit(t1);
}
/**
* Invoked after the test class is instantiated and before any configuration method is called.
*/
public void onStart(ITestContext context) {
System.out.println("Changing System.out...");
while (System.out instanceof SysOutPrintStream) {
System.setOut(((SysOutPrintStream) System.out).getOriginalSysOut());
}
while (System.err instanceof SysOutPrintStream) {
System.setErr(((SysOutPrintStream) System.err).getOriginalSysOut());
}
old_stdout = System.out;
old_stderr = System.err;
unsolicitedOut = new ByteArrayOutputStream();
unsolicitedErr = new ByteArrayOutputStream();
suffix = System.getProperty(SUFFIX);
if (suffix != null)
suffix = suffix.trim();
output_dir = context.getOutputDirectory(); // + File.separator + context.getName() + suffix + ".xml";
System.setOut(new SysOutPrintStream(new JUnitXMLReporterOutputStream(this, 1), old_stdout));
System.setErr(new SysOutPrintStream(new JUnitXMLReporterOutputStream(this, 2), old_stderr));
}
@Test(timeOut = 60_000)
public void testShadowCellsExistanceInAutocommit(ITestContext context) throws Exception {
TransactionManager tm = newTransactionManager(context);
TTable table = new TTable(connection, TEST_TABLE);
HBaseTransaction t1 = (HBaseTransaction) tm.begin();
// Test shadow cells are created properly
Put put = new Put(row);
put.addColumn(family, qualifier, data1);
put = TTable.markPutAsCommitted(put, t1.getWriteTimestamp(), t1.getWriteTimestamp());
table.getHTable().put(put);
// After markPutAsCommitted test that both cell and shadow cell are there
assertTrue(hasCell(row, family, qualifier, t1.getStartTimestamp(), new TTableCellGetterAdapter(table)),
"Cell should be there");
assertTrue(hasShadowCell(row, family, qualifier, t1.getStartTimestamp(), new TTableCellGetterAdapter(table)),
"Shadow cell should be there");
}
public void onStart(ITestContext context) {
ITestNGMethod[] allTestMethods = context.getAllTestMethods();
if (allTestMethods == null) {
return;
}
if (httpServer == null && hasEverrestJettyListenerTestHierarchy(allTestMethods)) {
httpServer = new JettyHttpServer();
context.setAttribute(JETTY_PORT, httpServer.getPort());
context.setAttribute(JETTY_SERVER, httpServer);
try {
httpServer.start();
httpServer.resetFactories();
httpServer.resetFilter();
RestAssured.port = httpServer.getPort();
RestAssured.basePath = JettyHttpServer.UNSECURE_REST;
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
throw new RuntimeException(e.getLocalizedMessage(), e);
}
}
}
private boolean configurationError( ITestContext context ) {
// check if this is a configuration issue
List<ITestResult> failedConfigurations = Arrays.asList(context.getFailedConfigurations()
.getAllResults()
.toArray(
new ITestResult[context.getFailedConfigurations()
.getAllResults()
.size()]));
for (ITestResult failedResult : failedConfigurations) {
if (failedResult.getThrowable() != null) {
logger.fatal("Configuration failed!", failedResult.getThrowable());
return true;
}
}
return false;
}
@Override
public void onStart(ITestContext context) {
ScenarioNode scenario = new ScenarioNode(context.getName());
currentMachine.addChild(scenario);
currentTestScenario = scenario;
// TODO: We want to avoid a case in which there is the same test class
// in different tests and a new scenario class is not created
testClassName = null;
}
public DataSupplierMetaData(final ITestContext context, final ITestNGMethod testMethod) {
this.testNGMethod = new TestNGMethod(context, testMethod);
this.transpose = testNGMethod.getDataSupplierArg(DataSupplier::transpose, false);
this.flatMap = testNGMethod.getDataSupplierArg(DataSupplier::flatMap, false);
this.indices = testNGMethod.getDataSupplierArg(DataSupplier::indices, new int[0]);
this.testData = transform();
}
@BeforeTest
@Parameters({"platformName", "deviceName", "browserName"})
public void Setup(ITestContext testContext, String platformName, String deviceName, String browserName) throws MalformedURLException {
Map<String, String> testngParams = testContext.getCurrentXmlTest().getAllParameters();
String kobitonURL = testngParams.get("kobitonURL");
if (platformName.toLowerCase().equals("android")) {
driver = new AndroidDriver(new URL(kobitonURL), this.generateDesiredCaps(platformName, deviceName, browserName));
} else {
driver = new IOSDriver(new URL(kobitonURL), this.generateDesiredCaps(platformName, deviceName, browserName));
}
driver.manage().timeouts().implicitlyWait(90, TimeUnit.SECONDS);
}
@Override
public void onStart(ITestContext arg0) {
// suppose to only run othervm mode
if (isRunWithSecurityManager()) {
JAXPPolicyManager policyManager = JAXPPolicyManager.getJAXPPolicyManager(true);
policyManager.addPermission(new SocketPermission("openjdk.java.net:80", "connect,resolve"));
policyManager.addPermission(new SocketPermission("www.w3.org:80", "connect,resolve"));
}
}
@BeforeSuite
public void initTestSuite(ITestContext context) throws IOException {
SecurityProviderUtility.installBCProvider();
Reporter.log("Invoked init test suite method \n", true);
String propertiesFile = context.getCurrentXmlTest().getParameter("propertiesFile");
if (StringHelper.isEmpty(propertiesFile)) {
propertiesFile = "target/test-classes/testng.properties";
}
FileInputStream conf = new FileInputStream(propertiesFile);
Properties prop = new Properties();
prop.load(conf);
Map<String, String> parameters = new HashMap<String, String>();
for (Entry<Object, Object> entry : prop.entrySet()) {
Object key = entry.getKey();
Object value = entry.getValue();
if (StringHelper.isEmptyString(key) || StringHelper.isEmptyString(value)) {
continue;
}
parameters.put(key.toString(), value.toString());
}
// Overrided test paramters
context.getSuite().getXmlSuite().setParameters(parameters);
}
@Parameters("wmTests")
@Override
public void onFinish(ITestContext iTestContext) {
if (isWiremockTest(iTestContext, "wmTests")) {
logger.info("{} was a wiremock test.\n Wiremock server is stopping...", iTestContext.getCurrentXmlTest().getName());
this.wmServer.stop();
logger.info("... Wiremock server stopped");
}
}
@Test(dataProvider = TEST_CONTEXT)
@Description(
given = "there is a running cloudbreak",
when = "a valid DistroX create request is sent",
then = "DistroX cluster with external database is created")
public void testCreateAndScaleDistroX(TestContext testContext, ITestContext iTestContext) {
String imageSettings = resourcePropertyProvider().getName();
DistroXScaleTestParameters params = new DistroXScaleTestParameters(iTestContext.getCurrentXmlTest().getAllParameters());
DistroXExternalDatabaseTestDto dbTestContext = testContext.given(DIX_EXTDB_KEY, DistroXExternalDatabaseTestDto.class)
.withAvailabilityType(DistroXDatabaseAvailabilityType.NON_HA);
if (params.isImageCatalogConfigured()) {
createImageCatalogWithUrl(testContext, params.getImageCatalogName(), params.getImageCatalogUrl());
dbTestContext.given(imageSettings, DistroXImageTestDto.class)
.withImageCatalog(params.getImageCatalogName())
.withImageId(params.getImageId());
}
DistroXTestDto currentContext = dbTestContext
.given(DistroXTestDto.class).withImageSettingsIf(params.isImageCatalogConfigured(), imageSettings)
.withExternalDatabase(DIX_EXTDB_KEY)
.when(distroXTestClient.create())
.await(STACK_AVAILABLE);
for (int i = 0; i < params.getTimes(); i++) {
currentContext = currentContext
.when(distroXTestClient.scale(params.getHostgroup(), params.getScaleUp()))
.await(STACK_AVAILABLE)
.when(distroXTestClient.stop())
.await(STACK_STOPPED)
.when(distroXTestClient.start())
.await(STACK_AVAILABLE)
.when(distroXTestClient.scale(params.getHostgroup(), params.getScaleDown()))
.await(STACK_AVAILABLE);
}
currentContext.validate();
}
@Override
public void afterInvocation(IInvokedMethod method, ITestResult testResult, ITestContext context) {
int failed = findFailed(context);
if (failed > 0) {
LOG.error("Preconditions execution will not proceed. {} Configurations have failed",failed);
return;
}
Method rmethod = method.getTestMethod().getConstructorOrMethod().getMethod();
Object proxy = proxifyObject(method);
if (rmethod.getAnnotation(Test.class) != null) {
if (rmethod.getAnnotation(Postconditions.class) != null) {
LOG.warn("Method or Class of {} wants postconditions to be checked", rmethod.getName());
AnnotationsHelper p = SteviaContext.getSpringContext().getBean(AnnotationsHelper.class);
try {
LOG.debug("Mask and Execute Postconditions of method {} ",rmethod.getName());
p.maskAndExecPostconditions(rmethod, proxy);
LOG.debug("Mask and Execute Postconditions of method {} DONE",rmethod.getName());
} catch (Throwable e) {
Throwable realException = findExceptionWithMessage(e);
LOG.error("Detected exception in postconditions execution, message = "+realException.getMessage(),e);
if (realException instanceof RuntimeException ) {
throw ((RuntimeException)realException);
} else {
throw new IllegalStateException(realException.getMessage(),realException);
}
}
}
}
}
default int getQTestProjectId(ITestContext context) {
String id = context.getSuite().getParameter(SpecialKeywords.QTEST_PROJECT_ID);
if (id != null) {
return Integer.valueOf(id.trim());
} else {
return -1;
}
}
@Test(timeOut = 30_000)
public void testCellCommitTimestampIsLocatedInShadowCellsAfterNotBeingInvalidated(ITestContext context) throws Exception {
CommitTable.Client commitTableClient = spy(getCommitTable(context).getClient());
AbstractTransactionManager tm = spy((AbstractTransactionManager) newTransactionManager(context, commitTableClient));
// The next two lines avoid steps 2), 3) and 5) and go directly to step 6)
// in AbstractTransactionManager.locateCellCommitTimestamp()
SettableFuture<Optional<CommitTimestamp>> f = SettableFuture.create();
f.set(Optional.<CommitTimestamp>absent());
doReturn(f).when(commitTableClient).getCommitTimestamp(any(Long.class));
Table htable = connection.getTable(TableName.valueOf(TEST_TABLE));
SnapshotFilterImpl snapshotFilter = new SnapshotFilterImpl(new HTableAccessWrapper(htable, htable),
tm.getCommitTableClient());
try (TTable table = spy(new TTable(htable, snapshotFilter, false))) {
// Commit a transaction to addColumn ST/CT in commit table
HBaseTransaction tx1 = (HBaseTransaction) tm.begin();
Put put = new Put(row1);
put.addColumn(family, qualifier, data1);
table.put(tx1, put);
tm.commit(tx1);
// Upon commit, the commit data should be in the shadow cells
// Test the locator finds the appropriate data in the shadow cells
HBaseCellId hBaseCellId = new HBaseCellId(table, row1, family, qualifier,
tx1.getStartTimestamp());
CommitTimestampLocator ctLocator = new CommitTimestampLocatorImpl(hBaseCellId,
Maps.<Long, Long>newHashMap());
CommitTimestamp ct = snapshotFilter.locateCellCommitTimestamp(tx1.getStartTimestamp(), tm.tsoClient.getEpoch(),
ctLocator,false);
assertTrue(ct.isValid());
assertEquals(ct.getValue(), tx1.getCommitTimestamp());
assertTrue(ct.getLocation().compareTo(SHADOW_CELL) == 0);
}
}
@Override
protected void configure() {
bind(ITestContext.class).toInstance(testContext);
while (moduleIterator.hasNext()) {
final TckModule module = moduleIterator.next();
module.setTestContext(testContext);
install(module);
}
}
public void onFinish(ITestContext iTestContext) {
Object id;
synchronized (lock) {
id = suites.remove(iTestContext.getName());
for (ITestNGMethod method : iTestContext.getAllTestMethods()) {
testMethodToSuiteMapping.remove(method);
}
}
resultProcessor.completed(id, new TestCompleteEvent(iTestContext.getEndDate().getTime()));
}
/**
* Package private. Used in unit test.
*
* @return UID for the current suite
*/
String getSuiteUid(ITestContext iTestContext) {
String uid;
if (iTestContext.getAttribute(SUITE_UID) != null) {
uid = (String) iTestContext.getAttribute(SUITE_UID);
} else {
uid = UUID.randomUUID().toString();
iTestContext.setAttribute(SUITE_UID, uid);
}
return uid;
}
@Test
public void shouldSendQueryParameters(ITestContext ctx) throws Exception {
final DefaultHttpJsonRequest request =
new DefaultHttpJsonRequest(getUrl(ctx) + "/query-parameters");
final Map<String, String> map =
request
.usePutMethod()
.addQueryParam("param1", "value1")
.addQueryParam("param2", "value2")
.request()
.asProperties();
assertEquals(map, ImmutableMap.of("param1", "value1", "param2", "value2"));
}
@Test(timeOut = 30_000)
public void testCrashAfterCommit(ITestContext context) throws Exception {
PostCommitActions syncPostCommitter =
spy(new HBaseSyncPostCommitter(new NullMetricsProvider(), getCommitTable(context).getClient(), connection));
AbstractTransactionManager tm = (AbstractTransactionManager) newTransactionManager(context, syncPostCommitter);
// The following line emulates a crash after commit that is observed in (*) below
doThrow(new RuntimeException()).when(syncPostCommitter).updateShadowCells(any(HBaseTransaction.class));
Table htable = connection.getTable(TableName.valueOf(TEST_TABLE));
SnapshotFilterImpl snapshotFilter = new SnapshotFilterImpl(new HTableAccessWrapper(htable, htable),
tm.getCommitTableClient());
TTable table = spy(new TTable(htable, snapshotFilter, false));
HBaseTransaction t1 = (HBaseTransaction) tm.begin();
// Test shadow cell are created properly
Put put = new Put(row1);
put.addColumn(family, qualifier, data1);
table.put(t1, put);
try {
tm.commit(t1);
} catch (Exception e) { // (*) crash
// Do nothing
}
assertTrue(CellUtils.hasCell(row1, family, qualifier, t1.getStartTimestamp(), new TTableCellGetterAdapter(table)),
"Cell should be there");
assertFalse(CellUtils.hasShadowCell(row1, family, qualifier, t1.getStartTimestamp(), new TTableCellGetterAdapter(table)),
"Shadow cell should not be there");
HBaseCellId hBaseCellId = new HBaseCellId(table, row1, family, qualifier, t1.getStartTimestamp());
HBaseTransactionClient hbaseTm = (HBaseTransactionClient) newTransactionManager(context);
assertTrue(snapshotFilter.isCommitted(hBaseCellId, 0, false), "row1 should be committed");
}
/**
* Before method.
*
* @param testContext the test context
* @throws Exception the exception
*/
@BeforeMethod(alwaysRun = true)
protected final void contextInitBeforeMethod(ITestContext testContext) throws Exception {
Map<String,String> parameters = testContext.getSuite().getXmlSuite().getAllParameters();
if (testContext.getSuite().getParallel().equalsIgnoreCase("methods")) {
STEVIA_TEST_BASE_LOG.warn("***************************************************************************************");
STEVIA_TEST_BASE_LOG.warn("*** Driver initialisation phase, current parallel level is @BeforeMethod[PANICMODE] ***");
STEVIA_TEST_BASE_LOG.warn("***************************************************************************************");
initializeStevia(parameters);
}
}
@DataProvider(name = "SingleDataProvider")
public Object[][] createDataSingleThread(final ITestNGMethod testMethod,
ITestContext context) {
Annotation[] annotations = testMethod.getConstructorOrMethod().getMethod().getDeclaredAnnotations();
Object[][] objects = DataProviderFactory.getDataProvider(annotations, context, testMethod);
return objects;
}
@DataProvider(name="dp-with-testngmethod-contex")
public Object[][] dataProviderForBDD(ITestNGMethod method, ITestContext contex){
Map<Object, Object> m = Maps.newHashMap();
m.put("method", method.getMethodName());
m.put("contex", contex.getName());
return new Object[][]{{m}};
}