private static Runner parallelize(Runner runner) { int nThreads = Integer.getInteger(Constants.NTHREADS, Runtime.getRuntime().availableProcessors()); LOGGER.info("Using " + nThreads + " threads."); if (runner instanceof ParentRunner) { ((ParentRunner<?>) runner).setScheduler(new RunnerScheduler() { private final ExecutorService fService = Executors.newFixedThreadPool(nThreads); @Override public void schedule(Runnable childStatement) { fService.submit(childStatement); } @Override public void finished() { try { fService.shutdown(); fService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { e.printStackTrace(System.err); } } }); } return runner; }
/** * Initializes this runner by initializing {@link #expectedMethods} with the list of methods which are expected to be called. This is then also checked by * {@link #methodBlock(FrameworkMethod)} and allows identifying the first and last methods correctly. */ private void ensureInitialized() { if (expectedMethods == null) { try { final Method getChildrenMethod = ParentRunner.class.getDeclaredMethod("getFilteredChildren"); //$NON-NLS-1$ getChildrenMethod.setAccessible(true); @SuppressWarnings("unchecked") final Collection<FrameworkMethod> testMethods = (Collection<FrameworkMethod>) getChildrenMethod.invoke(this); expectedMethods = ImmutableList.copyOf(Iterables.filter(testMethods, new Predicate<FrameworkMethod>() { @Override public boolean apply(final FrameworkMethod input) { return input.getAnnotation(Ignore.class) == null; } })); currentMethodIndex = 0; // CHECKSTYLE:OFF } catch (Exception e) { // CHECKSTYLE:ON throw new IllegalStateException(e); } } }
public Description getDescription() { Description description = Description.createSuiteDescription(myName, getTestClass().getAnnotations()); try { final Method getFilteredChildrenMethod = ParentRunner.class.getDeclaredMethod("getFilteredChildren", new Class[0]); getFilteredChildrenMethod.setAccessible(true); Collection filteredChildren = (Collection)getFilteredChildrenMethod.invoke(this, new Object[0]); for (Iterator iterator = filteredChildren.iterator(); iterator.hasNext();) { Object child = iterator.next(); description.addChild(describeChild((Runner)child)); } } catch (Exception e) { e.printStackTrace(); } return description; }
public ParentRunner<?> makeLink(Class<? extends ParentRunner<?>> runnerClass, final Class<?> testClass, final CompositeRunner compositeRunner, final ParentRunner<?> nextRunner, boolean isTestStructureProvider) throws InitializationError { ClassPool pool = ClassPool.getDefault(); String newClassName = runnerClass.getName() + (isTestStructureProvider ? "TestStructureProvider" : "ChainLink"); final Class<?> newRunnerCtClass = makeLinkClass(pool, newClassName, runnerClass, isTestStructureProvider); try { return (ParentRunner<?>) new ReflectiveCallable() { @Override protected Object runReflectiveCall() throws Throwable { return newRunnerCtClass.getConstructor(Class.class, CompositeRunner.class, ParentRunner.class) .newInstance(testClass, compositeRunner, nextRunner); } }.run(); } catch (InitializationError e) { throw e; } catch (Throwable throwable) { throw new RuntimeException(throwable); } }
private void buildFeatureElementRunners() { for (CucumberTagStatement cucumberTagStatement : cucumberFeature .getFeatureElements()) { try { ParentRunner<?> featureElementRunner; if (cucumberTagStatement instanceof CucumberScenario) { featureElementRunner = new RestExecutionUnitRunner(runtime, cucumberTagStatement, jUnitReporter, cucumberFeature); } else { featureElementRunner = new RestScenarioOutlineRunner(runtime, (CucumberScenarioOutline) cucumberTagStatement, jUnitReporter, cucumberFeature); } children.add(featureElementRunner); } catch (InitializationError e) { throw new CucumberException("Failed to create scenario runner", e); } } }
private static Runner parallelize(Runner runner) { if (runner instanceof ParentRunner) { ((ParentRunner<?>) runner).setScheduler(new RunnerScheduler() { private final ExecutorService fService = Executors.newCachedThreadPool(); public void schedule(Runnable childStatement) { fService.submit(childStatement); } public void finished() { try { fService.shutdown(); fService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { e.printStackTrace(System.err); } } }); } return runner; }
@Test public void useChildHarvester() throws InitializationError { log = ""; ParentRunner<?> runner = new BlockJUnit4ClassRunner(FruitTest.class); runner.setScheduler(new RunnerScheduler() { public void schedule(Runnable childStatement) { log += "before "; childStatement.run(); log += "after "; } public void finished() { log += "afterAll "; } }); runner.run(new RunNotifier()); assertEquals("before apple after before banana after afterAll ", log); }
@Test public void noBeforeOnClasspath() throws Exception { File libJar = tempFolder.newFile("lib.jar"); try (FileOutputStream fis = new FileOutputStream(libJar); JarOutputStream jos = new JarOutputStream(fis)) { addClassToJar(jos, RunWith.class); addClassToJar(jos, JUnit4.class); addClassToJar(jos, BlockJUnit4ClassRunner.class); addClassToJar(jos, ParentRunner.class); addClassToJar(jos, SuperTest.class); addClassToJar(jos, SuperTest.class.getEnclosingClass()); } compilationHelper .addSourceLines( "Test.java", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "import " + SuperTest.class.getCanonicalName() + ";", "@RunWith(JUnit4.class)", "class Test extends SuperTest {", " @Override public void setUp() {}", "}") .setArgs(Arrays.asList("-cp", libJar.toString())) .doTest(); }
public Description getDescription() { Description description = Description.createSuiteDescription(myName, getTestClass().getAnnotations()); try { final Method getFilteredChildrenMethod = ParentRunner.class.getDeclaredMethod("getFilteredChildren", new Class[0]); getFilteredChildrenMethod.setAccessible(true); List filteredChildren = (List)getFilteredChildrenMethod.invoke(this, new Object[0]); for (int i = 0, filteredChildrenSize = filteredChildren.size(); i < filteredChildrenSize; i++) { Object child = filteredChildren.get(i); description.addChild(describeChild((Runner)child)); } } catch (Exception e) { e.printStackTrace(); } return description; }
@Override protected List getChildren() { try { Method method = ParentRunner.class.getDeclaredMethod("getChildren"); method.setAccessible(true); return (List) method.invoke(oleasterRobolectricRunner); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } return new ArrayList(); }
@Override protected Description describeChild(Object object) { try { Method method = ParentRunner.class.getDeclaredMethod("describeChild", Object.class); method.setAccessible(true); return (Description) method.invoke(oleasterRobolectricRunner, object); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } return Description.EMPTY; }
@Override protected void runChild(Object object, RunNotifier runNotifier) { try { Method method = ParentRunner.class.getDeclaredMethod("runChild", Object.class, RunNotifier.class); method.setAccessible(true); method.invoke(oleasterRobolectricRunner, object, runNotifier); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } }
@Test public void parallelSchedulerTest() throws Throwable { ParallelParameterized parallelParameterized = new ParallelParameterized(FibonacciTest.class); Class<?> clazz = parallelParameterized.getClass(); while (clazz != ParentRunner.class) { clazz = clazz.getSuperclass(); } Field schedulerField = clazz.getDeclaredField("scheduler"); schedulerField.setAccessible(true); assertTrue(schedulerField.get(parallelParameterized) instanceof ParallelScheduler); }
/** * Sets the thread's context class loader to the class loader for the test * class. */ @Override protected void runChild(Runner runner, RunNotifier notifier) { ParentRunner<?> pr = (ParentRunner<?>) runner; // test class runner ClassLoader cl = null; try { cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader( pr.getTestClass().getJavaClass().getClassLoader()); super.runChild(runner, notifier); } finally { Thread.currentThread().setContextClassLoader(cl); } }
/** * Initializes the test filter. * * @param parentRunner * the {@link ParentRunner} to initialize, must not be {@code null} */ public static void initializeFilter(final ParentRunner<?> parentRunner) { try { parentRunner.filter(INSTANCE); } catch (NoTestsRemainException e) { // we ignore the case where no children are left } }
private void applyMethodFilter() throws InitializationError { for (Runner r : getChildren()) { try { if (r instanceof ParentRunner<?>) { ((ParentRunner<?>) r).filter(methodFilter); } } catch (NoTestsRemainException e) { throw new InitializationError(e); } } }
public FrameworkMethodChainLink(FrameworkMethod wrapped, RunNotifier runNotifier, ParentRunner<?> nextRunner) { super(wrapped.getMethod()); this.wrapped = wrapped; this.runNotifier = runNotifier; this.nextRunner = nextRunner; try { this.nextRunnerRunChild = nextRunner.getClass().getDeclaredMethod("runChild", Object.class, RunNotifier.class); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("Could not find runChild method in ParentRunner.", e); } this.nextRunnerRunChild.setAccessible(true); }
private CtMethod makeDescribeChildMethod(Class<? extends ParentRunner<?>> runnerClass, CtClass declaringClass) throws CannotCompileException { String parameterType = getDescribeChildParameterType(runnerClass).getName(); String describeChild = "protected org.junit.runner.Description describeChild(" + parameterType + " child) {\n" + " return flarestar.junit.composite.runner.chain.RunnerChainLinkFactory.invokeDescribeChild(compositeRunner.getStructureProvidingRunner(), child);\n" + "}"; return CtNewMethod.make(describeChild, declaringClass); }
private Class<?> getDescribeChildParameterType(Class<? extends ParentRunner<?>> runnerClass) { while (runnerClass.getSuperclass() != ParentRunner.class) { runnerClass = (Class<? extends ParentRunner<?>>)runnerClass.getSuperclass(); } return (Class<?>) ((ParameterizedType)runnerClass.getGenericSuperclass()).getActualTypeArguments()[0]; }
public static Statement invokeClassBlock(final ParentRunner<?> nextRunner, final RunNotifier notifier) { try { return (Statement)new ReflectiveCallable() { @Override protected Object runReflectiveCall() throws Throwable { Method classBlockMethod = ParentRunner.class.getDeclaredMethod("classBlock", RunNotifier.class); classBlockMethod.setAccessible(true); return classBlockMethod.invoke(nextRunner, notifier); } }.run(); } catch (Throwable throwable) { throw new RuntimeException(throwable); } }
public static List invokeGetChildren(final ParentRunner<?> runner) { try { return (List)new ReflectiveCallable() { @Override protected Object runReflectiveCall() throws Throwable { Method getChildrenMethod = ParentRunner.class.getDeclaredMethod("getChildren"); getChildrenMethod.setAccessible(true); return getChildrenMethod.invoke(runner); } }.run(); } catch (Throwable throwable) { throw new RuntimeException(throwable); } }
public static Description invokeDescribeChild(final ParentRunner<?> runner, final Object child) { try { return (Description) new ReflectiveCallable() { @Override protected Object runReflectiveCall() throws Throwable { Method describeChildMethod = ParentRunner.class.getDeclaredMethod("describeChild", Object.class); describeChildMethod.setAccessible(true); return describeChildMethod.invoke(runner, child); } }.run(); } catch (Throwable throwable) { throw new RuntimeException(throwable); } }
public List<ParentRunner<?>> makeRunnerChain(Class<?> testClass, CompositeRunner compositeRunner) throws InitializationError { List<Class<? extends ParentRunner<?>>> runnerClasses = compositeRunner.getRunnerClasses(); List<ParentRunner<?>> runners = new ArrayList<ParentRunner<?>>(runnerClasses.size()); createRunnerChainLink(testClass, compositeRunner, runners, runnerClasses.iterator(), true); return runners; }
private ParentRunner<?> createRunnerChainLink(Class<?> testClass, CompositeRunner compositeRunner, List<ParentRunner<?>> runners, Iterator<Class<? extends ParentRunner<?>>> iterator, boolean isTestStructureProvider) throws InitializationError { Class<? extends ParentRunner<?>> thisRunnerClass = iterator.next(); ParentRunner<?> nextRunner = null; if (iterator.hasNext()) { nextRunner = createRunnerChainLink(testClass, compositeRunner, runners, iterator, false); } ParentRunner<?> runner = factory.makeLink(thisRunnerClass, testClass, compositeRunner, nextRunner, isTestStructureProvider); runners.add(0, runner); return runner; }
public static ParentRunner<?> makeChain(Class<?> testCaseClass, CompositeRunner runner) { RunnerChainFactory factory = new RunnerChainFactory(); List<ParentRunner<?>> chain; try { chain = factory.makeRunnerChain(testCaseClass, runner); } catch (InitializationError initializationError) { throw new RuntimeException(initializationError); } return chain.get(0); }
@Override public void evaluate() throws Throwable { final Method runChildrenMethod = ParentRunner.class.getDeclaredMethod("runChildren", RunNotifier.class); runChildrenMethod.setAccessible(true); new ReflectiveCallable() { @Override protected Object runReflectiveCall() throws Throwable { return runChildrenMethod.invoke(runner, notifier); } }.run(); }
@Override public void setScheduler(RunnerScheduler scheduler) { for (Runner child : getChildren()) { if (child instanceof ParentRunner<?>) { ((ParentRunner<?>) child).setScheduler(scheduler); } } }
/** * Creates runners for each producer consumer combination. * @param producerIdentifiers Producer identifiers * @param consumerIdentifiers Consumer identifiers * @return All required combinations for given identifiers * @throws Exception */ public List<Runner> createRunnersForRoles(Collection<UserIdentifier> producerIdentifiers, Collection<UserIdentifier> consumerIdentifiers) throws Exception { List<Runner> runners = new ArrayList<>(); if (consumerIdentifiers.isEmpty()) { consumerIdentifiers.add(UserIdentifier.getWithProducerRole()); } validateProducers(producerIdentifiers); validateConsumers(producerIdentifiers, consumerIdentifiers); for (UserIdentifier producerIdentifier : producerIdentifiers) { for (UserIdentifier consumerIdentifier : consumerIdentifiers) { Object parentRunner; if (consumerIdentifier.getIdentifier() != null && consumerIdentifier.getIdentifier().equals(RunWithUsers.WITH_PRODUCER_ROLE)) { parentRunner = runnerConstructor.newInstance( testClass.getJavaClass(), producerIdentifier, producerIdentifier ); } else { parentRunner = runnerConstructor.newInstance( testClass.getJavaClass(), producerIdentifier, consumerIdentifier ); } runners.add((ParentRunner) parentRunner); } } return runners; }
@Test public void whenGetChildren_thenListOfChildrenReturned() throws InitializationError { List<CucumberTagStatement> featureElements = new ArrayList<CucumberTagStatement>(); CucumberScenario scenario = mock(CucumberScenario.class); featureElements.add(scenario); when(cucumberFeature.getFeatureElements()).thenReturn(featureElements); when(cucumberFeature.getGherkinFeature()).thenReturn(feature); when(feature.getKeyword()).thenReturn(TEST_KEYWORD); when(feature.getName()).thenReturn(TEST_NAME); runner = new RestFeatureRunner(cucumberFeature, runtime, reporter); List<ParentRunner<?>> listOfChildren = runner.getChildren(); assertTrue(!listOfChildren.isEmpty()); }
private CountingRunListener runTestWithParentRunner(Class<?> testClass) throws InitializationError { CountingRunListener listener = new CountingRunListener(); RunNotifier runNotifier = new RunNotifier(); runNotifier.addListener(listener); ParentRunner runner = new BlockJUnit4ClassRunner(testClass); runner.run(runNotifier); return listener; }
/** * Reflectively invokes a {@link ParentRunner}'s getFilteredChildren method. Manipulating this * list lets us control which tests will be run. */ static <T> List<T> getFilteredChildren(ParentRunner<T> parentRunner) { try { //noinspection unchecked return new ArrayList<>((Collection<T>) getFilteredChildrenMethod.invoke(parentRunner)); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException("Failed to invoke getFilteredChildren()", e); } }
@Override protected Description describeChild(Object child) { ParentRunner runner = runners.get(child.getClass()); try { Class<? extends ParentRunner> c = runner.getClass(); Method m = c.getDeclaredMethod("describeChild", child.getClass()); m.setAccessible(true); return (Description)m.invoke(runner, child); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { RuntimeException re = new RuntimeException("Illegal access exception running tests"); re.initCause(e); throw re; } }
@Override protected void runChild(Object child, RunNotifier notifier) { ParentRunner runner = runners.get(child.getClass()); try { Class<? extends ParentRunner> c = runner.getClass(); Method m = c.getDeclaredMethod("runChild", child.getClass(), RunNotifier.class); m.setAccessible(true); m.invoke(runner, child, notifier); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { RuntimeException re = new RuntimeException("Illegal access exception running tests"); re.initCause(e); throw re; } }