Example usage for junit.framework AssertionFailedError AssertionFailedError

List of usage examples for junit.framework AssertionFailedError AssertionFailedError

Introduction

In this page you can find the example usage for junit.framework AssertionFailedError AssertionFailedError.

Prototype

public AssertionFailedError(String message) 

Source Link

Usage

From source file:mondrian.test.DiffRepository.java

public void assertEquals(String tag, String expected, String actual, Util.Function1<String, String> filter) {
    final String testCaseName = getCurrentTestCaseName(true);
    String expected2 = expand(tag, expected);
    if (expected2 == null) {
        update(testCaseName, expected, actual);
        throw new AssertionFailedError("reference file does not contain resource '" + expected
                + "' for testcase '" + testCaseName + "'");
    } else {//w w  w .  j  a  v a  2s  . c o  m
        final String expected3;
        if (filter != null) {
            expected3 = filter.apply(expected2);
        } else {
            expected3 = expected2;
        }
        try {
            // TODO jvs 25-Apr-2006:  reuse bulk of
            // DiffTestCase.diffTestLog here; besides newline
            // insensitivity, it can report on the line
            // at which the first diff occurs, which is useful
            // for largish snippets
            String expected2Canonical = Util.replace(expected3, Util.nl, "\n");
            String actualCanonical = Util.replace(actual, Util.nl, "\n");
            Assert.assertEquals(expected2Canonical, actualCanonical);
        } catch (ComparisonFailure e) {
            amend(expected, actual);
            throw e;
        }
    }
}

From source file:org.auraframework.integration.test.util.WebDriverTestCase.java

/**
 * Gather up useful info to add to a test failure. try to get
 * <ul>//from  w ww.j a  v a  2s . c o  m
 * <li>any client js errors</li>
 * <li>last known js test function</li>
 * <li>running/waiting</li>
 * <li>a screenshot</li>
 * </ul>
 *
 * @param originalErr the test failure
 * @throws Throwable a new AssertionFailedError or UnexpectedError with the original and additional info
 */
private Throwable addAuraInfoToTestFailure(Throwable originalErr) {
    StringBuffer description = new StringBuffer();
    if (originalErr != null) {
        String msg = originalErr.getMessage();
        if (msg != null) {
            description.append(msg);
        }
    }

    description.append(String.format("\nBrowser: %s", currentBrowserType));
    if (getAuraUITestingUtil() != null) {
        description.append("\nUser-Agent: " + getAuraUITestingUtil().getUserAgent());
    }
    if (currentDriver == null) {
        description.append("\nTest failed before WebDriver was initialized");
    } else {

        if (this instanceof PerfExecutorTestCase) {
            JSONArray json = this.getLastCollectedMetrics();
            description.append("\nPerfMetrics: " + json + ';');
        }

        description.append("\nWebDriver: " + currentDriver);
        description.append("\nJS state: ");
        try {
            String dump = (String) getAuraUITestingUtil()
                    .getRawEval("return (window.$A && $A.test && $A.test.getDump())||'';");
            if (dump.isEmpty()) {
                description.append("no errors detected");
            } else {
                description.append(dump);
            }
        } catch (Throwable t) {
            description.append(t.getMessage());
        }

        String screenshotsDirectory = System.getProperty("screenshots.directory");
        if (screenshotsDirectory != null) {
            String screenshot = null;
            TakesScreenshot ts = (TakesScreenshot) currentDriver;
            try {
                screenshot = ts.getScreenshotAs(OutputType.BASE64);
            } catch (WebDriverException e) {
                description.append(String.format("%nScreenshot: {capture error: %s}", e.getMessage()));
            }

            if (screenshot != null) {
                String fileName = getClass().getName() + "." + getName() + "_" + currentBrowserType + ".png";
                try {
                    File path = new File(screenshotsDirectory + "/" + fileName);
                    path.getParentFile().mkdirs();
                    byte[] bytes = Base64.decodeBase64(screenshot.getBytes());
                    FileOutputStream fos = new FileOutputStream(path);
                    fos.write(bytes);
                    fos.close();
                    String baseUrl = System.getProperty("screenshots.baseurl");
                    description.append(String.format("%nScreenshot: %s/%s", baseUrl, fileName));
                } catch (Throwable t) {
                    description.append(String.format("%nScreenshot: {save error: %s}", t.getMessage()));
                }
            }
        }

        try {
            description.append("\nApplication cache status: ");
            description.append(getAuraUITestingUtil().getRawEval(
                    "var cache=window.applicationCache;return (cache===undefined || cache===null)?'undefined':cache.status;")
                    .toString());
        } catch (Exception ex) {
            description.append("error calculating status: " + ex);
        }
        description.append("\n");
        if (SauceUtil.areTestsRunningOnSauce()) {
            String linkToJob = SauceUtil.getLinkToPublicJobInSauce(currentDriver);
            description.append("\nSauceLabs-recording: ");
            description.append((linkToJob != null) ? linkToJob : "{not available}");
        }
    }

    // replace original exception with new exception with additional info
    Throwable newFailure;
    if (originalErr instanceof AssertionFailedError) {
        newFailure = new AssertionFailedError(description.toString());
    } else {
        description.insert(0, originalErr.getClass() + ": ");
        newFailure = new UnexpectedError(description.toString(), originalErr.getCause());
    }
    newFailure.setStackTrace(originalErr.getStackTrace());
    return newFailure;
}

From source file:io.realm.RealmTest.java

public void testCloseRealmInDifferentThread() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final AssertionFailedError threadAssertionError[] = new AssertionFailedError[1];

    final Thread thatThread = new Thread(new Runnable() {
        @Override//from   w w  w .  ja  v  a  2s . c o  m
        public void run() {
            try {
                testRealm.close();
                threadAssertionError[0] = new AssertionFailedError(
                        "Close realm in a different thread should throw IllegalStateException.");
            } catch (IllegalStateException ignored) {
            }
            latch.countDown();
        }
    });
    thatThread.start();

    // Timeout should never happen
    latch.await();
    if (threadAssertionError[0] != null) {
        throw threadAssertionError[0];
    }
    // After exception thrown in another thread, nothing should be changed to the realm in this thread.
    testRealm.checkIfValid();
    testRealm.close();
}

From source file:io.realm.RealmTests.java

@Test
public void close_differentThread() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final AssertionFailedError threadAssertionError[] = new AssertionFailedError[1];

    final Thread thatThread = new Thread(new Runnable() {
        @Override/*from   w  w w.j a v a  2s  .c  om*/
        public void run() {
            try {
                realm.close();
                threadAssertionError[0] = new AssertionFailedError(
                        "Close realm in a different thread should throw IllegalStateException.");
            } catch (IllegalStateException ignored) {
            }
            latch.countDown();
        }
    });
    thatThread.start();

    // Timeout should never happen
    latch.await();
    if (threadAssertionError[0] != null) {
        throw threadAssertionError[0];
    }
    // After exception thrown in another thread, nothing should be changed to the realm in this thread.
    realm.checkIfValid();
    realm.close();
    realm = null;
}

From source file:io.realm.RealmTests.java

@Test
public void isClosed_differentThread() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final AssertionFailedError threadAssertionError[] = new AssertionFailedError[1];

    final Thread thatThread = new Thread(new Runnable() {
        @Override//from w  ww .  java 2  s . c  o m
        public void run() {
            try {
                realm.isClosed();
                threadAssertionError[0] = new AssertionFailedError(
                        "Call isClosed() of Realm instance in a different thread should throw IllegalStateException.");
            } catch (IllegalStateException ignored) {
            }
            latch.countDown();
        }
    });
    thatThread.start();

    // Timeout should never happen
    latch.await();
    if (threadAssertionError[0] != null) {
        throw threadAssertionError[0];
    }
    // After exception thrown in another thread, nothing should be changed to the realm in this thread.
    realm.checkIfValid();
    assertFalse(realm.isClosed());
    realm.close();
}

From source file:com.scvngr.levelup.ui.activity.TestIntentActivity.java

/**
 * Waits for {@link #onActivityResult} to be called, then returns the result.
 *
 * @return the result that was delivered from the other activity.
 * @throws AssertionFailedError if the callback isn't called or is interrupted.
 *//*from  w  w  w.j ava  2 s  . com*/
@Nullable
public final Instrumentation.ActivityResult waitForActivityResult() throws AssertionFailedError {
    try {
        if (!mOnActivityResultLatch.await(RESULT_WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
            throw new AssertionFailedError("onActivityResult was not called.");
        }
    } catch (final InterruptedException e) {
        final AssertionFailedError assertionFailed = new AssertionFailedError("Latch interrupted.");
        assertionFailed.initCause(e);

        throw assertionFailed;
    }

    return mActivityResult;
}

From source file:org.apache.ddlutils.DatabaseTestHelper.java

/**
 * Asserts that the data in the tables described by the given model is the same in the
 * database accessed by the second platform as is in the database accessed by the first platform.
 * Note that it is not tested whether the second database has more data.<br/>
 * All differences will be printed via logging in DEBUG level.
 * //  w  w  w . ja v a 2s  .c o  m
 * @param failureMsg        The failure message to issue if the data is not the same
 * @param model             The database model to check
 * @param origDbPlatform    The first platform
 * @param testedDbPlatform  The second platform
 */
public void assertHasSameData(String failureMsg, Database model, Platform origDbPlatform,
        Platform testedDbPlatform) {
    boolean hasError = false;

    for (int idx = 0; idx < model.getTableCount(); idx++) {
        Table table = model.getTable(idx);
        Column[] pkCols = table.getPrimaryKeyColumns();

        for (Iterator it = origDbPlatform.query(model, buildQueryString(origDbPlatform, table, null, null),
                new Table[] { table }); it.hasNext();) {
            DynaBean obj = (DynaBean) it.next();
            Collection result = testedDbPlatform.fetch(model,
                    buildQueryString(origDbPlatform, table, pkCols, obj), new Table[] { table });

            if (result.isEmpty()) {
                if (_log.isDebugEnabled()) {
                    hasError = true;
                    _log.debug("Row " + obj.toString() + " is not present in second database");
                } else {
                    throw new AssertionFailedError(failureMsg);
                }
            } else if (result.size() > 1) {
                if (_log.isDebugEnabled()) {
                    hasError = true;

                    StringBuffer debugMsg = new StringBuffer();

                    debugMsg.append("Row ");
                    debugMsg.append(obj.toString());
                    debugMsg.append(" is present more than once in the second database:\n");
                    for (Iterator resultIt = result.iterator(); resultIt.hasNext();) {
                        debugMsg.append("  ");
                        debugMsg.append(resultIt.next().toString());
                    }
                    _log.debug(debugMsg.toString());
                } else {
                    throw new AssertionFailedError(failureMsg);
                }
            } else {
                DynaBean otherObj = (DynaBean) result.iterator().next();

                if (!obj.equals(otherObj)) {
                    if (_log.isDebugEnabled()) {
                        hasError = true;

                        _log.debug("Row " + obj.toString() + " is different in the second database: "
                                + otherObj.toString());
                    } else {
                        throw new AssertionFailedError(failureMsg);
                    }
                }
            }
        }
    }
    if (hasError) {
        throw new AssertionFailedError(failureMsg);
    }
}

From source file:org.apache.hadoop.dfs.ClusterTestDFSNamespaceLogging.java

private void testFsPseudoDistributed(int datanodeNum) throws Exception {
    try {/*from w ww .  ja  v a  2s .  c  om*/
        prepareTempFileSpace();

        configureDFS();
        startDFS(datanodeNum);

        if (logfh == null)
            try {
                logfh = new BufferedReader(new FileReader(logFile));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                throw new AssertionFailedError("Log file does not exist: " + logFile);
            }

        // create a directory
        try {
            assertTrue(dfsClient.mkdirs("/data"));
            assertMkdirs("/data", false);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        try {
            assertTrue(dfsClient.mkdirs("data"));
            assertMkdirs("data", true);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        //
        // create a file with 1 data block
        try {
            createFile("/data/xx", 1);
            assertCreate("/data/xx", 1, false);
        } catch (IOException ioe) {
            assertCreate("/data/xx", 1, true);
        }

        // create a file with 2 data blocks
        try {
            createFile("/data/yy", BLOCK_SIZE + 1);
            assertCreate("/data/yy", BLOCK_SIZE + 1, false);
        } catch (IOException ioe) {
            assertCreate("/data/yy", BLOCK_SIZE + 1, true);
        }

        // create an existing file
        try {
            createFile("/data/xx", 2);
            assertCreate("/data/xx", 2, false);
        } catch (IOException ioe) {
            assertCreate("/data/xx", 2, true);
        }

        // delete the file
        try {
            dfsClient.delete("/data/yy", true);
            assertDelete("/data/yy", false);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        // rename the file
        try {
            dfsClient.rename("/data/xx", "/data/yy");
            assertRename("/data/xx", "/data/yy", false);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        try {
            dfsClient.delete("/data/xx", true);
            assertDelete("/data/xx", true);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        try {
            dfsClient.rename("/data/xx", "/data/yy");
            assertRename("/data/xx", "/data/yy", true);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    } catch (AssertionFailedError afe) {
        afe.printStackTrace();
        throw afe;
    } catch (Throwable t) {
        msg("Unexpected exception_a: " + t);
        t.printStackTrace();
    } finally {
        shutdownDFS();

    }
}

From source file:org.apache.hadoop.dfs.ClusterTestDFSNamespaceLogging.java

private void assertHasLogged(String target, int headerLen) {
    String line;/*from  w w  w  .  j  av  a2  s  .  c  o m*/
    boolean notFound = true;
    try {
        while (notFound && (line = logfh.readLine()) != null) {
            if (line.length() > headerLen && line.startsWith(target, headerLen))
                notFound = false;
        }
    } catch (java.io.IOException e) {
        throw new AssertionFailedError("error reading the log file");
    }
    if (notFound) {
        throw new AssertionFailedError(target + " not logged");
    }
}

From source file:org.apache.hadoop.hbase.client.TestMetaMigrationRemovingHTD.java

public static void assertEquals(int expected, int actual) {
    if (expected != actual) {
        throw new AssertionFailedError("expected:<" + expected + "> but was:<" + actual + ">");
    }/*from www  .  ja  va2s . c o  m*/
}