@Override public void evaluate() throws Throwable { ProducedValues marker = method.getAnnotation(ProducedValues.class); ProducerAssignments assignments = ProducerAssignments.allUnassigned(testClass, method.getMethod()); int iterations = marker == null ? 1 : marker.iterations(); for (int i = 0; i < iterations; i++) { try { new AssignmentsStatement(testClass.getJavaClass(), method, assignments, i).evaluate(); success++; } catch (AssumptionViolatedException e) { failedAssumptions.add(e); } } if (success == 0) { fail("Never found parameters that satisfied method assumptions. Violated assumptions: " + failedAssumptions); } }
@Override protected void before() throws Throwable { if (runtimeMode == RuntimeMode.REQUIRE_RUNNING_INSTANCE) { if (!CassandraSocket.isConnectable(getHost(), getPort())) { throw new AssumptionViolatedException( String.format("Cassandra is not reachable at %s:%s.", getHost(), getPort())); } } if (runtimeMode == RuntimeMode.EMBEDDED_IF_NOT_RUNNING) { if (CassandraSocket.isConnectable(getHost(), getPort())) { return; } } EmbeddedCassandraServerHelper.startEmbeddedCassandra("embedded-cassandra.yaml"); super.before(); }
@Test public void whenDockerClientCantBeCreatedAnAssumptionExceptionIsThrown() throws NoSuchMethodException, NoSuchFieldException, IllegalAccessException, InvocationTargetException { destroyDockerClientFactoryInstance(); GenericContainerRule genericContainerRule = new GenericContainerRule(() -> new GenericContainer()).assumeDockerIsPresent(); boolean assumptionExceptionOccurred = false; try { genericContainerRule.apply(null,null).evaluate(); } catch (AssumptionViolatedException ave) { assumptionExceptionOccurred = true; } catch (Throwable throwable) { throwable.printStackTrace(); } finally { unDestroyDockerClientFactoryInstance(); } assertThat(assumptionExceptionOccurred).isTrue().as("AssumptionException was thrown"); }
protected Statement throwOnIgnoreTest(Statement statement, Description description) { if (isTest(description)) { boolean ignoreTest = false; String message = ""; IgnoreUntil testCaseAnnotation = description.getAnnotation(IgnoreUntil.class); if (testCaseAnnotation != null) { ignoreTest = evaluate(testCaseAnnotation, description); message = testCaseAnnotation.value(); } else if (description.getTestClass().isAnnotationPresent(IgnoreUntil.class)) { IgnoreUntil testClassAnnotation = description.getTestClass().getAnnotation(IgnoreUntil.class); ignoreTest = evaluate(testClassAnnotation, description); message = testClassAnnotation.value(); } if (ignoreTest) { throw new AssumptionViolatedException(format(message, description)); } } return statement; }
protected Statement throwOnIgnoreTest(Statement statement, Description description) { if (isTest(description)) { boolean ignoreTest = false; String message = ""; ConditionalIgnore testCaseAnnotation = description.getAnnotation(ConditionalIgnore.class); if (testCaseAnnotation != null) { ignoreTest = evaluate(testCaseAnnotation, description); message = testCaseAnnotation.value(); } else if (description.getTestClass().isAnnotationPresent(ConditionalIgnore.class)) { ConditionalIgnore testClassAnnotation = description.getTestClass().getAnnotation(ConditionalIgnore.class); ignoreTest = evaluate(testClassAnnotation, description); message = testClassAnnotation.value(); } if (ignoreTest) { throw new AssumptionViolatedException(format(message, description)); } } return statement; }
protected Statement prepareMethodBlock(final FrameworkMethod method, final RunNotifier notifier) { final Statement methodBlock = superMethodBlock(method); return new Statement() { @Override public void evaluate() throws Throwable { try { methodBlock.evaluate(); Description description = describeChild(method); try { notifier.fireTestStarted(description); notifier.fireTestAssumptionFailed(new Failure(description, new AssumptionViolatedException("Method " + method.getName() + " did parse any input"))); } finally { notifier.fireTestFinished(description); } } catch(TestDataCarrier testData) { AbstractParallelScenarioRunner.this.testData.put(method, testData.getData()); } } }; }
protected void process(String data) throws Exception { IInjectorProvider delegate = getOrCreateInjectorProvider().getDelegate(); if (delegate instanceof IRegistryConfigurator) { IRegistryConfigurator registryConfigurator = (IRegistryConfigurator) delegate; registryConfigurator.setupRegistry(); try { ScenarioProcessor processor = delegate.getInjector().getInstance(processorClass); String preProcessed = processor.preProcess(data); if (preProcessed == null) { throw new AssumptionViolatedException("Input is filtered by the pre processing step: " + data); } doProcess(preProcessed, processor); } finally { registryConfigurator.restoreRegistry(); } } }
@Override protected Sender createSender() throws Exception { RabbitMQSender result = RabbitMQSender.newBuilder() .queue("zipkin-jmh") .addresses("localhost:5672").build(); CheckResult check = result.check(); if (!check.ok()) { throw new AssumptionViolatedException(check.error().getMessage(), check.error()); } channel = result.get().createChannel(); channel.queueDelete(result.queue()); channel.queueDeclare(result.queue(), false, true, true, null); Thread.sleep(500L); new Thread(() -> { try { channel.basicConsume(result.queue(), true, new DefaultConsumer(channel)); } catch (IOException e) { e.printStackTrace(); } }).start(); return result; }
@Test public void useTimeoutEventDescriptionForMessage() throws Exception { String theMessage = "last result"; Mockito.doReturn(theMessage).when(event).getLastResult(); expectedException.expect(RuntimeException.class); expectedException.expectCause(allOf( Matchers.<Throwable>instanceOf(AssumptionViolatedException.class), applying(messageFunction(), allOf( containsString(failureMessage), containsString(theMessage), containsString(matcherDescription) )) )); try { timeoutExceptionFunction.apply(event); } catch (AssumptionViolatedException e) { throw new RuntimeException(e); } }
@Override public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { try { base.evaluate(); } catch (IOException e) { if (isOffline()) { throw new AssumptionViolatedException("offline", e); } else { throw e; } } } }; }
@Override protected ElasticsearchHttpStorage compute() { try { container = new GenericContainer(image) .withExposedPorts(9200) .withEnv("ES_JAVA_OPTS", "-Dmapper.allow_dots_in_name=true -Xms512m -Xmx512m") .waitingFor(new HttpWaitStrategy().forPath("/")); container.start(); if (Boolean.valueOf(System.getenv("ES_DEBUG"))) { container.followOutput(new Slf4jLogConsumer(LoggerFactory.getLogger(image))); } System.out.println("Starting docker image " + image); } catch (RuntimeException e) { // Ignore } ElasticsearchHttpStorage result = computeStorageBuilder().build(); CheckResult check = result.check(); if (check.ok()) { return result; } else { throw new AssumptionViolatedException(check.error().getMessage(), check.error()); } }
@Test public void testDeclareAndCallUF() { List<String> names = ImmutableList.of("Func", "|Func|", "(Func)"); for (String name : names) { Formula f; try { f = fmgr.declareAndCallUF( name, FormulaType.IntegerType, ImmutableList.of(imgr.makeNumber(1))); } catch (RuntimeException e) { if (name.equals("|Func|")) { throw new AssumptionViolatedException("unsupported UF name", e); } else { throw e; } } FunctionDeclaration<?> declaration = getDeclaration(f); Truth.assertThat(declaration.getName()).isEqualTo(name); Formula f2 = mgr.makeApplication(declaration, imgr.makeNumber(1)); Truth.assertThat(f2).isEqualTo(f); } }
@Override public Map<String, Object> getBaseConfiguration(String graphName, Class<?> test, String testMethodName, LoadGraphWith.GraphData loadGraphWith) { if (IGNORED_TESTS.containsKey(test) && IGNORED_TESTS.get(test).contains(testMethodName)) throw new AssumptionViolatedException("We allow mixed ids"); if (testMethodName.contains("graphson-v2-embedded")) throw new AssumptionViolatedException("graphson-v2-embedded support not implemented"); HashMap<String, Object> configs = new HashMap<String, Object>(); configs.put(Graph.GRAPH, OrientGraph.class.getName()); configs.put("name", graphName); if (testMethodName.equals("shouldPersistDataOnClose")) configs.put(OrientGraph.CONFIG_URL, "memory:test-" + graphName + "-" + test.getSimpleName() + "-" + testMethodName); Random random = new Random(); if (random.nextBoolean()) configs.put(OrientGraph.CONFIG_POOL_SIZE, random.nextInt(10) + 1); return configs; }
/** * Get the event bus that's being used in the app. * * @return The event bus. * @throws AssumptionViolatedException If the default event bus can't be constructed because of * the Android framework not being loaded. This will stop the calling tests from being reported * as failures. */ @NonNull private static EventBus getEventBus() { try { return EventBus.getDefault(); } catch (RuntimeException e) { /* The event bus uses the Looper from the Android framework, so * initializing it would throw a runtime exception if the * framework is not loaded. Nor can RoboGuice be used to inject * a mocked instance to get around this issue, since customizing * RoboGuice injections requires a Context. * * Robolectric can't be used to solve this issue, because it * doesn't support parameterized testing. The only solution that * could work at the moment would be to make this an * instrumented test suite. * * TODO: Mock the event bus when RoboGuice is replaced with * another dependency injection framework, or when there is a * Robolectric test runner available that support parameterized * tests. */ throw new AssumptionViolatedException( "Event bus requires Android framework", e, nullValue()); } }
/** * Implementation based on {@link TestWatcher}. */ @Override public Statement apply(final Statement base, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { List<Throwable> errors = new ArrayList<Throwable>(); startingQuietly(description, errors); try { base.evaluate(); succeededQuietly(description, errors); } catch (AssumptionViolatedException e) { errors.add(e); skippedQuietly(e, description, errors); } catch (Throwable t) { errors.add(t); failedQuietly(t, description, errors); } finally { finishedQuietly(description, errors); } MultipleFailureException.assertEmpty(errors); } }; }
@Override public Statement apply(final Statement base, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { for (CoordinateSystem2D coordinateSystem : CoordinateSystem2D.values()) { CoordinateSystem2D.setDefaultCoordinateSystem(coordinateSystem); try { base.evaluate(); } catch (AssumptionViolatedException exception) { // Ignore the exception related to the "ignore test" } } } }; }
@Override public Statement apply(final Statement base, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { for (CoordinateSystem3D coordinateSystem : CoordinateSystem3D.values()) { CoordinateSystem3D.setDefaultCoordinateSystem(coordinateSystem); try { base.evaluate(); } catch (AssumptionViolatedException exception) { // Ignore the exception related to the "ignore test" } } } }; }
@Override public Statement apply(final Statement base, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { for (PathWindingRule rule : PathWindingRule.values()) { try { CURRENT_RULE = rule; base.evaluate(); } catch (AssumptionViolatedException exception) { // Ignore the exception related to the "ignore test" } } } }; }
private void setUpForPermissionSystemTest() { if (permissionsSystemType == LUCK_PERMS) { LuckPermsApi api = mock(LuckPermsApi.class); ReflectionTestUtils.setField(LuckPerms.class, null, "instance", api); } else if (permissionsSystemType == PERMISSIONS_EX) { throw new AssumptionViolatedException( "PermissionsEx instance cannot be mocked because of missing dependencies -- skipping"); } else if (permissionsSystemType == Z_PERMISSIONS) { ZPermissionsService zPermissionsService = mock(ZPermissionsService.class); given(servicesManager.load(ZPermissionsService.class)).willReturn(zPermissionsService); } else if (permissionsSystemType == VAULT) { setUpForVault(); } else if (permissionsSystemType != B_PERMISSIONS) { throw new IllegalStateException("Unhandled permission systems type: " + permissionsSystemType); } }
@Override protected void skipped( AssumptionViolatedException e, Description description) { AbstractStopwatch.this.stopping(); AbstractStopwatch.this.skipped(getNanos(), e, description); }
@Override protected void before() throws Throwable { try (Socket socket = new Socket()) { socket.setTcpNoDelay(true); socket.setSoLinger(true, 0); socket.connect(new InetSocketAddress(host, port), timeout); } catch (Exception e) { throw new AssumptionViolatedException(String.format("Seems as Redis is not running at %s:%s.", host, port), e); } if (NO_VERSION.equals(requiredVersion)) { return; } try (Jedis jedis = new Jedis(host, port)) { String infoServer = jedis.info("server"); String redisVersion = JedisConverters.stringToProps().convert(infoServer).getProperty("redis_version"); Version runningVersion = Version.parse(redisVersion); if (runningVersion.isLessThan(requiredVersion)) { throw new AssumptionViolatedException(String .format("This test requires Redis version %s but you run version %s", requiredVersion, runningVersion)); } } }
@Override protected void before() throws Throwable { dependency.before(); Cluster cluster = Cluster.builder().addContactPoint(getHost()).withPort(getPort()) .withNettyOptions(new NettyOptions() { @Override public void onClusterClose(EventLoopGroup eventLoopGroup) { eventLoopGroup.shutdownGracefully(0, 0, TimeUnit.MILLISECONDS).syncUninterruptibly(); } }).build(); Session session = cluster.newSession(); try { if (requiredVersion != null) { Version cassandraReleaseVersion = CassandraVersion.getReleaseVersion(session); if (cassandraReleaseVersion.isLessThan(requiredVersion)) { throw new AssumptionViolatedException( String.format("Cassandra at %s:%s runs in Version %s but we require at least %s", getHost(), getPort(), cassandraReleaseVersion, requiredVersion)); } } session.execute(String.format("CREATE KEYSPACE IF NOT EXISTS %s \n" + "WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };", keyspaceName)); } finally { session.close(); cluster.close(); } }
/** * Add an assumption prior to container creation that throws {@link AssumptionViolatedException} * so that tests are ignored. This is opt-in * * @return this */ public SELF assumeDockerIsPresent() { final Supplier<T> originalContainerSupplier = containerSupplier; containerSupplier = () -> { try { DockerClientFactory.instance().client(); } catch (Throwable t) { throw new AssumptionViolatedException("Unable to create container[might be docker related]", t); } return originalContainerSupplier.get(); }; return self(); }
private Statement emptyStatement(final String reason) { return new Statement() { @Override public void evaluate() throws Throwable { throw new AssumptionViolatedException("Test was ignored by FilterRule: " + reason); } }; }
@Override public void after(Description description, Throwable testFailure) throws Throwable { super.after(description, testFailure); try { boolean isAssumptionViolation = false; if (testFailure != null) { if (AssumptionViolatedException.class.isAssignableFrom(testFailure.getClass())) { isAssumptionViolation = true; LOGGER.error("Test assumption was violated: ", testFailure); testFailure = null; } else { LOGGER.error("Test failed with error: ", testFailure); } } Logger.getRootLogger().removeAppender(appender); appender.close(); appender = null; if (isAssumptionViolation && saveOnAssumptionViolation) { saveToFileWithPostfix(description, "_AV.log"); } else if (!saveOnlyOnError || testFailure != null) { saveToFileWithPostfix(description, ".log"); } } finally { if (!tempFile.delete()) { LOGGER.error("Could not delete temp file at " + tempFile.getAbsolutePath()); } tempFile = null; } }
@Override protected void runChild(final FrameworkMethod method, RunNotifier notifier) { Description description = describeChild(method); if (isIgnored(method)) { notifier.fireTestIgnored(description); } else { try { runLeaf(methodBlock(method), description, notifier); } catch (AssumptionViolatedException ex) { notifier.fireTestIgnored(description); } } }
/** * Assume that a minimum {@link JavaVersion} is running. * @param version the minimum version for the test to run * @throws AssumptionViolatedException if the assumption fails */ public static void atLeast(JavaVersion version) { if (!JavaVersion.runningVersion().isAtLeast(version)) { throw new AssumptionViolatedException("Requires JDK " + version + " but running " + JavaVersion.runningVersion()); } }
/** * Assume that we can load fonts. * <p>See <a href="https://java.net/jira/browse/MACOSX_PORT-355">MACOSX_PORT-355</a> * issue. * @throws AssumptionViolatedException if the assumption fails */ public static void canLoadNativeDirFonts() { try { GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(); Class<?> parserClass = ClassUtils.forName( "net.sf.jasperreports.engine.util.JRStyledTextParser", Assume.class.getClassLoader()); Method method = parserClass.getMethod("getInstance"); method.setAccessible(true); method.invoke(null); } catch (Throwable ex) { throw new AssumptionViolatedException("Requires GraphicsEnvironment that can load fonts", ex); } }
@BeforeClass public static void checkCassandraIsUp() { try (Cluster cluster = buildCluster(Cassandra3Storage.builder().build()); Session session = cluster.newSession()) { session.execute("SELECT now() FROM system.local"); } catch (RuntimeException e) { throw new AssumptionViolatedException(e.getMessage(), e); } }
@BeforeClass public static void checkCassandraIsUp() { try (Cluster cluster = buildCluster(CassandraStorage.builder().build()); Session session = cluster.newSession()) { session.execute("SELECT now() FROM system.local"); } catch (RuntimeException e) { throw new AssumptionViolatedException(e.getMessage(), e); } }
@Test public void portDefaultsTo9300() throws IOException { try (LazyClient lazyClient = new LazyClient(ElasticsearchStorage.builder() .hosts(asList("localhost")))) { assertThat(((NativeClient) lazyClient.get()).client.transportAddresses()) .extracting(TransportAddress::getPort) .containsOnly(9300); } catch (NoNodeAvailableException e) { throw new AssumptionViolatedException(e.getMessage()); } }
@Override protected void skipped(AssumptionViolatedException e, Description description) { super.skipped(e, description); if (file != null) { //noinspection ResultOfMethodCallIgnored file.delete(); } }
@Override protected void process(String data) throws Exception { IInjectorProvider delegate = getOrCreateInjectorProvider().getDelegate(); ScenarioProcessor processor = delegate.getInjector().getInstance(getProcessorClass()); String preProcessed = processor.preProcess(data); if (preProcessed == null) { throw new AssumptionViolatedException("Input is filtered by the pre processing step: " + data); } doProcess(preProcessed, processor); }
@Before public void open() throws Exception { sender = RabbitMQSender.newBuilder() .queue("zipkin-test1") .addresses("localhost:5672").build(); CheckResult check = sender.check(); if (!check.ok()) { throw new AssumptionViolatedException(check.error().getMessage(), check.error()); } declareQueue(sender.queue()); }
public static String getenv(String name) { final String value = System.getenv(name); if (value == null) { throw new AssumptionViolatedException("environment variable " + name + " is not set"); } return value; }
@Before public void checkRateLimit() throws IOException { JsonNode rateLimitNode = new ObjectMapper().readTree(new URL("https://api.github.com/rate_limit")); int requestsRemaining = rateLimitNode.findPath("resources").findPath("core").findPath("remaining").intValue(); if (requestsRemaining <= 0) { throw new AssumptionViolatedException("API rate limit exceeded"); } }
private void assertTestIsSkipped(Statement testWithRuleApplied) throws Throwable { try { testWithRuleApplied.evaluate(); } catch (AssumptionViolatedException e) { // expected } }
@Override public <K, V> FileBackedStorageEngine<K, V> createStorageEngine(PageSource source, Portability<? super K> keyPortability, Portability<? super V> valuePortability, boolean thief, boolean victim) { if (!thief && !victim) { return new FileBackedStorageEngine<>((MappedPageSource) source, 1024, MemoryUnit.BYTES, keyPortability, valuePortability); } else { throw new AssumptionViolatedException("FileBackedStorageEngine doesn't support stealing"); } }
@Override public <K, V> Factory<FileBackedStorageEngine<K, V>> createStorageEngineFactory(PageSource source, Portability<? super K> keyPortability, Portability<? super V> valuePortability, boolean thief, boolean victim) { if (!thief && !victim) { return FileBackedStorageEngine.createFactory((MappedPageSource) source, 1024, MemoryUnit.BYTES, keyPortability, valuePortability); } else { throw new AssumptionViolatedException("FileBackedStorageEngine doesn't support stealing"); } }
@Override protected void skipped(AssumptionViolatedException e, Description description) { timeEnd = System.currentTimeMillis(); if (System.getProperty("saucelabs", "false").equals("true") && !sessionID.isEmpty()) { SauceAPI.flagTestPassed(sessionID); } addTestRailAPIResult(APIMethods.RESULT.SKIPPED, (timeEnd-timeStart)/1000.0, sessionID, configuration, testName, e.getMessage()); }