Best SeLion code snippet using com.paypal.selion.configuration.ListenerManager.isCurrentMethodSkipped
Source:SeleniumGridListener.java
...76 @Override77 public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {78 logger.entering(new Object[] { method, testResult });79 try {80 if (ListenerManager.isCurrentMethodSkipped(this)) {81 logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG);82 return;83 }84 // For non-session sharing, we only allow our annotation(s) on @Test methods.85 // When this condition is true, we allow the session be created.86 if (!method.isTestMethod() && !isSeLionAnnotatedTestClass(method)) {87 return;88 }89 // For session sharing, we only allow our annotation on the class.90 // In this case the session can only be created in the @Test with the highest priority (first test, smallest91 // number) or in a @BeforeClass92 if (isSeLionAnnotatedTestClass(method)) {93 if (!isValidBeforeCondition(method)) {94 return;95 }96 // For session sharing, we need to ensure @Test methods are priority based.97 if (method.isTestMethod()) {98 // we need to ensure each @Test method is annotated99 if (isLowPriority(method)) {100 // For session sharing tests, Need to create new session only for Test (Web or Mobile) with101 // highest priority (first test, smallest number) in the class.102 testSessionSharingRules(method);103 } else {104 return;105 }106 }107 }108 // Abort if there is already an instance of AbstractTestSession at this point.109 if (Grid.getTestSession() != null) {110 return;111 }112 AbstractTestSession testSession = TestSessionFactory.newInstance(method);113 Grid.getThreadLocalTestSession().set(testSession);114 InvokedMethodInformation methodInfo = TestNGUtils.getInvokedMethodInformation(method, testResult);115 testSession.initializeTestSession(methodInfo);116 if (!(testSession instanceof BasicTestSession)) {117 // BasicTestSession are non selenium tests. So no need to start the Local hub.118 try {119 LocalGridManager.spawnLocalHub(testSession);120 } catch (NoClassDefFoundError e) {121 logger.log(Level.SEVERE, "You are trying to run a local server but are missing Jars. Do you have "122 + "SeLion-Grid and Selenium-Server in your CLASSPATH?", e);123 // No sense in continuing ... SELENIUM_RUN_LOCALLY is a global config property124 System.exit(1); // NOSONAR125 }126 }127 } catch (Exception e) { // NOSONAR128 if (e instanceof RuntimeException) {129 throw e;130 }131 // convert the checked exception into a runtime exception.132 throw new RuntimeException(e.getMessage(), e);133 }134 logger.exiting();135 }136 private boolean isSeLionAnnotatedTestClass(IInvokedMethod method) {137 Class<?> cls = method.getTestMethod().getInstance().getClass();138 final boolean isWebTestClass = cls.getAnnotation(WebTest.class) != null;139 final boolean isMobileTestClass = cls.getAnnotation(MobileTest.class) != null;140 return isMobileTestClass || isWebTestClass;141 }142 private boolean isValidBeforeCondition(IInvokedMethod method) {143 if (method.isTestMethod()) {144 return true;145 }146 return method.getTestMethod().isBeforeClassConfiguration();147 }148 private void testSessionSharingRules(IInvokedMethod method) {149 Test t = method.getTestMethod().getInstance().getClass().getAnnotation(Test.class);150 if (t != null && t.singleThreaded()) {151 if (!isPriorityUnique(method)) {152 throw new IllegalStateException(153 "All the session sharing test methods within the same class should have a unique priority.");154 } else {155 return;156 }157 }158 throw new IllegalStateException(159 "Session sharing test should have a class level @Test annotation with the property singleThreaded = true defined.");160 }161 private boolean isLowPriority(IInvokedMethod method) {162 int low = method.getTestMethod().getPriority();163 for (ITestNGMethod test : method.getTestMethod().getTestClass().getTestMethods()) {164 // ensures all test methods have the @Test annotation. Throw exception if that's not the case165 if (!isAnnotatedWithTest(test.getConstructorOrMethod().getMethod())) {166 throw new IllegalStateException(167 "Session sharing requires all test methods to define a priority via the @Test annotation.");168 }169 if (test.getEnabled() && test.getPriority() < low) {170 return false;171 }172 }173 Test t = method.getTestMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class);174 // If there is an existing session and the test method has a DP then don't create a session175 // For a data driven test method with the first data the session must be created176 // Hence return true if currentInvocationCount is 1 otherwise utilize the same session177 // by returning false178 int currentInvocationCount = method.getTestMethod().getCurrentInvocationCount();179 if (!t.dataProvider().isEmpty()) {180 return currentInvocationCount == 0;181 }182 return true;183 }184 private boolean isHighPriority(IInvokedMethod method) {185 if (!isAnnotatedWithTest(method)) {186 // Abort. There will already be an exception thrown in isLowPriority for this case.187 return true;188 }189 int high = method.getTestMethod().getPriority();190 for (ITestNGMethod test : method.getTestMethod().getTestClass().getTestMethods()) {191 if (test.getEnabled() && test.getPriority() > high) {192 return false;193 }194 }195 Test t = method.getTestMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class);196 // For a test method with a data provider197 if (!(t.dataProvider().isEmpty())) {198 int currentInvocationCount = method.getTestMethod().getCurrentInvocationCount();199 int parameterInvocationCount = method.getTestMethod().getParameterInvocationCount();200 // If the data set from the data provider is exhausted201 // It means its the last method with the data provider- this is the exit condition202 return (currentInvocationCount == parameterInvocationCount);203 }204 return true;205 }206 private boolean isAnnotatedWithTest(IInvokedMethod method) {207 return isAnnotatedWithTest(method.getTestMethod().getConstructorOrMethod().getMethod());208 }209 private boolean isAnnotatedWithTest(Method method) {210 Test t = method.getAnnotation(Test.class);211 return t != null;212 }213 private boolean isPriorityUnique(IInvokedMethod method) {214 // Logic to check priorities of all test methods are unique. This is used in Session Sharing.215 Set<Integer> check = new HashSet<Integer>();216 int length = method.getTestMethod().getTestClass().getTestMethods().length;217 int expectedSize = 0;218 for (int i = 0; i < length; i++) {219 //ignore @Test(enabled = false) methods220 if (!method.getTestMethod().getTestClass().getTestMethods()[i].getEnabled()) {221 continue;222 }223 check.add(method.getTestMethod().getTestClass().getTestMethods()[i].getPriority());224 expectedSize += 1;225 if (check.size() != expectedSize) {226 return false;227 }228 }229 return true;230 }231 /**232 * Executes when test case is finished<br>233 * 234 * Identify if webtest wants to have session open, otherwise close session<br>235 * <b>sample</b><br>236 * @webtest(browser="*firefox", <b>keepSessionOpen = true</b>)<br>237 * Analyzes failure if any238 * 239 * @see org.testng.IInvokedMethodListener#afterInvocation(org.testng.IInvokedMethod, org.testng.ITestResult)240 * 241 */242 @Override243 public void afterInvocation(IInvokedMethod method, ITestResult testResult) {244 logger.entering(new Object[] { method, testResult });245 try {246 if (ListenerManager.isCurrentMethodSkipped(this)) {247 logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG);248 return;249 }250 // Abort at this point, if there is no AbstractTestSession instance.251 if (Grid.getTestSession() == null) {252 return;253 }254 // For non-session sharing, we only allow our annotation(s) on @Test methods.255 // When this condition is true, we allow the session to be closed.256 if (!method.isTestMethod() && !isSeLionAnnotatedTestClass(method)) {257 return;258 }259 // For session sharing, we only allow our annotation on the class.260 // In this case the session can only be closed in the @Test with the lowest priority (last test, biggest261 // number) or in an @AfterClass262 if (isSeLionAnnotatedTestClass(method)) {263 if (!isValidAfterCondition(method)) {264 return;265 }266 if (method.isTestMethod() && hasValidAfterCondition(method)) {267 return;268 }269 if (method.isTestMethod() && !isHighPriority(method)) {270 // For session sharing tests, Need to close session only for Test (Web or Mobile) with highest271 // priority (last test) in the class.272 return;273 }274 }275 // let's attempt to capture a screenshot in case of failure from Selenium or SeLion PageObject276 // or when there was an assertion failure.277 // That way a user can see the how the page looked like when a test failed.278 if (testResult.getStatus() == ITestResult.FAILURE279 && (testResult.getThrowable() instanceof WebDriverException ||280 testResult.getThrowable() instanceof AssertionError)) {281 warnUserOfTestFailures(testResult);282 }283 AbstractTestSession testSession = Grid.getTestSession();284 testSession.closeSession();285 testResult.setAttribute(JsonRuntimeReporterHelper.IS_COMPLETED, true);286 } catch (Exception e) { // NOSONAR287 logger.log(Level.WARNING, "An error occurred while processing afterInvocation: " + e.getMessage(), e);288 }289 logger.exiting();290 }291 private boolean isValidAfterCondition(IInvokedMethod method) {292 return method.isTestMethod() || method.getTestMethod().isAfterClassConfiguration();293 }294 private boolean hasValidAfterCondition(IInvokedMethod method) {295 return method.getTestMethod().getTestClass().getAfterClassMethods().length > 0;296 }297 private void warnUserOfTestFailures(ITestResult testResult) {298 // don't bother if we don't have a session299 if (!Grid.getTestSession().isStarted()) {300 return;301 }302 // don't bother if we don't have a web or mobile test session303 if (!(Grid.getTestSession() instanceof MobileTestSession) &&304 !(Grid.getTestSession() instanceof WebTestSession)) {305 return;306 }307 String errMsg = "";308 if (testResult.getThrowable() != null) {309 errMsg = testResult.getThrowable().getMessage();310 }311 if (StringUtils.isEmpty(errMsg)) {312 errMsg = "Test Failure screenshot";313 }314 SeLionReporter.log(errMsg, true, true);315 logger.info("Please review the test report for the screenshot at the time of failure.");316 }317 /**318 * Initiate config on suite start319 * 320 * @see org.testng.ISuiteListener#onStart(org.testng.ISuite)321 */322 @Override323 public void onStart(ISuite suite) {324 logger.entering(suite);325 if (ListenerManager.isCurrentMethodSkipped(this)) {326 logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG);327 return;328 }329 // Nothing should query for SeLionConfig values before this point.330 Config.initConfig(suite);331 ConfigSummaryData.initConfigSummary();332 ReporterConfigMetadata.initReporterMetadata();333 // Printing the JVM information.334 // This info will help us when it comes to debugging issues on fusion335 // a typical output will be as below336 // 13:42:04.312 INFO - JDK Information: Java HotSpot(TM) 64-Bit Server VM from Oracle Corporation VM ver.337 // 23.7-b01338 RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();339 String jdkInfo = runtime.getVmName() + " from " + runtime.getSpecVendor() + " ver. "340 + System.getProperty("java.version");341 logger.info("JDK Information: " + jdkInfo);342 logger.exiting();343 }344 /**345 * Generates and returns output directory string path346 * 347 * @param base348 * String shows path to the suiteName349 * @param suiteName350 * String suiteName specified by config file351 * @return String - path to output directory for that particular suite352 */353 public static String filterOutputDirectory(String base, String suiteName) {354 logger.entering(new Object[] { base, suiteName });355 int index = base.lastIndexOf(suiteName);356 String outputFolderWithoutName = base.substring(0, index);357 logger.exiting(outputFolderWithoutName + File.separator);358 return outputFolderWithoutName + File.separator;359 }360 /**361 * Closes selenium session when suite finished to run362 * 363 * @see org.testng.ISuiteListener#onFinish(org.testng.ISuite)364 */365 @Override366 public void onFinish(ISuite suite) {367 logger.entering(suite);368 if (ListenerManager.isCurrentMethodSkipped(this)) {369 logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG);370 return;371 }372 LocalGridManager.shutDownHub();373 logger.exiting();374 }375 /**376 * 377 * @see org.testng.ISuiteListener#onFinish(org.testng.ISuite)378 */379 @Override380 public void onFinish(ITestContext context) {381 // Below conditional check needs to be invoked in all TestNG Listener interface implementation.382 // Failing to do so can have un-predictable results.383 if (ListenerManager.isCurrentMethodSkipped(this)) {384 logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG);385 return;386 }387 }388 /**389 * On start each suite initialize config object and report object390 */391 @Override392 public void onStart(ITestContext context) {393 logger.entering(context);394 if (ListenerManager.isCurrentMethodSkipped(this)) {395 logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG);396 return;397 }398 String testName = context.getCurrentXmlTest().getName();399 // initializing the ConfigSummaryData before initializers so that config details can be added.400 ConfigSummaryData.initLocalConfigSummary(testName);401 // We have to ensure that our configuration is the first thing that gets loaded.402 // Our loading mechanism is going to be via listeners. But the problem with TestNG listeners is403 // that the order of loading is never guaranteed. Things become complicated if our downstream consumers404 // want to piggy back on our configuration and want to have their configurations loaded as well.405 // Because of all these issues, we cannot rely on building a config specific listener.406 // So we are relying on the ServiceLoaders in Java to do it for us. The moment we are here, we ensure that407 // not only the SeLion specific configurations are loaded, but all downstream consumer's configurations408 // are loaded as well along with us. So SeLion now becomes the single point of initialization and thus409 // does away with all the inherent setbacks that are associated with TestNG listeners orders.410 invokeInitializersBasedOnPriority(context);411 ConfigManager.printConfiguration(testName);412 ISuite suite = context.getSuite();413 if (!suite.getParallel().equals("false") && logger.isLoggable(Level.FINE)) {414 logger.log(Level.FINE, "Parallel suite execution. Updating SeLion local config for Test, "415 + context.getCurrentXmlTest().getName());416 }417 String base = suite.getOutputDirectory();418 String suiteName = suite.getName();419 String rootFolder = filterOutputDirectory(base, suiteName);420 SeLionReporter.setTestNGOutputFolder(rootFolder);421 SeLionReporter.init();422 logger.exiting();423 }424 @Override425 public void onTestFailedButWithinSuccessPercentage(ITestResult result) {426 // Below conditional check needs to be invoked in all TestNG Listener interface implementation.427 // Failing to do so can have un-predictable results.428 if (ListenerManager.isCurrentMethodSkipped(this)) {429 logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG);430 return;431 }432 }433 @Override434 public void onTestFailure(ITestResult result) {435 // Below conditional check needs to be invoked in all TestNG Listener interface implementation.436 // Failing to do so can have un-predictable results.437 if (ListenerManager.isCurrentMethodSkipped(this)) {438 logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG);439 return;440 }441 }442 @Override443 public void onTestSkipped(ITestResult result) {444 // Below conditional check needs to be invoked in all TestNG Listener interface implementation.445 // Failing to do so can have un-predictable results.446 if (ListenerManager.isCurrentMethodSkipped(this)) {447 logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG);448 return;449 }450 }451 @Override452 public void onTestStart(ITestResult result) {453 // Below conditional check needs to be invoked in all TestNG Listener interface implementation.454 // Failing to do so can have un-predictable results.455 if (ListenerManager.isCurrentMethodSkipped(this)) {456 logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG);457 }458 }459 @Override460 public void onTestSuccess(ITestResult result) {461 // Below conditional check needs to be invoked in all TestNG Listener interface implementation.462 // Failing to do so can have un-predictable results.463 if (ListenerManager.isCurrentMethodSkipped(this)) {464 logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG);465 }466 }467 /**468 * This method facilitates initialization of all configurations from the current project as well as downstream469 * consumers.470 * 471 * @param context472 */473 private void invokeInitializersBasedOnPriority(ITestContext context) {474 ServiceLoader<Initializer> serviceLoader = ServiceLoader.load(Initializer.class);475 List<AbstractConfigInitializer> loader = new ArrayList<AbstractConfigInitializer>();476 for (Initializer l : serviceLoader) {477 loader.add((AbstractConfigInitializer) l);...
isCurrentMethodSkipped
Using AI Code Generation
1package com.paypal.selion.examples.mobile;2import org.testng.Assert;3import org.testng.annotations.Test;4import com.paypal.selion.annotations.WebTest;5import com.paypal.selion.configuration.ListenerManager;6import com.paypal.selion.examples.mobile.SampleMobileTest.MobileTest1;7import com.paypal.selion.platform.mobile.MobileTestListener;8import com.paypal.selion.platform.mobile.UiObject;9import com.paypal.selion.platform.mobile.android.UiAutomatorTest;10import com.paypal.selion.platform.mobile.ios.UiIosTest;11public class SampleMobileTest extends UiIosTest {12 public static class MobileTest1 extends UiAutomatorTest {13 public void testMobileTest1() {14 Assert.assertFalse(ListenerManager.isCurrentMethodSkipped());15 }16 }17 public static class MobileTest2 extends UiIosTest {18 public void testMobileTest2() {19 Assert.assertFalse(ListenerManager.isCurrentMethodSkipped());20 }21 }22 public void testMobileTest3() {23 Assert.assertFalse(ListenerManager.isCurrentMethodSkipped());24 }25 public void testMobileTest4() {26 Assert.assertFalse(ListenerManager.isCurrentMethodSkipped());27 }28 public void testMobileTest5() {29 Assert.assertFalse(ListenerManager.isCurrentMethodSkipped());30 }31 public void testMobileTest6() {32 Assert.assertFalse(ListenerManager.isCurrentMethodSkipped());33 }34 public void testMobileTest7() {35 Assert.assertFalse(ListenerManager.isCurrentMethodSkipped());36 }37 public void testMobileTest8() {38 Assert.assertFalse(ListenerManager.isCurrentMethodSkipped());39 }40 public void testMobileTest9() {41 Assert.assertFalse(ListenerManager.isCurrentMethodSkipped());42 }43 public void testMobileTest10() {44 Assert.assertFalse(ListenerManager.isCurrentMethodSkipped());45 }46 public void testMobileTest11() {47 Assert.assertFalse(ListenerManager.isCurrentMethodSkipped());
isCurrentMethodSkipped
Using AI Code Generation
1import com.paypal.selion.configuration.ListenerManager;2import org.testng.annotations.Test;3public class ListenerManagerTest {4 public void testIsCurrentMethodSkipped() {5 ListenerManager listenerManager = new ListenerManager();6 System.out.println("Is Current Method Skipped: " + listenerManager.isCurrentMethodSkipped());7 }8}
isCurrentMethodSkipped
Using AI Code Generation
1package com.paypal.selion.plugins;2import java.util.ArrayList;3import java.util.List;4import org.testng.ITestContext;5import org.testng.ITestListener;6import org.testng.ITestResult;7import com.paypal.selion.configuration.ListenerManager;8public class SelionTestListener implements ITestListener {9 public void onFinish(ITestContext arg0) {10 }11 public void onStart(ITestContext arg0) {12 }13 public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {14 }15 public void onTestFailure(ITestResult arg0) {16 }17 public void onTestSkipped(ITestResult arg0) {18 }19 public void onTestStart(ITestResult arg0) {20 }21 public void onTestSuccess(ITestResult arg0) {22 }23}24public class SelionTestListener implements ITestListener {25 public void onFinish(ITestContext arg0) {26 }27 public void onStart(ITestContext arg0) {28 }29 public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {30 }31 public void onTestFailure(ITestResult arg0) {32 }33 public void onTestSkipped(ITestResult arg0) {34 }35 public void onTestStart(ITestResult arg0) {36 }37 public void onTestSuccess(ITestResult arg0) {38 }39}40public void afterMethod(ITestResult result) {41 if (result.getStatus() == ITestResult.SUCCESS) {42 }43 if (result.getStatus() == ITestResult.FAIL
isCurrentMethodSkipped
Using AI Code Generation
1public class ListenerManagerTest {2 public void testIsCurrentMethodSkipped() {3 assertFalse(ListenerManager.isCurrentMethodSkipped(new Object() {4 public void testMethod() {5 }6 }.getClass().getEnclosingMethod()));7 assertTrue(ListenerManager.isCurrentMethodSkipped(new Object() {8 public void testMethod() {9 }10 }.getClass().getEnclosingMethod()));11 }12}13package com.paypal.selion.test;14import org.testng.annotations.Test;15import com.paypal.selion.annotations.WebTest;16import com.paypal.selion.configuration.ListenerManager;17import com.paypal.selion.platform.grid.Grid;18import com.paypal.selion.platform.utilities.WebDriverWaitUtils;19public class SkipTest {20 public void testMethod() {
isCurrentMethodSkipped
Using AI Code Generation
1package com.paypal.selion.testcomponents;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.support.ui.ExpectedConditions;4import org.openqa.selenium.support.ui.WebDriverWait;5import org.testng.Assert;6import org.testng.annotations.Test;7import com.paypal.selion.annotations.WebTest;8import com.paypal.selion.configuration.ListenerManager;9import com.paypal.selion.platform.grid.Grid;10import com.paypal.selion.platform.html.Button;11import com.paypal.selion.platform.html.Label;12import com.paypal.selion.platform.html.TextField;13import com.paypal.selion.platform.utilities.WebDriverWaitUtils;14import com.paypal.selion.testcomponents.BasicPageImpl;15public class BasicPageTest extends BasicPageImpl {16 private static final String TEST_PAGE_TITLE = "Test Page";17 public void testPageTitle() {18 if (ListenerManager.isCurrentMethodSkipped()) {19 return;20 }21 Assert.assertEquals(getPageTitle(), TEST_PAGE_TITLE);22 }23 public void testPageUrl() {24 if (ListenerManager.isCurrentMethodSkipped()) {25 return;26 }27 Assert.assertEquals(getPageUrl(), TEST_PAGE_URL);28 }29 public void testPageUrl2() {30 if (ListenerManager.isCurrentMethodSkipped()) {31 return;32 }33 Assert.assertEquals(getPageUrl(), TEST_PAGE_URL2);34 }35 public void testPageTitle2() {36 if (ListenerManager.isCurrentMethodSkipped()) {37 return;38 }39 Assert.assertEquals(getPageTitle(), TEST_PAGE_TITLE);40 }41 public void testPageTitle3() {42 if (ListenerManager.isCurrentMethodSkipped()) {43 return;44 }45 Assert.assertEquals(getPageTitle(), TEST_PAGE_TITLE);46 }47 public void testPageTitle4() {48 if (ListenerManager.isCurrentMethodSkipped()) {49 return;50 }51 Assert.assertEquals(getPageTitle(), TEST_PAGE_TITLE);52 }
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!