List of usage examples for java.lang AssertionError getMessage
public String getMessage()
From source file:org.apache.hadoop.yarn.server.resourcemanager.TestRMHA.java
private void verifyClusterMetrics(int activeNodes, int appsSubmitted, int appsPending, int containersPending, long availableMB, int activeApplications) throws Exception { int timeoutSecs = 0; QueueMetrics metrics = rm.getResourceScheduler().getRootQueueMetrics(); ClusterMetrics clusterMetrics = ClusterMetrics.getMetrics(); boolean isAllMetricAssertionDone = false; String message = null;//from w w w . ja v a2 s. co m while (timeoutSecs++ < 5) { try { // verify queue metrics assertMetric("appsSubmitted", appsSubmitted, metrics.getAppsSubmitted()); assertMetric("appsPending", appsPending, metrics.getAppsPending()); assertMetric("containersPending", containersPending, metrics.getPendingContainers()); assertMetric("availableMB", availableMB, metrics.getAvailableMB()); assertMetric("activeApplications", activeApplications, metrics.getActiveApps()); // verify node metric assertMetric("activeNodes", activeNodes, clusterMetrics.getNumActiveNMs()); isAllMetricAssertionDone = true; break; } catch (AssertionError e) { message = e.getMessage(); System.out.println("Waiting for metrics assertion to complete"); Thread.sleep(1000); } } assertTrue(message, isAllMetricAssertionDone); }
From source file:org.elasticsearch.test.rest.yaml.section.DoSectionTests.java
public void testWarningHeaders() throws IOException { {/*from w w w .j a va 2s . c o m*/ final DoSection section = new DoSection(new XContentLocation(1, 1)); // No warning headers doesn't throw an exception section.checkWarningHeaders(emptyList(), Version.CURRENT); } final String testHeader = DeprecationLogger.formatWarning("test"); final String anotherHeader = DeprecationLogger.formatWarning("another"); final String someMoreHeader = DeprecationLogger.formatWarning("some more"); final String catHeader = DeprecationLogger.formatWarning("cat"); // Any warning headers fail { final DoSection section = new DoSection(new XContentLocation(1, 1)); final AssertionError one = expectThrows(AssertionError.class, () -> section.checkWarningHeaders(singletonList(testHeader), Version.CURRENT)); assertEquals("got unexpected warning header [\n\t" + testHeader + "\n]\n", one.getMessage()); final AssertionError multiple = expectThrows(AssertionError.class, () -> section.checkWarningHeaders(Arrays.asList(testHeader, anotherHeader, someMoreHeader), Version.CURRENT)); assertEquals("got unexpected warning headers [\n\t" + testHeader + "\n\t" + anotherHeader + "\n\t" + someMoreHeader + "\n]\n", multiple.getMessage()); } // But not when we expect them { final DoSection section = new DoSection(new XContentLocation(1, 1)); section.setExpectedWarningHeaders(singletonList("test")); section.checkWarningHeaders(singletonList(testHeader), Version.CURRENT); } { final DoSection section = new DoSection(new XContentLocation(1, 1)); section.setExpectedWarningHeaders(Arrays.asList("test", "another", "some more")); section.checkWarningHeaders(Arrays.asList(testHeader, anotherHeader, someMoreHeader), Version.CURRENT); } // But if you don't get some that you did expect, that is an error { final DoSection section = new DoSection(new XContentLocation(1, 1)); section.setExpectedWarningHeaders(singletonList("test")); final AssertionError e = expectThrows(AssertionError.class, () -> section.checkWarningHeaders(emptyList(), Version.CURRENT)); assertEquals("did not get expected warning header [\n\ttest\n]\n", e.getMessage()); } { final DoSection section = new DoSection(new XContentLocation(1, 1)); section.setExpectedWarningHeaders(Arrays.asList("test", "another", "some more")); final AssertionError multiple = expectThrows(AssertionError.class, () -> section.checkWarningHeaders(emptyList(), Version.CURRENT)); assertEquals("did not get expected warning headers [\n\ttest\n\tanother\n\tsome more\n]\n", multiple.getMessage()); final AssertionError one = expectThrows(AssertionError.class, () -> section.checkWarningHeaders(Arrays.asList(testHeader, someMoreHeader), Version.CURRENT)); assertEquals("did not get expected warning header [\n\tanother\n]\n", one.getMessage()); } // It is also an error if you get some warning you want and some you don't want { final DoSection section = new DoSection(new XContentLocation(1, 1)); section.setExpectedWarningHeaders(Arrays.asList("test", "another", "some more")); final AssertionError e = expectThrows(AssertionError.class, () -> section.checkWarningHeaders(Arrays.asList(testHeader, catHeader), Version.CURRENT)); assertEquals( "got unexpected warning header [\n\t" + catHeader + "\n]\n" + "did not get expected warning headers [\n\tanother\n\tsome more\n]\n", e.getMessage()); } }
From source file:eu.stratosphere.core.testing.GenericTestPlan.java
private void validateResults() { for (final GenericDataSinkBase<T> sinkOperator : this.getDataSinks()) { final Records expectedValues = this.expectedOutputs.get(sinkOperator); // need a format which is deserializable without configuration if (sinkOperator.getFormatWrapper().getUserCodeClass() == (Class<?>) SequentialOutputFormat.class && expectedValues != null && expectedValues.isInitialized()) { final Records actualValues = this.getActualOutput(sinkOperator); try { actualValues.assertEquals(expectedValues); } catch (final AssertionError e) { final AssertionError assertionError = new AssertionError( sinkOperator.getName() + ": " + e.getMessage()); assertionError.initCause(e.getCause()); throw assertionError; } finally { actualValues.close();/* w w w .j a v a2s . c o m*/ } } } }
From source file:com.alliander.osgp.acceptancetests.configurationmanagement.GetConfigurationDataSteps.java
@DomainStep("the get configuration data response should return result (.*)") public boolean thenTheResponseShouldReturn(final String result) { LOGGER.info("THEN: the get status response should return {}.", result); if (result.toUpperCase().equals("OK")) { try {/*from w w w. ja v a2s.co m*/ Assert.assertNotNull("Response should not be null", this.response); Assert.assertNull("Throwable should be null", this.throwable); } catch (final AssertionError e) { LOGGER.error("Exception [{}]: {}", e.getClass().getSimpleName(), e.getMessage()); return false; } } else { try { Assert.assertNotNull("Throwable should not be null", this.throwable); Assert.assertEquals(result.toUpperCase(), this.throwable.getClass().getSimpleName().toUpperCase()); } catch (final AssertionError e) { LOGGER.error("Exception [{}]: {}", e.getClass().getSimpleName(), e.getMessage()); return false; } } return true; }
From source file:com.android.tools.idea.tests.gui.gradle.GradleSyncTest.java
@Test public void syncDuringOfflineMode() throws IOException { String hyperlinkText = "Disable offline mode and sync project"; guiTest.importSimpleApplication();/* w ww. j a v a 2s.c om*/ IdeFrameFixture ideFrame = guiTest.ideFrame(); File buildFile = new File(ideFrame.getProjectPath(), join("app", FN_BUILD_GRADLE)); assertAbout(file()).that(buildFile).isFile(); appendToFile(buildFile, "dependencies { compile 'something:not:exists' }"); GradleSettings gradleSettings = GradleSettings.getInstance(ideFrame.getProject()); gradleSettings.setOfflineWork(true); ideFrame.requestProjectSync().waitForGradleProjectSyncToFinish(); MessagesToolWindowFixture messagesToolWindow = ideFrame.getMessagesToolWindow(); MessageFixture message = messagesToolWindow.getGradleSyncContent().findMessage(ERROR, firstLineStartingWith("Failed to resolve:")); HyperlinkFixture hyperlink = message.findHyperlink(hyperlinkText); hyperlink.click(); assertFalse(gradleSettings.isOfflineWork()); ideFrame.waitForGradleProjectSyncToFinish(); messagesToolWindow = ideFrame.getMessagesToolWindow(); message = messagesToolWindow.getGradleSyncContent().findMessage(ERROR, firstLineStartingWith("Failed to resolve:")); try { message.findHyperlink(hyperlinkText); fail(hyperlinkText + " link still present"); } catch (AssertionError e) { // After offline mode is disable, the previous hyperlink will disappear after next sync assertThat(e.getMessage()).contains("Failed to find URL"); assertThat(e.getMessage()).contains(hyperlinkText); } }
From source file:com.joyent.manta.client.crypto.AbstractMantaEncryptedObjectInputStreamTest.java
protected void canReadByteRange(SupportedCipherDetails cipherDetails, Class<? extends ReadBytes> strategy, int startPosInclusive, int endPosInclusive) throws IOException { final byte[] content; try (InputStream in = testURL.openStream(); ByteArrayOutputStream out = new ByteArrayOutputStream()) { IOUtils.copy(in, out);//ww w .j a v a2 s. c o m content = out.toByteArray(); } /* If the plaintext size specified is greater than the actual plaintext * size, we adjust it here. This is only for creating the expectation * that we compare our output to. */ final int endPositionExclusive; if (endPosInclusive + 1 > plaintextSize) { endPositionExclusive = plaintextSize; } else { endPositionExclusive = endPosInclusive + 1; } boolean unboundedEnd = (endPositionExclusive >= plaintextSize || endPosInclusive < 0); byte[] expected = Arrays.copyOfRange(content, startPosInclusive, endPositionExclusive); SecretKey key = SecretKeyUtils.generate(cipherDetails); EncryptedFile encryptedFile = encryptedFile(key, cipherDetails, this.plaintextSize); long ciphertextSize = encryptedFile.file.length(); /* Here we translate the plaintext ranges to ciphertext ranges. Notice * that we take the input of endPos because it may overrun past the * size of the plaintext. */ ByteRangeConversion ranges = cipherDetails.translateByteRange(startPosInclusive, endPosInclusive); long ciphertextStart = ranges.getCiphertextStartPositionInclusive(); long plaintextLength = ((long) (endPosInclusive - startPosInclusive)) + 1L; /* Here, we simulate being passed only a subset of the total bytes of * a file - just like how the output of a HTTP range request would be * passed. */ try (RandomAccessFile randomAccessFile = new RandomAccessFile(encryptedFile.file, "r")) { // We seek to the start of the ciphertext to emulate a HTTP byte range request randomAccessFile.seek(ciphertextStart); long initialSkipBytes = ranges.getPlaintextBytesToSkipInitially() + ranges.getCiphertextStartPositionInclusive(); long binaryEndPositionInclusive = ranges.getCiphertextEndPositionInclusive(); long ciphertextRangeMaxBytes = ciphertextSize - ciphertextStart; long ciphertextRangeRequestBytes = binaryEndPositionInclusive - ciphertextStart + 1; /* We then calculate the range length based on the *actual* ciphertext * size so that we are emulating HTTP range requests by returning a * the binary of the actual object (even if the range went beyond). */ long ciphertextByteRangeLength = Math.min(ciphertextRangeMaxBytes, ciphertextRangeRequestBytes); if (unboundedEnd) ciphertextByteRangeLength = ciphertextSize - ciphertextStart; // include MAC byte[] rangedBytes = new byte[(int) ciphertextByteRangeLength]; randomAccessFile.read(rangedBytes); // it's a byte array, close does nothing so skip try-with-resources final ByteArrayInputStream bin = new ByteArrayInputStream(rangedBytes); final ByteArrayInputStream binSpy = Mockito.spy(bin); /* When creating the fake stream, we feed it a content-length equal * to the size of the byte range because that is what Manta would * do. Also, we pass along the incorrect plaintext length and * test how the stream handles incorrect values of plaintext length. */ MantaEncryptedObjectInputStream min = createEncryptedObjectInputStream(key, binSpy, ciphertextByteRangeLength, cipherDetails, encryptedFile.cipher.getIV(), false, (long) this.plaintextSize, initialSkipBytes, plaintextLength, unboundedEnd); byte[] actual = new byte[expected.length]; ReadBytesFactory.fullStrategy(strategy).readBytes(min, actual); min.close(); Mockito.verify(binSpy, Mockito.atLeastOnce()).close(); try { AssertJUnit.assertArrayEquals("Byte range output doesn't match", expected, actual); } catch (AssertionError e) { Assert.fail(String.format("%s\nexpected: %s\nactual : %s", e.getMessage(), new String(expected, StandardCharsets.UTF_8), new String(actual, StandardCharsets.UTF_8))); } } }
From source file:com.mgmtp.jfunk.core.scripting.ScriptContext.java
/** * Runs the specified closure catching any exception that might occur during execution. * /*from w ww. j ava 2 s. c o m*/ * @param closure * the {@link Closure} representing a Groovy block */ @Cmd public void optional(final Closure<Void> closure) { log.info("Executing optional block ..."); try { closure.call(); } catch (final Exception ex) { log.error("Exception executing optional block: " + ex.getMessage(), ex); errors.add(ex); } catch (AssertionError err) { log.error("Assertion failed executing optional block: " + err.getMessage(), err); errors.add(err); } log.info("... finished execution of optional block"); }
From source file:com.htmlhifive.pitalium.core.rules.AssertionView.java
@Override protected void succeeded(Description desc) { // ????ExpectedId if (verifyErrors.isEmpty()) { LOG.info("[Testcase succeeded]"); TestResultManager.getInstance().updateExpectedId(className, methodName); return;//from w w w . ja v a 2 s . c om } LOG.info("[Testcase failed] (verified {} errors)", verifyErrors.size()); TestResultManager.getInstance().cancelUpdateExpectedId(className); String errors = StringUtils .join(FluentIterable.from(verifyErrors).transform(new Function<AssertionError, String>() { @Override public String apply(AssertionError error) { return error.getMessage(); } }).filter(new Predicate<String>() { @Override public boolean apply(String message) { return !Strings.isNullOrEmpty(message); } }), "\n"); throw new AssertionError(String.format(Locale.US, "Verified %d errors: %s", verifyErrors.size(), errors)); }
From source file:org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.ec2.bigdata.RepetativeInstallAndUninstallStockDemoWithProblemAtInstallEc2Test.java
private int installUninstallInstall(String stockdemoAppPath, String cassandraPostStartScriptPath, String newPostStartScriptPath) throws Exception { LogUtils.log("corrupting cassandra service"); corruptCassandraService(cassandraPostStartScriptPath, newPostStartScriptPath); try {/*from w ww . j av a 2 s.c o m*/ LogUtils.log("first installation of stockdemo - this should fail"); installApplicationAndWait(stockdemoAppPath, APPLICATION_NAME, 5, true); } catch (AssertionError e) { return 1; } LogUtils.log("fixing cassandra service"); fixCassandraService(cassandraPostStartScriptPath, newPostStartScriptPath); LogUtils.log("uninstalling stockdemo"); uninstallApplicationAndWait(APPLICATION_NAME); LogUtils.log("asserting all services are down"); assertUninstallWasSuccessful(); try { LogUtils.log("second installation of stockdemo - this should succeed"); installApplicationAndWait(stockdemoAppPath, APPLICATION_NAME, 45, false); LogUtils.log("checking second installation's result"); Assert.assertTrue("The applications home page isn't available, counts as not installed properly", WebUtils.isURLAvailable(stockdemoUrl)); return 2; } catch (AssertionError e) { LogUtils.log(e.getMessage()); return 3; } }
From source file:ru.anr.base.BaseParent.java
/** * Executes something specified in the callback but ignores any exceptions * and writes them to the error log/*from www . j a v a2 s .co m*/ * * @param callback * The callback to use * @param params * A set of parameters */ protected void runIgnored(RunIgnoreErrors callback, Object... params) { try { callback.run(params); } catch (AssertionError ignore) { error("Ignored error: {}", nullSafe(ignore.getMessage())); } catch (RuntimeException ignore) { error("Ignored error: {}", nullSafe(ignore.getMessage())); } catch (Exception ignore) { error("Ignored error: {}", nullSafe(ignore.getMessage())); } }