List of usage examples for java.lang AssertionError AssertionError
public AssertionError(double detailMessage)
double
, which is converted to a string as defined in section 15.18.1.1 of The Java™ Language Specification. From source file:com.predic8.membrane.examples.tests.LoadBalancerSession3Test.java
/** * The test as described in README.txt, but "wsimport" (previously called by ant) * was removed and is run directly from this test before everything else. Thereby * we can use a Maven dependency on wsimport and do not have to download it ourselves. *//* w ww.ja v a 2 s.co m*/ @Test public void test() throws IOException, InterruptedException { File base = getExampleDir("loadbalancer-session-3"); AssertUtils.replaceInFile(new File(base, "proxies.xml"), "8080", "3023"); AssertUtils.replaceInFile(new File(base, "src/com/predic8/chat/Client.java"), "8080", "3023"); AssertUtils.replaceInFile(new File(base, "data/ChatService.wsdl"), "8080", "3023"); Process2 sl = new Process2.Builder().in(base).script("service-proxy").waitForMembrane().start(); try { File buildXML = new File(base, "build.xml"); // remove <exec...</exec> from build.xml String s = Pattern.compile("<exec.*</exec>", Pattern.DOTALL) .matcher(FileUtils.readFileToString(buildXML)).replaceAll(""); FileUtils.writeStringToFile(buildXML, s); File classes = new File(base, "build" + File.separator + "classes"); classes.mkdirs(); File source = new File(base, "src"); source.mkdirs(); // run "wsimport" generating java sources Assert.assertTrue(new com.sun.tools.ws.wscompile.WsimportTool(System.out).run(new String[] { "-quiet", "-Xnocompile", new File(base, "data" + File.separator + "ChatService.wsdl").getAbsolutePath(), "-s", source.getAbsolutePath() })); // call "ant compile" now so that both antNodeX processes do call it at the same time BufferLogger loggerCompile = new BufferLogger(); Process2 antCompile = new Process2.Builder().in(base).withWatcher(loggerCompile) .executable("ant compile").start(); try { int result = antCompile.waitFor(60000); if (result != 0) throw new AssertionError( "'ant compile' returned non-zero " + result + ":\r\n" + loggerCompile.toString()); } finally { antCompile.killScript(); } BufferLogger loggerNode1 = new BufferLogger(); BufferLogger loggerNode2 = new BufferLogger(); Process2 antNode1 = new Process2.Builder().in(base).withWatcher(loggerNode1).executable("ant run-node1") .start(); try { Process2 antNode2 = new Process2.Builder().in(base).withWatcher(loggerNode2) .executable("ant run-node2").start(); try { LoadBalancerUtil.addLBNodeViaHTML("http://localhost:9000/admin/", "localhost", 4000); LoadBalancerUtil.addLBNodeViaHTML("http://localhost:9000/admin/", "localhost", 4001); Thread.sleep(1000); // wait for nodes to come up Process2 antClient = new Process2.Builder().in(base).executable("ant run-client -Dlogin=jim") .start(); try { antClient.waitFor(60000); } finally { antClient.killScript(); } } finally { antNode2.killScript(); } } finally { antNode1.killScript(); } AssertUtils.assertContains("Hallo World", loggerNode1.toString()); AssertUtils.assertContainsNot("Hallo World", loggerNode2.toString()); } finally { sl.killScript(); } }
From source file:com.simiacryptus.mindseye.test.unit.SerializationTest.java
@Nullable @Override/*from w ww . j a v a2 s . c o m*/ public ToleranceStatistics test(@Nonnull final NotebookOutput log, @Nonnull final Layer layer, final Tensor... inputPrototype) { log.h1("Serialization"); log.p("This apply will demonstrate the key's JSON serialization, and verify deserialization integrity."); String prettyPrint = ""; log.h2("Raw Json"); try { prettyPrint = log.eval(() -> { final JsonObject json = layer.getJson(); @Nonnull final Layer echo = Layer.fromJson(json); if (echo == null) throw new AssertionError("Failed to deserialize"); if (layer == echo) throw new AssertionError("Serialization did not copy"); if (!layer.equals(echo)) throw new AssertionError("Serialization not equal"); echo.freeRef(); return new GsonBuilder().setPrettyPrinting().create().toJson(json); }); @Nonnull String filename = layer.getClass().getSimpleName() + "_" + log.getName() + ".json"; log.p(log.file(prettyPrint, filename, String.format("Wrote Model to %s; %s characters", filename, prettyPrint.length()))); } catch (RuntimeException e) { e.printStackTrace(); Util.sleep(1000); } catch (OutOfMemoryError e) { e.printStackTrace(); Util.sleep(1000); } log.p(""); @Nonnull Object outSync = new Object(); if (prettyPrint.isEmpty() || prettyPrint.length() > 1024 * 64) Arrays.stream(SerialPrecision.values()).parallel().forEach(precision -> { try { @Nonnull File file = new File(log.getResourceDir(), log.getName() + "_" + precision.name() + ".zip"); layer.writeZip(file, precision); @Nonnull final Layer echo = Layer.fromZip(new ZipFile(file)); getModels().put(precision, echo); synchronized (outSync) { log.h2(String.format("Zipfile %s", precision.name())); log.p(log.link(file, String.format("Wrote Model apply %s precision to %s; %.3fMiB bytes", precision, file.getName(), file.length() * 1.0 / (0x100000)))); } if (!isPersist()) file.delete(); if (echo == null) throw new AssertionError("Failed to deserialize"); if (layer == echo) throw new AssertionError("Serialization did not copy"); if (!layer.equals(echo)) throw new AssertionError("Serialization not equal"); } catch (RuntimeException e) { e.printStackTrace(); } catch (OutOfMemoryError e) { e.printStackTrace(); } catch (ZipException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }); return null; }
From source file:daveayan.gherkinsalad.components.core.BaseBrowserElement.java
public Element findElement(final By by) { if (by == null) { error("Cannot find element on the page with a null element locator"); return NullElement.newInstance(element_locator); }//from ww w .j a v a 2 s . c om if (browser.driver() instanceof NullWebDriver) { throw new AssertionError("Cannot find any element '" + by + "' on a NullWebDriver"); } Wait<WebDriver> wait = new FluentWait<WebDriver>(browser.driver()) .withTimeout(Config.seconds_timeout, TimeUnit.SECONDS) .pollingEvery(Config.seconds_poll_interval, TimeUnit.SECONDS) .ignoring(NoSuchElementException.class); WebElement _webElement; try { _webElement = wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(by); } }); } catch (TimeoutException toe) { return NullElement.newInstance(element_locator); } return Element.newInstance(_webElement, name(), by); }
From source file:com.bigdata.dastor.client.RingCache.java
public void refreshEndPointMap() { for (String seed : seeds_) { try {/* w ww . j ava 2s. co m*/ TSocket socket = new TSocket(seed, port_); TBinaryProtocol binaryProtocol = new TBinaryProtocol(socket, false, false); Dastor.Client client = new Dastor.Client(binaryProtocol); socket.open(); Map<String, String> tokenToHostMap = (Map<String, String>) JSONValue .parse(client.get_string_property(DastorThriftServer.TOKEN_MAP)); BiMap<Token, InetAddress> tokenEndpointMap = HashBiMap.create(); for (Map.Entry<String, String> entry : tokenToHostMap.entrySet()) { Token token = StorageService.getPartitioner().getTokenFactory().fromString(entry.getKey()); String host = entry.getValue(); try { tokenEndpointMap.put(token, InetAddress.getByName(host)); } catch (UnknownHostException e) { throw new AssertionError(e); // host strings are IPs } } tokenMetadata = new TokenMetadata(tokenEndpointMap); break; } catch (TException e) { /* let the Exception go and try another seed. log this though */ logger_.debug("Error contacting seed " + seed + " " + e.getMessage()); } } }
From source file:mulavito.algorithms.shortestpath.ksp.KShortestPathAlgorithm.java
/** Test whether the source is equal to the target */ private boolean check(V source, V target) { if (!graph.containsVertex(source) || !graph.containsVertex(target)) throw new AssertionError("The source or the target node does not exist!"); return source.equals(target); }
From source file:com.wickettasks.business.services.user.TestUserService.java
@Test(expected = IllegalArgumentException.class) public void aPasswordIsMandatoryToCreateAnUser() { try {/*from w w w . j a va 2s . c o m*/ this.userService.add("test@email.com", null); } catch (ExistingUserException e) { throw new AssertionError(e); } }
From source file:io.github.retz.web.Client.java
protected Client(URI uri, Authenticator authenticator, boolean checkCert) { this.uri = Objects.requireNonNull(uri); this.authenticator = Objects.requireNonNull(authenticator); this.checkCert = checkCert; if (uri.getScheme().equals("https") && !checkCert) { LOG.warn(//w ww . j a v a2 s . c o m "DANGER ZONE: TLS certificate check is disabled. Set 'retz.tls.insecure = false' at config file to supress this message."); try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[] { new WrongTrustManager() }, new java.security.SecureRandom()); socketFactory = sc.getSocketFactory(); hostnameVerifier = new NoOpHostnameVerifier(); } catch (NoSuchAlgorithmException e) { throw new AssertionError(e.toString()); } catch (KeyManagementException e) { throw new AssertionError(e.toString()); } } else { socketFactory = null; hostnameVerifier = null; } this.retz = Retz.connect(uri, authenticator, socketFactory, hostnameVerifier); System.setProperty("http.agent", Client.VERSION_STRING); }
From source file:com.mgmtp.perfload.core.client.util.concurrent.DelayingExecutorServiceTest.java
@Test public void testWithDelay() throws InterruptedException, BrokenBarrierException { DelayingExecutorService execSrv = new DelayingExecutorService(); final StopWatch sw = new StopWatch(); final CyclicBarrier stopBarrier = new CyclicBarrier(11, new Runnable() { @Override//w w w . java 2s .c o m public void run() { sw.stop(); } }); sw.start(); final long taskSleepMillis = 75L; long delayMultiplier = 50L; int loopMax = 10; for (int i = 0; i < loopMax; ++i) { Callable<Void> c = new Callable<Void>() { @Override public Void call() { try { Thread.sleep(taskSleepMillis); stopBarrier.await(); } catch (Exception ex) { throw new AssertionError(ex); } return null; } }; long delay = delayMultiplier * i; ScheduledFuture<?> future = execSrv.schedule(c, delay, TimeUnit.MILLISECONDS); long actualDelay = future.getDelay(TimeUnit.MILLISECONDS); // compare with epsilon to make up for bad accuracy assertTrue(abs(delay - actualDelay) < EPSILON); } stopBarrier.await(); long actualTime = sw.getTime(); long expectedTime = delayMultiplier * (loopMax - 1) + taskSleepMillis; // compare with epsilon to make up for bad accuracy assertTrue(abs(actualTime - expectedTime) < EPSILON); }
From source file:org.elasticsearch.smoketest.SmokeTestWatcherWithSecurityClientYamlTestSuiteIT.java
@Before public void startWatcher() throws Exception { // delete the watcher history to not clutter with entries from other test getAdminExecutionContext().callApi("indices.delete", Collections.singletonMap("index", ".watcher-history-*"), emptyList(), emptyMap()); // create one document in this index, so we can test in the YAML tests, that the index cannot be accessed Response resp = adminClient().performRequest("PUT", "/index_not_allowed_to_read/doc/1", Collections.emptyMap(), new StringEntity("{\"foo\":\"bar\"}", ContentType.APPLICATION_JSON)); assertThat(resp.getStatusLine().getStatusCode(), is(201)); assertBusy(() -> {//from ww w . j av a2 s . co m ClientYamlTestResponse response = getAdminExecutionContext().callApi("xpack.watcher.stats", emptyMap(), emptyList(), emptyMap()); String state = (String) response.evaluate("stats.0.watcher_state"); switch (state) { case "stopped": ClientYamlTestResponse startResponse = getAdminExecutionContext().callApi("xpack.watcher.start", emptyMap(), emptyList(), emptyMap()); boolean isAcknowledged = (boolean) startResponse.evaluate("acknowledged"); assertThat(isAcknowledged, is(true)); break; case "stopping": throw new AssertionError("waiting until stopping state reached stopped state to start again"); case "starting": throw new AssertionError("waiting until starting state reached started state"); case "started": // all good here, we are done break; default: throw new AssertionError("unknown state[" + state + "]"); } }); assertBusy(() -> { for (String template : WatcherIndexTemplateRegistryField.TEMPLATE_NAMES) { ClientYamlTestResponse templateExistsResponse = getAdminExecutionContext().callApi( "indices.exists_template", singletonMap("name", template), emptyList(), emptyMap()); assertThat(templateExistsResponse.getStatusCode(), is(200)); } }); }
From source file:edu.emory.cci.aiw.cvrg.eureka.common.entity.SystemProposition.java
private CategoryType inferCategoryType() { if (systemType != null) { switch (systemType) { case HIGH_LEVEL_ABSTRACTION: return CategoryType.HIGH_LEVEL_ABSTRACTION; case CONSTANT: return CategoryType.CONSTANT; case EVENT: return CategoryType.EVENT; case PRIMITIVE_PARAMETER: return CategoryType.PRIMITIVE_PARAMETER; case LOW_LEVEL_ABSTRACTION: return CategoryType.LOW_LEVEL_ABSTRACTION; case SLICE_ABSTRACTION: return CategoryType.SLICE_ABSTRACTION; case SEQUENTIAL_TEMPORAL_PATTERN_ABSTRACTION: return CategoryType.SEQUENTIAL_TEMPORAL_PATTERN_ABSTRACTION; case CONTEXT: return CategoryType.CONTEXT; default://from www . j ava 2 s .com throw new AssertionError("Invalid system type: " + systemType); } } else { return null; } }