Example usage for java.lang AssertionError getMessage

List of usage examples for java.lang AssertionError getMessage

Introduction

In this page you can find the example usage for java.lang AssertionError getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.alliander.osgp.acceptancetests.adhocmanagement.SetTransitionSteps.java

@DomainStep("the set transition request should return result (.*)")
public boolean thenTheRequestShouldReturn(final String result) {
    LOGGER.info("THEN: the set transition request should return {}.", result);

    if (result.toUpperCase().equals("OK")) {
        try {//from   www  .  j  a v  a  2s .c  o 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:org.assertj.examples.IterableAssertionsExamples.java

@Test
public void iterable_basic_contains_exactly_assertions_examples() {
    Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
    assertThat(elvesRings).containsExactly(vilya, nenya, narya).containsExactlyInAnyOrder(vilya, nenya, narya)
            .containsExactlyInAnyOrder(nenya, vilya, narya);

    // It works with collections that have a consistent iteration order
    SortedSet<Ring> elvesRingsSet = new TreeSet<Ring>();
    elvesRingsSet.add(vilya);//from  w w  w  . ja va  2s . c o m
    elvesRingsSet.add(nenya);
    elvesRingsSet.add(narya);
    assertThat(elvesRingsSet).containsExactly(vilya, nenya, narya);

    // Expected values can be given by another Iterable.
    assertThat(elvesRings).containsExactlyElementsOf(elvesRingsSet);

    try {
        // putting a different order would make the assertion fail :
        assertThat(elvesRings).containsExactly(nenya, vilya, narya);
    } catch (AssertionError e) {
        logger.info(e.getMessage());
        logAssertionErrorMessage("containsExactly", e);
    }

    try {
        List<String> z = newArrayList("a", "a", "a");
        assertThat(z).containsExactly("a", "a");
    } catch (AssertionError e) {
        logAssertionErrorMessage("containsExactly with same elements appearing several time", e);
    }

    try {
        // putting a different order would make the assertion fail :
        assertThat(newArrayList(narya, vilya, nenya)).containsExactlyElementsOf(elvesRingsSet);
    } catch (AssertionError e) {
        logger.info(e.getMessage());
        logAssertionErrorMessage("containsExactlyElementsOf with elements in different order", e);
    }
}

From source file:org.apache.hadoop.hive.ql.io.HiveContextAwareRecordReader.java

public boolean doNext(K key, V value) throws IOException {
    if (this.isSorted) {
        if (this.getIOContext().shouldEndBinarySearch()
                || (!this.getIOContext().useSorted() && this.wasUsingSortedSearch)) {
            beginLinearSearch();//from w  w  w. ja va 2s.c  om
            this.wasUsingSortedSearch = false;
            this.getIOContext().setEndBinarySearch(false);
        }

        if (this.getIOContext().useSorted()) {
            if (this.genericUDFClassName == null && this.getIOContext().getGenericUDFClassName() != null) {
                setGenericUDFClassName(this.getIOContext().getGenericUDFClassName());
            }

            if (this.getIOContext().isBinarySearching()) {
                // Proceed with a binary search
                if (this.getIOContext().getComparison() != null) {
                    switch (this.getIOContext().getComparison()) {
                    case GREATER:
                    case EQUAL:
                        // Indexes have only one entry per value, could go linear from here, if we want to
                        // use this for any sorted table, we'll need to continue the search
                        rangeEnd = previousPosition;
                        break;
                    case LESS:
                        rangeStart = previousPosition;
                        break;
                    default:
                        break;
                    }
                }

                long position = (rangeStart + rangeEnd) / 2;
                sync(position);

                long newPosition = getSyncedPosition();
                // If the newPosition is the same as the previousPosition, we've reached the end of the
                // binary search, if the new position at least as big as the size of the split, any
                // matching rows must be in the final block, so we can end the binary search.
                if (newPosition == previousPosition || newPosition >= splitEnd) {
                    this.getIOContext().setBinarySearching(false);
                    sync(rangeStart);
                }

                previousPosition = newPosition;
            } else if (foundAllTargets()) {
                // Found all possible rows which will not be filtered
                return false;
            }
        }
    }

    try {

        /**
         * When start reading new file, check header, footer rows.
         * If file contains header, skip header lines before reading the records.
         * If file contains footer, used a FooterBuffer to remove footer lines
         * at the end of the table file.
         **/
        if (this.ioCxtRef.getCurrentBlockStart() == 0) {

            // Check if the table file has header to skip.
            Path filePath = this.ioCxtRef.getInputPath();
            PartitionDesc part = null;
            try {
                if (pathToPartitionInfo == null) {
                    pathToPartitionInfo = Utilities.getMapWork(jobConf).getPathToPartitionInfo();
                }
                part = HiveFileFormatUtils.getPartitionDescFromPathRecursively(pathToPartitionInfo, filePath,
                        IOPrepareCache.get().getPartitionDescMap());
            } catch (AssertionError ae) {
                LOG.info("Cannot get partition description from " + this.ioCxtRef.getInputPath() + "because "
                        + ae.getMessage());
                part = null;
            } catch (Exception e) {
                LOG.info("Cannot get partition description from " + this.ioCxtRef.getInputPath() + "because "
                        + e.getMessage());
                part = null;
            }
            TableDesc table = (part == null) ? null : part.getTableDesc();
            if (table != null) {
                headerCount = Utilities.getHeaderCount(table);
                footerCount = Utilities.getFooterCount(table, jobConf);
            }

            // If input contains header, skip header.
            if (!Utilities.skipHeader(recordReader, headerCount, (WritableComparable) key, (Writable) value)) {
                return false;
            }
            if (footerCount > 0) {
                footerBuffer = new FooterBuffer();
                if (!footerBuffer.initializeBuffer(jobConf, recordReader, footerCount, (WritableComparable) key,
                        (Writable) value)) {
                    return false;
                }
            }
        }
        if (footerBuffer == null) {

            // Table files don't have footer rows.
            return recordReader.next(key, value);
        } else {
            return footerBuffer.updateBuffer(jobConf, recordReader, (WritableComparable) key, (Writable) value);
        }
    } catch (Exception e) {
        return HiveIOExceptionHandlerUtil.handleRecordReaderNextException(e, jobConf);
    }
}

From source file:com.gatf.executor.validator.ResponseValidator.java

public void validate(Response response, TestCase testCase, TestCaseReport testCaseReport,
        AcceptanceTestContext context) {
    try {//w ww.j a v  a  2  s . c  o m
        Object intObj = getInternalObject(testCaseReport);
        if (intObj != null && testCase.getAexpectedNodes() != null && !testCase.getAexpectedNodes().isEmpty()) {
            for (String node : testCase.getAexpectedNodes()) {
                List<String> nodeProps = getNodeProperties(node);

                String nodeVal = null;
                if (nodeProps.size() == 1 || !hasValidationFunction(nodeProps.get(0))) {
                    nodeVal = getNodeValue(intObj, nodeProps.get(0));
                    Assert.assertNotNull("Expected Node value for " + nodeProps.get(0) + " is null", nodeVal);
                }
                if (nodeProps.size() > 1) {
                    String lhs = nodeProps.get(0);
                    String lhsv = nodeVal;
                    String oper = nodeProps.size() > 2 ? nodeProps.get(1) : "==";
                    String rhsv = nodeProps.get(nodeProps.size() - 1);
                    doNodeLevelValidation(lhs, lhsv, oper, rhsv, context, testCase, testCaseReport);
                }
            }
        }

        if (testCase.getRepeatScenarios() == null && testCase.getRepeatScenarioProviderName() == null) {
            validateLogicalConditions(testCase, context, null);
        }

        extractWorkflowVariables(testCase, testCaseReport, intObj, context);

        List<Cookie> cookies = response.getCookies();
        context.getWorkflowContextHandler().storeCookies(testCase, cookies);

        boolean authEnabled = testCase.isServerApiAuth()
                ? context.getGatfExecutorConfig().isServerLogsApiAuthEnabled()
                : context.getGatfExecutorConfig().isAuthEnabled();
        String authUrl = testCase.isServerApiAuth() ? testCase.getUrl()
                : context.getGatfExecutorConfig().getAuthUrl();
        String[] authExtractAuthParams = testCase.isServerApiAuth()
                ? context.getGatfExecutorConfig().getServerApiAuthExtractAuthParams()
                : context.getGatfExecutorConfig().getAuthExtractAuthParams();

        if (authEnabled && authUrl.equals(testCase.getUrl())) {
            String identifier = null;
            String authext = "";
            if (authExtractAuthParams[1].equalsIgnoreCase("cookie")) {
                authext = "cookie ";
                for (Cookie cookie : cookies) {
                    if (authExtractAuthParams[0].equals(cookie.getName())) {
                        identifier = cookie.getValue();
                        break;
                    }
                }
            } else if (authExtractAuthParams[1].equalsIgnoreCase("header")) {
                authext = "header ";
                identifier = response.getHeader(authExtractAuthParams[0]);
            } else {
                authext = "response-content ";
                identifier = getNodeValue(intObj, authExtractAuthParams[0]);
            }
            Assert.assertNotNull(
                    "Authentication token not found for " + authext + "(" + authExtractAuthParams[0] + ")",
                    identifier);
            context.setSessionIdentifier(identifier, testCase);
            context.getWorkflowContextHandler().getSuiteWorkflowContext(testCase).put(authExtractAuthParams[2],
                    identifier);
            Assert.assertNotNull("Authentication token is null", context.getSessionIdentifier(testCase));
        }
        testCaseReport.setStatus(TestStatus.Success.status);
    } catch (AssertionError e) {
        testCaseReport.setStatus(TestStatus.Failed.status);
        testCaseReport.setFailureReason(TestFailureReason.NodeValidationFailed.status);
        testCaseReport.setError(e.getMessage());
        testCaseReport.setErrorText(ExceptionUtils.getStackTrace(e));
        if (e.getMessage() == null && testCaseReport.getErrorText() != null
                && testCaseReport.getErrorText().indexOf("\n") != -1) {
            testCaseReport.setError(
                    testCaseReport.getErrorText().substring(0, testCaseReport.getErrorText().indexOf("\n")));
        }
        e.printStackTrace();
    } catch (Throwable e) {
        testCaseReport.setStatus(TestStatus.Failed.status);
        testCaseReport.setFailureReason(TestFailureReason.Exception.status);
        testCaseReport.setError(e.getMessage());
        testCaseReport.setErrorText(ExceptionUtils.getStackTrace(e));
        if (e.getMessage() == null && testCaseReport.getErrorText() != null
                && testCaseReport.getErrorText().indexOf("\n") != -1) {
            testCaseReport.setError(
                    testCaseReport.getErrorText().substring(0, testCaseReport.getErrorText().indexOf("\n")));
        }
        e.printStackTrace();
    }
}

From source file:org.jahia.test.services.render.filter.cache.base.CacheFilterHttpTest.java

private void testACLs(String path) throws Exception {
    List<String> users = Arrays.asList(null, "root", "userAB", "userAC");

    List<List<String>> allPerms = new ArrayList<>();
    permute(users, 0, allPerms);/*  w  w w  .  j  a va 2 s .  com*/

    Map<String, String> results = new HashMap<>();

    for (List<String> allPerm : allPerms) {
        results.clear();
        clearAll();

        for (String user : allPerm) {
            results.put(user, getContent(getUrl(path), user, getPassword(user), null));
        }

        try {
            checkAcl(allPerm + ", guest : ", results.get(null),
                    new boolean[] { false, false, false, false, false, false, false, false });
            checkAcl(allPerm + ", root : ", results.get("root"),
                    new boolean[] { true, true, true, true, true, true, true, true });
            checkAcl(allPerm + ", userAB : ", results.get("userAB"),
                    new boolean[] { false, true, true, false, false, true, true, false });
            checkAcl(allPerm + ", userAC : ", results.get("userAC"),
                    new boolean[] { false, true, false, false, true, true, false, true });
        } catch (AssertionError e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
    }

    JCRSessionWrapper session = JCRSessionFactory.getInstance().getCurrentUserSession("live", new Locale("en"));
    JCRNodeWrapper n = session.getNode(path + "/main/simple-text-A");
    JCRNodeWrapper n2 = session.getNode(path + "/simple-page-A");
    try {
        n.revokeRolesForPrincipal("g:groupA");
        n.grantRoles("g:groupB", new HashSet<String>(Arrays.asList("reader")));
        n2.revokeRolesForPrincipal("g:groupA");
        n2.grantRoles("g:groupB", new HashSet<String>(Arrays.asList("reader")));
        session.save();

        Map<String, String> results2 = new HashMap<>();

        for (String user : users) {
            results2.put(user, getContent(getUrl(path), user, getPassword(user), null));
        }
        checkAcl(users + ", guest : ", results2.get(null),
                new boolean[] { false, false, false, false, false, false, false, false });
        checkAcl(users + ", root : ", results2.get("root"),
                new boolean[] { true, true, true, true, true, true, true, true });
        checkAcl(users + ", userAB : ", results2.get("userAB"),
                new boolean[] { false, true, true, false, false, true, true, false });
        checkAcl(users + ", userAC : ", results2.get("userAC"),
                new boolean[] { false, true, false, false, true, false, false, true });
    } finally {
        n.revokeRolesForPrincipal("g:groupB");
        n.grantRoles("g:groupA", new HashSet<String>(Arrays.asList("reader")));
        n2.revokeRolesForPrincipal("g:groupB");
        n2.grantRoles("g:groupA", new HashSet<String>(Arrays.asList("reader")));
        session.save();
    }

    for (String user : users) {
        assertEquals("Content served is not the same for " + user, results.get(user),
                getContent(getUrl(path), user, getPassword(user), null));
    }
}

From source file:fr.landel.utils.assertor.OperatorTest.java

/**
 * Test combination./* w  w w  . ja va 2  s  .c o m*/
 */
@Test
public void test() {
    // "true" and "OR" => true (collections preconditions are invalid, but
    // aren't checked because of previous check)
    try {
        Assertor.that(true).isTrue().or(Collections.emptyList()).contains("test").orElseThrow(JUNIT_THROWABLE);
    } catch (AssertionError e) {
        fail(e.getMessage());
    }
}

From source file:org.apache.geode.management.internal.cli.commands.GfshCommandJUnitTest.java

@Test(expected = AssertionError.class)
public void testReadPidWithNull() {
    try {/*from w  w w.ja  v  a 2  s  .  c  o m*/
        StartMemberUtils.readPid(null);
    } catch (AssertionError expected) {
        assertEquals("The file from which to read the process ID (pid) cannot be null!", expected.getMessage());
        throw expected;
    }
}

From source file:com.xtructure.xutil.valid.UTestValidateUtils.java

public void assertThatWithOnePredicateBehavesAsExpected() {
    String assertionName = RandomStringUtils.randomAlphanumeric(10);
    boolean valid = assertThat(assertionName, new Object(), isNotNull());
    if (!valid) {
        throw new AssertionError();
    }/*from  w w  w .j a  v a2 s . co m*/
    try {
        assertThat(assertionName, null, isNotNull());
    } catch (AssertionError e) {
        if (!String.format("%s (%s): %s", assertionName, null, isNotNull()).equals(e.getMessage())) {
            throw new AssertionError();
        }
    }
}

From source file:com.xtructure.xutil.valid.UTestValidateUtils.java

public void assertThatWithMultiplePredicatesBehavesAsExpected() {
    String assertionName = RandomStringUtils.randomAlphanumeric(10);
    boolean valid = assertThat(assertionName, new Object(), isNotNull(), isNotNull());
    if (!valid) {
        throw new AssertionError();
    }/* w  w w . j  a va 2  s  . co m*/
    try {
        assertThat(assertionName, null, isNotNull(), isNotNull());
    } catch (AssertionError e) {
        if (!String.format("%s (%s): %s", assertionName, null, isNotNull()).equals(e.getMessage())) {
            throw new AssertionError();
        }
    }
}

From source file:com.xtructure.xutil.valid.UTestValidateUtils.java

public void assertThatWithValidationStrategyBehavesAsExpected() {
    String assertionName = RandomStringUtils.randomAlphanumeric(10);
    TestValidationStrategy<Object> validationStrategy = new TestValidationStrategy<Object>(isNotNull());
    boolean valid = assertThat(assertionName, new Object(), validationStrategy);
    if (!valid) {
        throw new AssertionError();
    }/*from w w w .jav  a2s. co  m*/
    try {
        assertThat(assertionName, null, validationStrategy);
    } catch (AssertionError e) {
        if (!String.format("%s (%s): %s", assertionName, null, isNotNull()).equals(e.getMessage())) {
            throw new AssertionError();
        }
    }
}