How to use Annotation Type Categories.ExcludeCategory class of org.junit.experimental.categories package

Best junit code snippet using org.junit.experimental.categories.Annotation Type Categories.ExcludeCategory

Run junit automation tests on LambdaTest cloud grid

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

copy
1package firebats.test.junit;
2
3import java.io.IOException;
4import java.lang.annotation.ElementType;
5import java.lang.annotation.Inherited;
6import java.lang.annotation.Retention;
7import java.lang.annotation.RetentionPolicy;
8import java.lang.annotation.Target;
9
10import javax.annotation.Nullable;
11
12import org.junit.experimental.categories.Categories.CategoryFilter;
13import org.junit.experimental.categories.Categories.ExcludeCategory;
14import org.junit.experimental.categories.Categories.IncludeCategory;
15import org.junit.runner.Description;
16import org.junit.runner.manipulation.Filter;
17import org.junit.runner.manipulation.NoTestsRemainException;
18import org.junit.runners.model.InitializationError;
19import org.junit.runners.model.RunnerBuilder;
20
21import com.google.common.base.Function;
22import com.google.common.base.Predicate;
23import com.google.common.collect.FluentIterable;
24import com.google.common.collect.ImmutableSet;
25import com.google.common.collect.Iterables;
26import com.google.common.reflect.ClassPath;
27import com.google.common.reflect.ClassPath.ClassInfo;
28
29/**
30 * 自动classpath查找Suite实现
31 * 
32 * 范例:
33 * @RunWith(ClassPathSuite.class)
34 * @IncludeCategory(SlowTestCategory.class)
35 * @SuiteClasses(packageName="junit4")
36 * public class AllSlowTests {
37 * }
38 * 
39 * public interface SlowTestCategory {}
40 * 
41 * @Category(SlowTestCategory.class)
42 * public class ASlowTest {
43 *   	@Test	public void test() {}
44 * }
45 */
46public class ClassPathScanSuite extends org.junit.runners.Suite {
47    /**
48     * The <code>SuiteClasses</code> annotation specifies the classes to be run when a class
49     * annotated with <code>@RunWith(Suite.class)</code> is run.
50     */
51    @Retention(RetentionPolicy.RUNTIME)
52    @Target(ElementType.TYPE)
53    @Inherited
54    public @interface SuiteClasses {
55        /**
56         * @return the classes to be run
57         */
58        public String packageName();
59    }
60
61	static public ClassPath classpath;
62	static {
63		try {
64			classpath = ClassPath.from(Thread.currentThread().getContextClassLoader());
65		} catch (IOException e) {
66			throw new RuntimeException(e);
67		}
68	}
69
70
71	/**
72	 * for junit invoke.
73	 */
74	public ClassPathScanSuite(Class<?> clazz, RunnerBuilder builder)
75			throws InitializationError {
76		super(builder, clazz, Iterables.toArray(getClasses(getPackageName(clazz), getIncludedCategory(clazz)), Class.class));
77		CategoryFilter filter=new CategoryFilter(getIncludedCategory(clazz),getExcludedCategory(clazz));
78 		try {
79 	 		filter(new ClassPathCategoryFilter(getPackageName(clazz),filter));
80		} catch (NoTestsRemainException e) {
81            throw new InitializationError(e);
82		}
83	}
84	
85	public static class ClassPathCategoryFilter extends Filter {
86  		private String packageName;
87  		CategoryFilter filter;
88 		public ClassPathCategoryFilter(String packageName,CategoryFilter filter) {
89			this.filter=filter;
90 			this.packageName=packageName;
91  		}
92		@Override
93		public boolean shouldRun(Description description) {
94			if(description!=null&&description.getTestClass()!=null){
95				return description.getTestClass().getPackage().getName().startsWith(packageName)
96						&&filter.shouldRun(description);
97			}
98 			return false;
99		}
100		@Override
101		public String describe() { 
102            return filter.describe() +" ,packages " +packageName;
103		}
104	}
105
106	private static ImmutableSet<Class<?>> getClasses(String packageName,
107			final Class<?> annotationClass) {
108		return FluentIterable
109				.from(classpath.getTopLevelClassesRecursive(packageName))
110				.filter(new Predicate<ClassPath.ClassInfo>() {
111					@Override
112					public boolean apply(ClassInfo input) {
113						return true;
114					}
115				})
116				.transform(new Function<ClassInfo, Class<?>>() {
117					@Override
118					@Nullable
119					public Class<?> apply(@Nullable ClassInfo input) {
120						try {
121							return Class.forName(input.getName());
122						} catch (ClassNotFoundException e) {
123							throw new RuntimeException(e);
124						}
125					}
126				})
127				.filter(new Predicate<Class<?>>() {
128					@Override
129					public boolean apply(@Nullable Class<?> input) {
130						return true;
131					}
132				}).toSet();
133	}
134	
135	private static Class<?> getExcludedCategory(Class<?> klass) {
136		ExcludeCategory annotation= klass.getAnnotation(ExcludeCategory.class);
137		return annotation == null ? null : annotation.value();
138	}
139	private static Class<?> getIncludedCategory(Class<?> klass) {
140		IncludeCategory annotation= klass.getAnnotation(IncludeCategory.class);
141		return annotation == null ? null : annotation.value();
142	}
143	private static String getPackageName(Class<?> klass) {
144		SuiteClasses annotation= klass.getAnnotation(SuiteClasses.class);
145		return annotation == null ? "no package name" : annotation.packageName();
146	}
147}
148
Full Screen
copy
1package helpers.suite;
2
3
4import config.TestHttpAppConfig;
5import helpers.category.ServletContainerTest;
6import helpers.category.UnitTests;
7import net.tokensmith.authorization.http.controller.RSAPublicKeyResourceTest;
8import net.tokensmith.authorization.http.controller.RSAPublicKeysResourceTest;
9import net.tokensmith.authorization.http.controller.RegisterResourceTest;
10import net.tokensmith.authorization.http.controller.WelcomeResourceTest;
11import net.tokensmith.authorization.http.controller.authorization.AuthorizationResourceTest;
12import net.tokensmith.authorization.http.controller.authorization.OAuth2CodeResourceTest;
13import net.tokensmith.authorization.http.controller.authorization.OAuth2ImplicitResourceTest;
14import net.tokensmith.authorization.http.controller.authorization.OpenIdCodeResourceTest;
15import net.tokensmith.authorization.http.controller.authorization.OpenIdImplicitIdentityResourceTest;
16import net.tokensmith.authorization.http.controller.authorization.OpenIdImplicitResourceTest;
17import net.tokensmith.authorization.http.controller.resource.ForgotPasswordResourceTest;
18import net.tokensmith.authorization.http.controller.resource.UpdatePasswordResourceTest;
19import net.tokensmith.authorization.http.controller.resource.api.publik.HealthResourceTest;
20import net.tokensmith.authorization.http.controller.resource.api.site.RestAddressResourceTest;
21import net.tokensmith.authorization.http.controller.resource.api.site.RestProfileResourceTest;
22import net.tokensmith.authorization.http.controller.resource.html.authorization.AuthorizationResource;
23import net.tokensmith.authorization.http.controller.token.TokenResourceRefreshTokenTest;
24import net.tokensmith.authorization.http.controller.token.TokenResourceResponseTypeCodeTest;
25import net.tokensmith.authorization.http.controller.token.TokenResourceResponseTypePasswordTest;
26import net.tokensmith.authorization.http.controller.userInfo.UserInfoResourceOAuth2CodeTest;
27import net.tokensmith.authorization.http.controller.userInfo.UserInfoResourceOAuth2PasswordTest;
28import net.tokensmith.authorization.http.controller.userInfo.UserInfoResourceOAuth2RefreshTest;
29import net.tokensmith.authorization.http.controller.userInfo.UserInfoResourceOAuth2TokenTest;
30import net.tokensmith.authorization.http.controller.userInfo.UserInfoResourceOpenIdCodeTest;
31import net.tokensmith.authorization.http.controller.userInfo.UserInfoResourceOpenIdPasswordTest;
32import net.tokensmith.authorization.http.controller.userInfo.UserInfoResourceOpenIdRefreshTest;
33import net.tokensmith.authorization.http.controller.userInfo.UserInfoResourceOpenIdTokenAndIdTokenTest;
34import net.tokensmith.authorization.http.controller.userInfo.UserInfoResourceTest;
35import net.tokensmith.otter.config.OtterAppFactory;
36import net.tokensmith.otter.server.HttpServerConfig;
37import net.tokensmith.otter.server.container.ServletContainer;
38import net.tokensmith.otter.server.container.ServletContainerFactory;
39import org.asynchttpclient.AsyncHttpClient;
40import org.asynchttpclient.DefaultAsyncHttpClientConfig;
41import org.junit.AfterClass;
42import org.junit.BeforeClass;
43import org.junit.experimental.categories.Categories;
44import org.junit.runner.RunWith;
45import org.junit.runners.Suite;
46import org.springframework.context.annotation.AnnotationConfigApplicationContext;
47
48import java.util.Arrays;
49import java.util.List;
50
51import static org.asynchttpclient.Dsl.asyncHttpClient;
52
53
54@RunWith(Categories.class)
55@Categories.IncludeCategory(ServletContainerTest.class)
56@Categories.ExcludeCategory(UnitTests.class)
57@Suite.SuiteClasses({
58        AuthorizationResourceTest.class,
59        OAuth2CodeResourceTest.class,
60        OAuth2ImplicitResourceTest.class,
61        OpenIdCodeResourceTest.class,
62        OpenIdImplicitIdentityResourceTest.class,
63        OpenIdImplicitResourceTest.class,
64        TokenResourceResponseTypeCodeTest.class,
65        TokenResourceResponseTypePasswordTest.class,
66        TokenResourceRefreshTokenTest.class,
67        UserInfoResourceTest.class,
68        UserInfoResourceOpenIdPasswordTest.class,
69        UserInfoResourceOpenIdCodeTest.class,
70        UserInfoResourceOpenIdTokenAndIdTokenTest.class,
71        UserInfoResourceOpenIdRefreshTest.class,
72        UserInfoResourceOAuth2CodeTest.class,
73        UserInfoResourceOAuth2PasswordTest.class,
74        UserInfoResourceOAuth2RefreshTest.class,
75        UserInfoResourceOAuth2TokenTest.class,
76        RSAPublicKeysResourceTest.class,
77        RSAPublicKeyResourceTest.class,
78        RegisterResourceTest.class,
79        WelcomeResourceTest.class,
80        ForgotPasswordResourceTest.class,
81        UpdatePasswordResourceTest.class,
82        RestProfileResourceTest.class,
83        RestAddressResourceTest.class,
84        HealthResourceTest.class
85})
86public class IntegrationTestSuite {
87
88    private static OtterAppFactory otterTestAppFactory;
89    private static ServletContainerFactory servletContainerFactory;
90    private static ServletContainer server;
91    private static AsyncHttpClient httpClient;
92    private static String DOCUMENT_ROOT = "/";
93    private static int RANDOM_PORT = 0;
94    private static String REQUEST_LOG = "logs/jetty/jetty-test-yyyy_mm_dd.request.log";
95
96    private static AnnotationConfigApplicationContext context;
97
98    private static void configureAndStartServletContainer() throws Exception {
99
100        otterTestAppFactory = new OtterAppFactory();
101        servletContainerFactory = otterTestAppFactory.servletContainerFactory();
102
103        List<String> gzipMimeTypes = Arrays.asList(
104                "text/html", "text/plain", "text/xml",
105                "text/css", "application/javascript", "text/javascript",
106                "application/json");
107
108
109        HttpServerConfig config = new HttpServerConfig.Builder()
110                .documentRoot(DOCUMENT_ROOT)
111                .port(RANDOM_PORT)
112                .requestLog(REQUEST_LOG)
113                .clazz(AuthorizationResource.class)
114                .gzipMimeTypes(gzipMimeTypes)
115                .build();
116
117        server = servletContainerFactory.makeServletContainer(config);
118
119        server.start();
120
121        httpClient = asyncHttpClient(new DefaultAsyncHttpClientConfig.Builder().setCookieStore(null).build());
122    }
123
124    /**
125     * Starts a servlet container and a spring container.
126     *
127     * @throws Exception
128     */
129    @BeforeClass
130    public static void beforeClass() throws Exception {
131        configureAndStartServletContainer();
132        context = new AnnotationConfigApplicationContext();
133        context.register(TestHttpAppConfig.class);
134        context.refresh();
135    }
136
137    /**
138     * Stops a servlet container
139     *
140     * @throws Exception
141     */
142    @AfterClass
143    public static void afterClass() throws Exception {
144        server.stop();
145    }
146
147    public static ServletContainer getServer() {
148        return server;
149    }
150
151    public static void setServer(ServletContainer server) {
152        IntegrationTestSuite.server = server;
153    }
154
155    public static AsyncHttpClient getHttpClient() {
156        return httpClient;
157    }
158
159    public static void setHttpClient(AsyncHttpClient httpClient) {
160        IntegrationTestSuite.httpClient = httpClient;
161    }
162
163    public static AnnotationConfigApplicationContext getContext() {
164        return context;
165    }
166}
167
Full Screen
copy
1package org.jboss.tools.ui.bot.ext;
2
3import java.awt.AWTException;
4import java.io.File;
5import java.io.IOException;
6import java.lang.reflect.Method;
7import java.lang.reflect.Modifier;
8import java.util.ArrayList;
9import java.util.Arrays;
10import java.util.Collections;
11import java.util.HashSet;
12import java.util.List;
13import java.util.Map.Entry;
14import java.util.Set;
15import java.util.TreeSet;
16
17import org.apache.log4j.Logger;
18import org.eclipse.swtbot.swt.finder.junit.ScreenshotCaptureListener;
19import org.jboss.tools.test.util.ScreenRecorderExt;
20import org.jboss.tools.ui.bot.ext.config.Annotations.Require;
21import org.jboss.tools.ui.bot.ext.config.TestConfiguration;
22import org.jboss.tools.ui.bot.ext.config.TestConfigurator;
23import org.jboss.tools.ui.bot.ext.config.requirement.RequirementBase;
24import org.junit.Test;
25import org.junit.experimental.categories.Categories.ExcludeCategory;
26import org.junit.experimental.categories.Categories.IncludeCategory;
27import org.junit.experimental.categories.Category;
28import org.junit.runner.Description;
29import org.junit.runner.Runner;
30import org.junit.runner.manipulation.Filter;
31import org.junit.runner.manipulation.NoTestsRemainException;
32import org.junit.runner.notification.RunListener;
33import org.junit.runner.notification.RunNotifier;
34import org.junit.runners.BlockJUnit4ClassRunner;
35import org.junit.runners.Suite;
36import org.junit.runners.model.FrameworkMethod;
37import org.junit.runners.model.InitializationError;
38import org.junit.runners.model.RunnerBuilder;
39import org.junit.runners.model.Statement;
40
41/**
42 * JUnit4 requirement aware testsuite runner. If suite class is annotated by @
43 * RunWith({@link RequirementAwareSuite}) class, test classes can have
44 * {@link Require} annotations
45 * 
46 * @author lzoubek@redhat.com
47 */
48public class RequirementAwareSuite extends Suite {
49  private static boolean runManageBlockingWindow = true;
50  private static ScreenRecorderExt screenRecorderExt = null;
51	// we have one global instance of cleanup listener
52	final static DoAfterAllTestsRunListener cleanUp = new DoAfterAllTestsRunListener();
53
54	final Filter categoryFilter;
55
56	public static class CategoryFilter extends Filter {
57		public static CategoryFilter include(Class<?> categoryType) {
58			return new CategoryFilter(categoryType, null);
59		}
60
61		private final Class<?> fIncluded;
62		private final Class<?> fExcluded;
63
64		public CategoryFilter(Class<?> includedCategory,
65				Class<?> excludedCategory) {
66			fIncluded = includedCategory;
67			fExcluded = excludedCategory;
68		}
69
70		@Override
71		public String describe() {
72			return "category " + fIncluded;
73		}
74
75		@Override
76		public boolean shouldRun(Description description) {
77			if (hasCorrectCategoryAnnotation(description))
78				return true;
79			for (Description each : description.getChildren())
80				if (shouldRun(each))
81					return true;
82			return false;
83		}
84
85		private boolean hasCorrectCategoryAnnotation(Description description) {
86			List<Class<?>> categories = categories(description);
87			if (categories.isEmpty())
88				return fIncluded == null;
89			for (Class<?> each : categories)
90				if (fExcluded != null && fExcluded.isAssignableFrom(each))
91					return false;
92			for (Class<?> each : categories)
93				if (fIncluded == null || fIncluded.isAssignableFrom(each))
94					return true;
95			return false;
96		}
97
98		private List<Class<?>> categories(Description description) {
99			ArrayList<Class<?>> categories = new ArrayList<Class<?>>();
100			categories.addAll(Arrays.asList(directCategories(description)));
101			// categories.addAll(Arrays.asList(directCategories(parentDescription(description))));
102			return categories;
103		}
104
105		private Description parentDescription(Description description) {
106			// TODO: how heavy are we cringing?
107			return Description.createSuiteDescription(description
108					.getTestClass());
109		}
110
111		private Class<?>[] directCategories(Description description) {
112			Category annotation = description.getAnnotation(Category.class);
113			if (annotation == null)
114				return new Class<?>[0];
115			return annotation.value();
116		}
117	}
118
119	class ReqAwareClassRunner extends BlockJUnit4ClassRunner {
120		private final TestConfiguration config;
121		private final List<RequirementBase> requirements;
122
123		public ReqAwareClassRunner(Class<?> klass,
124				List<RequirementBase> requirements, TestConfiguration config)
125				throws InitializationError {
126			super(klass);
127			this.requirements = requirements;
128			this.config = config;
129
130			try {
131				if (categoryFilter != null){
132					filter(categoryFilter);					
133				}
134			} catch (NoTestsRemainException e) {
135				// TODO Auto-generated catch block
136				throw new InitializationError(e);
137			}
138
139		}
140		
141
142		public List<RequirementBase> getRequirements() {
143			return Collections.unmodifiableList(this.requirements);
144		}
145		
146		@Override
147		protected List<FrameworkMethod> computeTestMethods() {
148			List<FrameworkMethod> testMethods = new ArrayList<FrameworkMethod>();			
149			for (Method mm : getTestClass().getJavaClass().getMethods()) {
150				if (mm.getAnnotation(Test.class)!=null 
151						||
152						(mm.getName().startsWith("test") 
153						&& !Modifier.isStatic(mm.getModifiers())
154						&& mm.getParameterTypes().length==0
155						&& Void.TYPE.equals(mm.getReturnType())
156						)) {
157					testMethods.add(new FrameworkMethod(mm));
158				}
159			}
160			for (FrameworkMethod method : testMethods) {
161				method.getAnnotation(Category.class);
162			}
163			return testMethods;
164		}
165		
166
167		@Override
168		public void run(RunNotifier notifier) {
169			// planned test counter must know about all tests (methods) within a
170			// class
171			cleanUp.incrPlanned(getChildren().size() - 1);
172			// ensure that we have exactly 1 cleanup listener registered
173			notifier.removeListener(cleanUp);
174			notifier.addListener(cleanUp);
175			// adding ability to create screen shot (taken from
176			// SWTBotJunit4ClassRunner)
177			RunListener failureSpy = new ScreenshotCaptureListener();
178			notifier.removeListener(failureSpy);
179			notifier.addListener(failureSpy);
180			try {
181				super.run(notifier);
182			} finally {
183        if (System.getProperty("swt.bot.test.record.screencast","false").equalsIgnoreCase("true")){
184		      RequirementAwareSuite.stopScreenRecorder();
185		    }
186				notifier.removeListener(failureSpy);
187			}
188		}
189
190		@Override
191		protected String testName(FrameworkMethod method) {
192			return config.getPropName() + " - " + method.getName();
193		}
194
195		@Override
196		protected Statement withBeforeClasses(Statement statement) {
197		  if (System.getProperty("swt.bot.test.record.screencast","false").equalsIgnoreCase("true")){
198		    RequirementAwareSuite.startScreenRecorder(getTestClass().getJavaClass().getSimpleName());
199		  }
200		  
201		  MacSpecifics.setupToolkit();
202		  
203		  if (RequirementAwareSuite.runManageBlockingWindow){
204		    SWTJBTExt.manageBlockingWidows(false, false);
205		    RequirementAwareSuite.runManageBlockingWindow = false;
206		  }
207		  
208		  MacSpecifics.setupJava();
209		  
210			if (!this.config.equals(TestConfigurator.currentConfig)) {
211				TestConfigurator.currentConfig = this.config;
212			}
213			log.info("Fullfilling requirements before test "
214					+ getTestClass().getJavaClass());
215
216			try {
217				for (RequirementBase r : requirements) {
218					r.fulfill();
219				}
220			} catch (Exception e) {
221				log.error("Fulfilling failed", e);
222			}
223			log.info("Done");
224
225
226			return super.withBeforeClasses(statement);
227		}
228	}
229	
230
231	private static final Logger log = Logger
232			.getLogger(RequirementAwareSuite.class);
233
234	private class RequirementAwareRunnerBuilder extends RunnerBuilder {
235		private final TestConfiguration config;
236
237		public RequirementAwareRunnerBuilder(TestConfiguration config) {
238			this.config = config;
239		}
240
241		@Override
242		public Runner runnerForClass(Class<?> klass) throws Throwable {
243			if (!this.config.equals(TestConfigurator.currentConfig)) {
244				TestConfigurator.currentConfig = this.config;
245			}
246			log.info("class " + klass.getCanonicalName());
247			List<RequirementBase> reqs = TestConfigurator
248					.getClassRequirements(klass);
249			if (reqs != null) {
250				if (cleanUp.isClassPlanned(klass)) {
251					if (TestConfigurator.isRequiresRunOnce(klass)) {
252						// class is already scheduled to run and contains
253						// annotation runOnce
254						log.info("runOnce=true, class already planned");
255						log.info("Skipped");
256						return null;
257					}
258					if (!TestConfigurator.isRequiresAnyRuntime(klass)) {
259						// class is scheduled and does not require any runtime, thus
260						// no need to run it against other configuration
261						log.info("no runtimes required + class already planned");
262						log.info("Skipped");
263						return null;
264					}
265				}
266				log.info("OK");
267				// increment number of tests planned to run by 1 (class contains
268				// at least 1 test method)
269				cleanUp.incrPlanned();
270				cleanUp.addClass(klass);
271				return new ReqAwareClassRunner(klass, reqs, config);
272			}
273			log.info("Skipped");
274			cleanUp.addSkippedClass(klass);
275			return null;
276		}
277
278	}
279
280	/**
281	 * listener which listens to test runs, does some cleanup after all tests
282	 * have run it also holds set of all classes which run (usefull for runOnce
283	 * annotation)
284	 * 
285	 * @author lzoubek
286	 * 
287	 */
288	static class DoAfterAllTestsRunListener extends RunListener {
289		// As we can run more suites at once, we need to count tests which are
290		// planned to run
291		// and the ones which already passed (or failed), perform cleanups when
292		// the last one finishes
293		private int testsAboutToRun = 0;
294		private int testsFinished = 0;
295
296		public void incrPlanned() {
297			testsAboutToRun += 1;
298		}
299
300		/**
301		 * adds class to the list of skipped classes
302		 * 
303		 * @param klass
304		 */
305		public void addSkippedClass(Class<?> klass) {
306			skippedClasses.add(klass.getName());
307
308		}
309
310		public void incrPlanned(int amount) {
311			testsAboutToRun += amount;
312		}
313
314		public void incrFinished() {
315			testsFinished += 1;
316		}
317
318		public int getPlanned() {
319			return testsAboutToRun;
320		}
321
322		public int getFinished() {
323			return testsFinished;
324		}
325
326		private Set<String> classes = new HashSet<String>();
327
328		/**
329		 * adds class to runList - as it is planned to run
330		 * 
331		 * @param klass
332		 */
333		public void addClass(Class<?> klass) {
334			classes.add(klass.getName());
335		}
336
337		public boolean isClassPlanned(Class<?> klass) {
338			return classes.contains(klass.getName());
339		}
340
341		/**
342		 * set of classes that has been skipped (annotations not met etc)
343		 */
344		private Set<String> skippedClasses = new TreeSet<String>();
345
346		private void reportSkippedClasses() {
347			Set<String> finalized = new TreeSet<String>();
348			// lets figure out if a class that has been at least once skipped
349			// was not planned
350			for (String clazz : skippedClasses) {
351				if (!classes.contains(clazz)) {
352					finalized.add(clazz);
353				}
354			}
355			if (!finalized.isEmpty()) {
356				log.info("Several test classes have been skipped, see head of log to figure out why it happened");
357				for (String clazz : finalized) {
358					log.info(" * " + clazz);
359				}
360			}
361		}
362
363		@Override
364		public void testFinished(Description description) throws Exception {
365			incrFinished();
366			log.info("Finished test : " + description.getDisplayName());
367			log.info("Finished tests : " + getFinished() + "/" + getPlanned());
368			if (getFinished() >= getPlanned()) {
369				log.info("All tests finished, performing cleanup requirements ");
370				try {
371					RequirementBase.createStopServer().fulfill();
372					RequirementBase.createStopDBServer().fulfill();
373
374					log.info("All cleanup requirements performed");
375				} catch (Exception ex) {
376					log.error("Unable to fulfill cleanup requirements", ex);
377				}
378				reportSkippedClasses();
379			}
380			super.testFinished(description);
381		}
382	}
383
384	private final ArrayList<Runner> runners = new ArrayList<Runner>();
385
386	/**
387	 * Only called reflectively. Do not use programmatically.
388	 */
389
390	/**
391	 * Called reflectively on classes annotated with
392	 * <code>@RunWith(RequirementAwareSuite.class)</code>
393	 * 
394	 * @param klass
395	 *            the root class
396	 */
397	public RequirementAwareSuite(Class<?> klass) throws Throwable {
398		super(klass, Collections.<Runner> emptyList());
399		log.info("Loading test configurations");
400
401		for (Entry<Object, Object> entry : TestConfigurator.multiProperties
402				.entrySet()) {
403			try {
404				TestConfiguration config = new TestConfiguration(entry.getKey()
405						.toString(), entry.getValue().toString());
406				String suiteName = config.getPropName() + " - "
407						+ klass.getCanonicalName();
408				log.info("Determine whether test classes meet configuration");
409				NamedSuite suite = new NamedSuite(klass,new RequirementAwareRunnerBuilder(config), suiteName);
410				// when no class mathces given config, do not init it 
411				if (suite.getRunnerCount()>0) {
412					log.info("Configuration '"+config.getPropName()+"' initialized with "+suite.getRunnerCount()+" runners.");
413					runners.add(suite);
414					config.initialize();
415				}
416				else {
417					log.info("Configuration '"+config.getPropName()+"' skipped, no runners");				
418				}
419			} catch (Exception ex) {
420				log.error("Error loading test configuration", ex);
421				throw ex;
422			}
423		}
424
425		try {
426			categoryFilter = new CategoryFilter(getIncludedCategory(klass),
427					getExcludedCategory(klass));
428			filter(categoryFilter);
429
430		} catch (NoTestsRemainException e) {
431			throw new InitializationError(e);
432		}
433	}
434
435	@Override
436	protected List<Runner> getChildren() {
437		return runners;
438	}
439
440	public class NamedSuite extends Suite {
441		private final String suiteName;
442
443		public NamedSuite(Class<?> klass, RunnerBuilder builder, String name)
444				throws InitializationError {
445			super(klass, builder);
446			this.suiteName = name;
447		}
448		/**
449		 * gets count of test runners within this suite
450		 * @return

451		 */
452		public int getRunnerCount() {
453			return getChildren().size();
454		}
455
456		@Override
457		protected String getName() {
458			return suiteName;
459		}
460	}
461
462	private Class<?> getIncludedCategory(Class<?> klass) {
463		IncludeCategory annotation = klass.getAnnotation(IncludeCategory.class);
464		return annotation == null ? null : annotation.value();
465	}
466
467	private Class<?> getExcludedCategory(Class<?> klass) {
468		ExcludeCategory annotation = klass.getAnnotation(ExcludeCategory.class);
469		return annotation == null ? null : annotation.value();
470	}
471	/**
472	 * Starts Screen Recorder
473	 */
474  private static void startScreenRecorder(String className) {
475    if (screenRecorderExt == null) {
476      try {
477        screenRecorderExt = new ScreenRecorderExt();
478      } catch (IOException ioe) {
479        throw new RuntimeException("Unable to initialize Screen Recorder.", ioe);
480      } catch (AWTException awte) {
481        throw new RuntimeException("Unable to initialize Screen Recorder.", awte);
482      }
483    }
484    if (screenRecorderExt != null) {
485      if (screenRecorderExt.isState(ScreenRecorderExt.STATE_DONE)) {
486        try {
487          File screenCastDir = new File ("screencasts");
488          if (!screenCastDir.exists()){
489            screenCastDir.mkdir();
490          }
491          final String fileName = "screencasts" + File.separator + className;
492          log.info("Starting Screen Recorder. Saving Screen Cast to file: " + fileName);
493          screenRecorderExt.start(fileName);
494        } catch (IOException ioe) {
495          throw new RuntimeException("Unable to start Screen Recorder.", ioe);
496        }
497      } else {
498        throw new RuntimeException(
499            "Unable to start Screen Recorder.\nScreen Recorder is not in state DONE.");
500      }
501    } else {
502      log.error("Screen Recorder was not properly initilized");
503    }
504  }
505	/**
506	 * Stops Screen Recorder
507	 */
508  private static void stopScreenRecorder(){
509    if (screenRecorderExt != null){
510      if (screenRecorderExt.isState(ScreenRecorderExt.STATE_RECORDING)){
511        try {
512          screenRecorderExt.stop();
513          log.info("Screen Recorder stopped.");
514        } catch (IOException ioe) {
515          throw 
516            new RuntimeException("Unable to stop Screen Recorder." , ioe);
517        }
518      }
519      else{
520        throw 
521          new RuntimeException("Unable to stop Screen Recorder.\nScreen Recorder is no in state RECORDING.");
522      }
523    }
524    else {
525      throw 
526        new RuntimeException("Unable to stop Screen Recorder.\nScreen Recorder was not properly initilized");
527    }
528  }
529}
530
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

...Most popular Stackoverflow questions on Annotation-Type-Categories.ExcludeCategory

    No relevant questions found for this class 😞

Most used methods in Annotation-Type-Categories.ExcludeCategory

    No methods found for this class 😞

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)