Java Examples for org.junit.ComparisonFailure

The following java examples will help you to understand the usage of org.junit.ComparisonFailure. These source code samples are taken from different open source projects.

Example 1
Project: hibernate-tools-master  File: JUnitUtilTest.java View source code
@Test
public void testAssertIteratorContainsExactly() {
    ArrayList<String> list = new ArrayList<String>();
    list.add("foo");
    list.add("bar");
    try {
        JUnitUtil.assertIteratorContainsExactly("less", list.iterator(), 1);
        Assert.fail();
    } catch (ComparisonFailure e) {
        Assert.assertTrue(e.getMessage().contains("less"));
    }
    try {
        JUnitUtil.assertIteratorContainsExactly("more", list.iterator(), 3);
        Assert.fail();
    } catch (ComparisonFailure e) {
        Assert.assertTrue(e.getMessage().contains("more"));
    }
    try {
        JUnitUtil.assertIteratorContainsExactly("exact", list.iterator(), 2);
        Assert.assertTrue(true);
    } catch (ComparisonFailure e) {
        Assert.fail();
    }
}
Example 2
Project: intellij-community-master  File: JUnitTreeByDescriptionHierarchyTest.java View source code
@Test
public void testLongOutputPreservesTestName() throws Exception {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < 1000; i++) {
        buf.append(DebugUtil.currentStackTrace());
    }
    final StringBuffer output = new StringBuffer();
    final JUnit4TestListener sender = createListener(output);
    final Description description = Description.createTestDescription("A", "a");
    sender.testFailure(new Failure(description, new ComparisonFailure(buf.toString(), buf.toString(), "diff" + buf.toString())));
    final String startMessage = "##teamcity[enteredTheMatrix]\n\n" + "##teamcity[testFailed name='A.a' ";
    assertEquals(startMessage, StringUtil.convertLineSeparators(output.toString()).substring(0, startMessage.length()));
}
Example 3
Project: consulo-master  File: ComparisonFailureData.java View source code
private static String get(final Throwable assertion, final Map staticMap, final String fieldName) throws IllegalAccessException, NoSuchFieldException {
    String actual;
    if (assertion instanceof ComparisonFailure) {
        actual = (String) ((Field) staticMap.get(ComparisonFailure.class)).get(assertion);
    } else if (assertion instanceof org.junit.ComparisonFailure) {
        actual = (String) ((Field) staticMap.get(org.junit.ComparisonFailure.class)).get(assertion);
    } else {
        Field field = assertion.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        actual = (String) field.get(assertion);
    }
    return actual;
}
Example 4
Project: eclipse.jdt.ui-master  File: TestRunListenerTest4.java View source code
public void testSimpleTest() throws Exception {
    String source = "package pack;\n" + "import org.junit.Test;\n" + "import org.junit.FixMethodOrder;\n" + "import org.junit.runners.MethodSorters;\n" + "import static org.junit.Assert.*;\n" + "\n" + "@FixMethodOrder(MethodSorters.NAME_ASCENDING)\n" + "public class ATestCase {\n" + "	protected int fValue1;\n" + "	protected int fValue2;\n" + "\n" + "	protected void setUp() {\n" + "		fValue1= 2;\n" + "		fValue2= 3;\n" + "	}\n" + "	@Test public void testAdd() {\n" + "		double result= fValue1 + fValue2;\n" + "		// forced failure result == 5\n" + "		assertTrue(result == 6);\n" + "	}\n" + "	@Test public void testDivideByZero() {\n" + "		int zero= 0;\n" + "		int result= 8/zero;\n" + "	}\n" + "	@Test public void testEquals() {\n" + "		assertEquals(12, 12);\n" + "		assertEquals(12L, 12L);\n" + "		assertEquals(new Long(12), new Long(12));\n" + "\n" + "		assertEquals(\"Size\", String.valueOf(12), String.valueOf(13));\n" + "	}\n" + "}";
    IType aTestCase = createType(source, "pack", "ATestCase.java");
    String[] expectedSequence = new String[] { "sessionStarted-" + TestRunListeners.sessionAsString("ATestCase", ProgressState.RUNNING, Result.UNDEFINED, 0), "testCaseStarted-" + TestRunListeners.testCaseAsString("testAdd", "pack.ATestCase", ProgressState.RUNNING, Result.UNDEFINED, null, 0), "testCaseFinished-" + TestRunListeners.testCaseAsString("testAdd", "pack.ATestCase", ProgressState.COMPLETED, Result.FAILURE, new FailureTrace("java.lang.AssertionError", null, null), 0), "testCaseStarted-" + TestRunListeners.testCaseAsString("testDivideByZero", "pack.ATestCase", ProgressState.RUNNING, Result.UNDEFINED, null, 0), "testCaseFinished-" + TestRunListeners.testCaseAsString("testDivideByZero", "pack.ATestCase", ProgressState.COMPLETED, Result.ERROR, new FailureTrace("java.lang.ArithmeticException", null, null), 0), "testCaseStarted-" + TestRunListeners.testCaseAsString("testEquals", "pack.ATestCase", ProgressState.RUNNING, Result.UNDEFINED, null, 0), "testCaseFinished-" + TestRunListeners.testCaseAsString("testEquals", "pack.ATestCase", ProgressState.COMPLETED, Result.FAILURE, new FailureTrace("org.junit.ComparisonFailure", "12", "13"), 0), "sessionFinished-" + TestRunListeners.sessionAsString("ATestCase", ProgressState.COMPLETED, Result.ERROR, 0) };
    String[] actual = runSequenceTest(aTestCase);
    assertEqualLog(expectedSequence, actual);
}
Example 5
Project: org.openntf.domino-master  File: JUnit4TestListener.java View source code
@Override
public void testFailure(Failure failure) throws Exception {
    TestReferenceFailure testReferenceFailure;
    try {
        Throwable exception = failure.getException();
        String status = exception instanceof AssertionError ? MessageIds.TEST_FAILED : MessageIds.TEST_ERROR;
        FailedComparison comparison = null;
        if (exception instanceof junit.framework.ComparisonFailure) {
            junit.framework.ComparisonFailure comparisonFailure = (junit.framework.ComparisonFailure) exception;
            comparison = new FailedComparison(comparisonFailure.getExpected(), comparisonFailure.getActual());
        } else if (exception instanceof org.junit.ComparisonFailure) {
            org.junit.ComparisonFailure comparisonFailure = (org.junit.ComparisonFailure) exception;
            comparison = new FailedComparison(comparisonFailure.getExpected(), comparisonFailure.getActual());
        }
        testReferenceFailure = new TestReferenceFailure(getIdentifier(failure.getDescription()), status, failure.getTrace(), comparison);
    } catch (RuntimeException e) {
        StringWriter stringWriter = new StringWriter();
        e.printStackTrace(new PrintWriter(stringWriter));
        testReferenceFailure = new TestReferenceFailure(getIdentifier(failure.getDescription()), MessageIds.TEST_FAILED, stringWriter.getBuffer().toString(), null);
    }
    fNotified.notifyTestFailed(testReferenceFailure);
}
Example 6
Project: substeps-eclipse-plugin-master  File: JUnit4TestListener.java View source code
@Override
public void testFailure(final Failure failure) throws Exception {
    TestReferenceFailure testReferenceFailure;
    try {
        final Throwable exception = failure.getException();
        final String status = exception instanceof AssertionError ? MessageIds.TEST_FAILED : MessageIds.TEST_ERROR;
        FailedComparison comparison = null;
        if (exception instanceof junit.framework.ComparisonFailure) {
            final junit.framework.ComparisonFailure comparisonFailure = (junit.framework.ComparisonFailure) exception;
            comparison = new FailedComparison(comparisonFailure.getExpected(), comparisonFailure.getActual());
        } else if (exception instanceof org.junit.ComparisonFailure) {
            final org.junit.ComparisonFailure comparisonFailure = (org.junit.ComparisonFailure) exception;
            comparison = new FailedComparison(comparisonFailure.getExpected(), comparisonFailure.getActual());
        }
        testReferenceFailure = new TestReferenceFailure(getIdentifier(failure.getDescription()), status, failure.getTrace(), comparison);
    } catch (final RuntimeException e) {
        final StringWriter stringWriter = new StringWriter();
        e.printStackTrace(new PrintWriter(stringWriter));
        testReferenceFailure = new TestReferenceFailure(getIdentifier(failure.getDescription()), MessageIds.TEST_FAILED, stringWriter.getBuffer().toString(), null);
    }
    notified.notifyTestFailed(testReferenceFailure);
}
Example 7
Project: fest-assert-1.x-master  File: FailureMessages.java View source code
@Nonnull
static String notEqual(String description, Object actual, Object expected) {
    String d = inBrackets(description);
    String a = toStringOf(actual);
    String e = toStringOf(expected);
    boolean isArray = isArray(actual) || isArray(expected);
    if (!isArray) {
        return new ComparisonFailure(d, e, a).getMessage();
    }
    d = addSpaceIfNotEmpty(d);
    return String.format("%sexpected:<%s> but was:<%s>", d, e, a);
}
Example 8
Project: jedis-master  File: AssertUtil.java View source code
public static void assertByteArraySetEquals(Set<byte[]> expected, Set<byte[]> actual) {
    assertEquals(expected.size(), actual.size());
    Iterator<byte[]> e = expected.iterator();
    while (e.hasNext()) {
        byte[] next = e.next();
        boolean contained = false;
        for (byte[] element : expected) {
            if (Arrays.equals(next, element)) {
                contained = true;
            }
        }
        if (!contained) {
            throw new ComparisonFailure("element is missing", Arrays.toString(next), actual.toString());
        }
    }
}
Example 9
Project: mockito-cookbook-master  File: MeanTaxFactorCalculatorTest.java View source code
@Test(expected = ComparisonFailure.class)
public void should_calculate_mean_tax_factor() {
    // given
    TaxService taxService = given(Mockito.mock(TaxService.class).performAdditionalCalculation()).willReturn(UNUSED_VALUE).getMock();
    MeanTaxFactorCalculator systemUnderTest = new MeanTaxFactorCalculator(taxService);
    // when
    double meanTaxFactor = systemUnderTest.calculateMeanTaxFactorFor(new Person());
    // then
    then(meanTaxFactor).isEqualTo(UNUSED_VALUE);
}
Example 10
Project: approval-master  File: StringEqualsJunitReporterTest.java View source code
@Test
public void shouldProperlyThrowAJunitComparisonError() throws Exception {
    REPORTER.notTheSame(EXPECTED.getBytes(StandardCharsets.UTF_8), new File("test"), EXPECTED.getBytes(StandardCharsets.UTF_8), new File("other"));
    try {
        REPORTER.notTheSame(EXPECTED.getBytes(StandardCharsets.UTF_8), new File("test"), ACTUAL.getBytes(StandardCharsets.UTF_8), new File("other"));
        Assert.fail("Should fail");
    } catch (ComparisonFailure e) {
        Assert.assertEquals(e.getExpected(), EXPECTED);
        Assert.assertEquals(e.getActual(), ACTUAL);
    }
}
Example 11
Project: cachecloud-master  File: JedisCommandTestBase.java View source code
protected void assertEquals(Set<byte[]> expected, Set<byte[]> actual) {
    assertEquals(expected.size(), actual.size());
    Iterator<byte[]> e = expected.iterator();
    while (e.hasNext()) {
        byte[] next = e.next();
        boolean contained = false;
        for (byte[] element : expected) {
            if (Arrays.equals(next, element)) {
                contained = true;
            }
        }
        if (!contained) {
            throw new ComparisonFailure("element is missing", Arrays.toString(next), actual.toString());
        }
    }
}
Example 12
Project: durian-master  File: TreeComparison.java View source code
/**
	 * Returns an {@link AssertionError} containing the contents of the
	 * two trees. Attempts to throw a JUnit ComparisonFailure if JUnit
	 * is on the class path, but it fails to a plain old {@code java.lang.AssertionError}
	 * if the reflection calls fail. 
	 */
private AssertionError createAssertionError() {
    // convert both sides to strings
    String expected = TreeQuery.toString(expectedDef, expectedRoot, expectedToString);
    String actual = TreeQuery.toString(actualDef, actualRoot, actualToString);
    // try to create a junit ComparisonFailure
    for (String exceptionType : Arrays.asList("org.junit.ComparisonFailure", "junit.framework.ComparisonFailure")) {
        try {
            return createComparisonFailure(exceptionType, expected, actual);
        } catch (Exception e) {
        }
    }
    // we'll have to settle for a plain-jane AssertionError
    return new AssertionError("Expected:\n" + expected + "\n\nActual:\n" + actual);
}
Example 13
Project: guanxi-common-master  File: TestUtils.java View source code
/**
     * This checks that two map objects are equivalent by checking the keys and values.
     * 
     * @param <A>
     * @param <B>
     * @param message
     * @param expected
     * @param actual
     */
public static <A, B> void assertMapEquals(String message, Map<A, B> expected, Map<A, B> actual) {
    if (actual == null && expected == null) {
        return;
    } else if (actual == null || expected == null) {
        throw new ComparisonFailure(message, expected == null ? "null" : expected.toString(), actual == null ? "null" : actual.toString());
    }
    assertEquals(message, expected.size(), actual.size());
    for (A key : expected.keySet()) {
        assertEquals("Differing values for key '" + key.toString() + "'", expected.get(key), actual.get(key));
    }
}
Example 14
Project: k3po-master  File: SpecificationStatement.java View source code
@Override
public void evaluate() throws Throwable {
    latch.setInterruptOnException(Thread.currentThread());
    FutureTask<ScriptPair> scriptFuture = new FutureTask<>(scriptRunner);
    try {
        // start the script execution
        new Thread(scriptFuture).start();
        // wait for script to be prepared (all binds ready for incoming connections from statement)
        latch.awaitPrepared();
        try {
            // note: JUnit timeout will trigger an exception
            statement.evaluate();
        } catch (AssumptionViolatedException e) {
            if (!latch.isFinished()) {
                scriptRunner.abort();
            }
            throw e;
        } catch (Throwable cause) {
            if (latch.hasException()) {
                throw cause;
            } else {
                if (!latch.isFinished()) {
                    scriptRunner.abort();
                }
                try {
                    ScriptPair scripts = scriptFuture.get(5, SECONDS);
                    try {
                        assertEquals("Specified behavior did not match", scripts.getExpectedScript(), scripts.getObservedScript());
                        throw cause;
                    } catch (ComparisonFailure f) {
                        f.initCause(cause);
                        throw f;
                    }
                } catch (ExecutionException ee) {
                    throw ee.getCause().initCause(cause);
                } catch (Exception e) {
                    throw cause;
                }
            }
        }
        // note: statement MUST call join() to ensure wrapped Rule(s) do not complete early
        // and to allow Specification script(s) to make progress
        String k3poSimpleName = K3poRule.class.getSimpleName();
        assertTrue(format("Did you instantiate %s with a @Rule and call %s.join()?", k3poSimpleName, k3poSimpleName), latch.isStartable());
        ScriptPair scripts = scriptFuture.get();
        assertEquals("Specified behavior did not match", scripts.getExpectedScript(), scripts.getObservedScript());
    } finally {
        try {
            scriptRunner.dispose();
        } finally {
            // clean up the task if it is still running
            scriptFuture.cancel(true);
        }
    }
}
Example 15
Project: komma-master  File: ManchesterTest.java View source code
private void parse(BufferedReader in, int testcaseNumber) throws Exception {
    System.out.println("\n\n*************************************************");
    System.out.println("Testcase: " + testcaseNumber);
    int failures = 0;
    for (TextInfo textInfo : getTextInfos(in)) {
        System.out.println(textInfo.text);
        ParsingResult<Object> result = new ReportingParseRunner<Object>(parser.OntologyDocument()).run(textInfo.text);
        InputBuffer inputBuffer = new DefaultInputBuffer(textInfo.text.toCharArray());
        boolean passed = result.hasErrors() && textInfo.result == Result.FAIL || !result.hasErrors() && textInfo.result == Result.OK;
        if (result.hasErrors() && textInfo.result == Result.OK) {
            System.out.println(ErrorUtils.printParseErrors(result));
        }
        if (textInfo.pathCheck.size() > 0) {
            Set<String> keySet = textInfo.pathCheck.keySet();
            for (Iterator<String> iterator = keySet.iterator(); iterator.hasNext(); ) {
                String path = iterator.next();
                String expected = textInfo.pathCheck.get(path);
                try {
                    assertNode(result, path, expected, inputBuffer);
                } catch (ComparisonFailure e) {
                    System.err.println(e);
                    passed = false;
                }
            }
        }
        if (!passed) {
            failures++;
            System.err.println(textInfo.text + " --> " + textInfo.result);
        }
        System.out.println(ParseTreeUtils.printNodeTree(result));
        System.out.println("*************************\n\n");
    }
    Assert.assertEquals(0, failures);
}
Example 16
Project: mdsal-master  File: AssertDataObjects.java View source code
// package local method used only in the self tests of this utility (not intended for usage by client code)
static void assertEqualByText(String expectedText, Object actual) throws ComparisonFailure {
    String actualText = GENERATOR.getExpression(actual);
    if (!expectedText.equals(actualText)) {
        String diff = DiffUtil.diff(expectedText, actualText);
        LOG.warn("diff for ComparisonFailure about to be thrown:\n{}", diff);
        throw new ComparisonFailure("Expected and actual beans do not match", expectedText, actualText);
    }
}
Example 17
Project: shazamcrest-master  File: MatcherAssertIgnoringFieldTest.java View source code
@Test(expected = ComparisonFailure.class)
public void failsWhenBeanDoesNotMatchAfterIgnoringFieldsInBeansWhitinList() {
    ParentBean.Builder expected = parent().addToChildBeanList(child().childString("kiwi").childInteger(2)).addToChildBeanList(child().childString("plum"));
    ParentBean.Builder actual = parent().addToChildBeanList(child().childString("banana")).addToChildBeanList(child().childString("grape"));
    assertThat(actual, sameBeanAs(expected).ignoring("childBeanList.childString"));
}
Example 18
Project: takari-lifecycle-master  File: CompileRule.java View source code
public void assertMessage(File basedir, String path, ErrorMessage expected) throws Exception {
    Collection<String> messages = getBuildContextLog().getMessages(new File(basedir, path));
    if (messages.size() != 1) {
        throw new ComparisonFailure("Number of messages", expected.toString(), messages.toString());
    }
    String message = messages.iterator().next();
    if (!expected.isMatch(message)) {
        throw new ComparisonFailure("", expected.toString(), message);
    }
}
Example 19
Project: Xpect-master  File: ParameterParserImpl.java View source code
protected void errorLeftoverTrailingText(IRegion claim, int offset, String leftover, String syntax) {
    String expected = claim.getDocument().toString();
    String actual = expected.substring(0, claim.getOffset() + offset) + expected.substring(claim.getOffset() + claim.getLength());
    String text = claim.getRegionText().trim();
    String msg = "When parsing \"" + text + "\" with syntax \"" + syntax + "\", the trailing part \"" + leftover + "\" remains unmatched.";
    throw new ComparisonFailure(msg, expected, actual);
}
Example 20
Project: xmlunit-master  File: CompareMatcherTest.java View source code
@Test
public void testIsIdenticalTo_withComparisonFailureForWhitespaces_throwsReadableMessage() {
    // Expected Exception
    expect(ComparisonFailure.class);
    expectMessage("Expected child nodelist length '1' but was '3'");
    expectMessage("expected:<<a>[<b/>]</a>> but was:<<a>[" + getLineSeparator() + "  <b/>" + getLineSeparator() + "]</a>>");
    // run test:
    assertThat("<a>\n  <b/>\n</a>", isIdenticalTo("<a><b/></a>").throwComparisonFailure());
}
Example 21
Project: assertj-core-master  File: ShouldBeEqual.java View source code
/**
   * Creates an <code>{@link AssertionError}</code> indicating that an assertion that verifies that two objects are
   * equal failed.<br>
   * The <code>{@link AssertionError}</code> message is built so that it differentiates {@link #actual} and
   * {@link #expected} description in case their string representation are the same (like 42 float and 42 double).
   * <p>
   * If JUnit 4 is in the classpath and the description is standard (no comparator was used and {@link #actual} and
   * {@link #expected} string representation were different), this method will instead create a
   * org.junit.ComparisonFailure that highlights the difference(s) between the expected and actual objects.
   * </p>
   * {@link AssertionError} stack trace won't show AssertJ related elements if {@link Failures} is configured to filter
   * them (see {@link Failures#setRemoveAssertJRelatedElementsFromStackTrace(boolean)}).
   *
   * @param description the description of the failed assertion.
   * @param representation
   * @return the created {@code AssertionError}.
   */
@Override
public AssertionError newAssertionError(Description description, Representation representation) {
    if (actualAndExpectedHaveSameStringRepresentation()) {
        // ComparisonFailure (which looks nice in eclipse)
        return Failures.instance().failure(defaultDetailedErrorMessage(description, representation));
    }
    // assertion error message to make it clear to the user it was used.
    if (comparisonStrategy.isStandard()) {
        // comparison strategy is standard -> try to build a JUnit ComparisonFailure that is nicely displayed in IDE.
        AssertionError error = comparisonFailure(description);
        // error ==null means that JUnit was not in the classpath
        if (error != null)
            return error;
    }
    // No JUnit in the classpath => fall back to default error message
    return Failures.instance().failure(defaultErrorMessage(description, representation));
}
Example 22
Project: BACKUP_FROM_SVN-master  File: DatabaseTestTemplate.java View source code
private void test(DatabaseTest test, Set<Database> databasesToTestOn) throws Exception {
    for (Database database : databasesToTestOn) {
        if (database instanceof SQLiteDatabase) {
            //todo: find how to get tests to run correctly on SQLite
            continue;
        }
        JdbcExecutor writeExecutor = new JdbcExecutor();
        writeExecutor.setDatabase(database);
        ExecutorService.getInstance().setExecutor(database, writeExecutor);
        LockService.getInstance(database).reset();
        if (database.getConnection() != null) {
            LockService.getInstance(database).forceReleaseLock();
        }
        try {
            test.performTest(database);
        } catch (ComparisonFailure e) {
            String newMessage = "Database Test Failure on " + database;
            if (e.getMessage() != null) {
                newMessage += ": " + e.getMessage();
            }
            ComparisonFailure newError = new ComparisonFailure(newMessage, e.getExpected(), e.getActual());
            newError.setStackTrace(e.getStackTrace());
            throw newError;
        } catch (AssertionError e) {
            e.printStackTrace();
            String newMessage = "Database Test Failure on " + database;
            if (e.getMessage() != null) {
                newMessage += ": " + e.getMessage();
            }
            AssertionError newError = new AssertionError(newMessage);
            newError.setStackTrace(e.getStackTrace());
            throw newError;
        } catch (MigrationFailedException e) {
            e.printStackTrace();
            String newMessage = "Database Test Failure on " + database;
            if (e.getMessage() != null) {
                newMessage += ": " + e.getMessage();
            }
            AssertionError newError = new AssertionError(newMessage);
            newError.setStackTrace(e.getStackTrace());
            throw newError;
        } catch (Exception e) {
            e.printStackTrace();
            String newMessage = "Database Test Exception on " + database;
            if (e.getMessage() != null) {
                newMessage += ": " + e.getMessage();
            }
            Exception newError = e.getClass().getConstructor(String.class).newInstance(newMessage);
            if (e.getCause() == null) {
                newError.setStackTrace(e.getStackTrace());
            } else {
                newError.setStackTrace(e.getCause().getStackTrace());
            }
            throw newError;
        } finally {
            if (database.getConnection() != null && !database.getAutoCommitMode()) {
                database.rollback();
            }
        }
    }
}
Example 23
Project: emf-master  File: JMergerTest.java View source code
/**
   * Verifies that target contents matches the contents of expected output file.
   *
   * @param expectedOutput
   * @param targetContents
   */
protected static void verifyMerge(File expectedOutput, String targetContents) {
    // extract merged contents
    StringBuilder mergeResult = new StringBuilder(targetContents);
    // we need to remove it from the mergedResult
    for (int i = mergeResult.length() - 1; i >= 0; i--) {
        if ('\r' == mergeResult.charAt(i)) {
            mergeResult.deleteCharAt(i);
        }
    }
    String expectedMerge = TestUtil.readFile(expectedOutput, false);
    String actualMerge = mergeResult.toString();
    try {
        assertEquals("Make sure the line breaks are OK.  The expected merge should have no '\\r'", expectedMerge, actualMerge);
    } catch (ComparisonFailure exception) {
        File alternative = new File(expectedOutput.toString().replace(".java", "Alt.java"));
        if (alternative.exists()) {
            expectedMerge = TestUtil.readFile(alternative, false);
            assertEquals("Make sure the line breaks are OK.  The expected merge should have no '\\r'", expectedMerge, actualMerge);
        } else {
            throw exception;
        }
    }
}
Example 24
Project: fest-assert-2.x-master  File: NotEqualErrorFactory_newAssertionError_Test.java View source code
@Test
public void should_create_ComparisonFailure_if_JUnit4_is_present() {
    NotEqualErrorFactory factory = shouldBeEqual("Luke", "Yoda");
    factory.descriptionFormatter = mock(DescriptionFormatter.class);
    when(factory.descriptionFormatter.format(description)).thenReturn(formattedDescription);
    AssertionError error = factory.newAssertionError(description);
    assertEquals(ComparisonFailure.class, error.getClass());
    assertEquals("[Jedi] expected:<'[Yoda]'> but was:<'[Luke]'>", error.getMessage());
}
Example 25
Project: handlebars.java-master  File: SpecTest.java View source code
private void run(final Spec spec) throws IOException {
    count++;
    Report report = new Report();
    report.header(80);
    report.append("* %s", spec.description());
    final String input = spec.template();
    final String expected = spec.expected();
    Object data = spec.data();
    report.append("DATA:");
    report.append(data.toString());
    report.append("PARTIALS:");
    report.append(spec.partials());
    report.append("INPUT:");
    report.append(input);
    report.append("EXPECTED:");
    report.append(expected);
    long startCompile = System.currentTimeMillis();
    Handlebars handlebars = new Handlebars(new SpecResourceLocator(spec));
    handlebars.setPrettyPrint(true);
    configure(handlebars);
    Template template = handlebars.compile("template");
    long endCompile = System.currentTimeMillis();
    long startMerge = System.currentTimeMillis();
    CharSequence output = template.apply(data);
    long endMerge = System.currentTimeMillis();
    long total = endMerge - startCompile;
    long compile = endCompile - startCompile;
    long merge = endMerge - startMerge;
    try {
        assertEquals(expected, output);
        report.append("OUTPUT:");
        report.append(output);
    } catch (HandlebarsException ex) {
        Handlebars.error(ex.getMessage());
    } catch (ComparisonFailure ex) {
        report.append("FOUND:");
        report.append(ex.getActual());
        throw ex;
    } finally {
        report.append("TOTAL    : %sms", total);
        if (total > 0) {
            report.append("  (%s%%)compile: %sms", compile * 100 / total, compile);
            report.append("  (%s%%)merge  : %sms", merge * 100 / total, merge);
        }
        report.header(80);
    }
}
Example 26
Project: hibernate-ogm-master  File: OrderedListAssertionsTest.java View source code
@Test
public void shouldConsiderNullInTheMiddleForExpectedValue() {
    try {
        OgmAssertions.assertThat(asList(Competitor// 1
        .GOLD, Competitor// 2
        .SILVER, Competitor// null
        .OTHER, Competitor// 3
        .BRONZE)).onProperty("order").ignoreNullOrder().containsExactly(1, null, 2, 3);
        fail("Expected failure wasn't raised");
    } catch (ComparisonFailure cf) {
        assertThat(cf.getMessage()).isEqualTo("expected:<[1, [null, 2], 3]> but was:<[1, [2, null], 3]>");
    }
}
Example 27
Project: jbosstools-integration-tests-master  File: DefaultValueAnnotationSupportTest.java View source code
/**
	 * Fails due to JBIDE-12027
	 * 
	 * @see https://issues.jboss.org/browse/JBIDE-12027
	 */
@Test(expected = ComparisonFailure.class)
public void testPathParamDefaultValue() {
    /* prepare project */
    importWSTestProject("default3");
    /* get RESTful services from JAX-RS REST explorer for the project */
    List<RESTfulWebService> restServices = restfulServicesForProject("default3");
    /* test JAX-RS REST explorer */
    assertCountOfRESTServices(restServices, 1);
    assertExpectedPathOfService("JBIDE-12027: ", restServices.get(0), "/rest/{" + paramName + ":" + paramType + ":" + defaultValue + "}");
}
Example 28
Project: liquibase-master  File: DatabaseTestTemplate.java View source code
private void test(DatabaseTest test, Set<Database> databasesToTestOn) throws Exception {
    for (Database database : databasesToTestOn) {
        if (database instanceof SQLiteDatabase) {
            //todo: find how to get tests to run correctly on SQLite
            continue;
        }
        JdbcExecutor writeExecutor = new JdbcExecutor();
        writeExecutor.setDatabase(database);
        ExecutorService.getInstance().setExecutor(database, writeExecutor);
        LockService lockService = LockServiceFactory.getInstance().getLockService(database);
        lockService.reset();
        if (database.getConnection() != null) {
            lockService.forceReleaseLock();
        }
        try {
            test.performTest(database);
        } catch (ComparisonFailure e) {
            String newMessage = "Database Test Failure on " + database;
            if (e.getMessage() != null) {
                newMessage += ": " + e.getMessage();
            }
            ComparisonFailure newError = new ComparisonFailure(newMessage, e.getExpected(), e.getActual());
            newError.setStackTrace(e.getStackTrace());
            throw newError;
        } catch (AssertionError e) {
            e.printStackTrace();
            String newMessage = "Database Test Failure on " + database;
            if (e.getMessage() != null) {
                newMessage += ": " + e.getMessage();
            }
            AssertionError newError = new AssertionError(newMessage);
            newError.setStackTrace(e.getStackTrace());
            throw newError;
        } catch (MigrationFailedException e) {
            e.printStackTrace();
            String newMessage = "Database Test Failure on " + database;
            if (e.getMessage() != null) {
                newMessage += ": " + e.getMessage();
            }
            AssertionError newError = new AssertionError(newMessage);
            newError.setStackTrace(e.getStackTrace());
            throw newError;
        } catch (Exception e) {
            e.printStackTrace();
            String newMessage = "Database Test Exception on " + database;
            if (e.getMessage() != null) {
                newMessage += ": " + e.getMessage();
            }
            Exception newError = e.getClass().getConstructor(String.class).newInstance(newMessage);
            if (e.getCause() == null) {
                newError.setStackTrace(e.getStackTrace());
            } else {
                newError.setStackTrace(e.getCause().getStackTrace());
            }
            throw newError;
        } finally {
            if (database.getConnection() != null && !database.getAutoCommitMode()) {
                database.rollback();
            }
        }
    }
}
Example 29
Project: cf-java-client-master  File: AbstractRestTest.java View source code
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
    if (interactionContext.isDone()) {
        throw new IllegalStateException("Additional request received: " + request);
    }
    interactionContext.setDone(true);
    try {
        interactionContext.getRequest().assertEquals(request);
        return interactionContext.getResponse().getMockResponse();
    } catch (ComparisonFailure e) {
        e.printStackTrace();
        return new MockResponse().setResponseCode(400);
    }
}
Example 30
Project: core-master  File: RemoteScopeTest.java View source code
@Deployment(testable = false)
public static Archive<?> deploy() {
    return ShrinkWrap.create(WebArchive.class, Utils.getDeploymentNameAsHash(RemoteScopeTest.class, Utils.ARCHIVE_TYPE.WAR)).addClasses(Bar.class, Foo.class, RemoteClient.class, Special.class, Temp.class, TempConsumer.class, TempProducer.class, Useless.class).addClasses(Utils.class, Assert.class, Description.class, SelfDescribing.class, ComparisonFailure.class).addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
Example 31
Project: glassfish-main-master  File: TestableThread.java View source code
@SuppressWarnings("serial")
public synchronized void startJoinAndCheckForFailures() {
    start();
    try {
        join();
    } catch (InterruptedException e) {
        throwableHolder[0] = e;
    }
    if (throwableHolder[0] != null) {
        if (throwableHolder[0] instanceof ComparisonFailure) {
            throw (ComparisonFailure) throwableHolder[0];
        } else {
            throw (StoppedByUserException) new StoppedByUserException() {

                @Override
                public String getMessage() {
                    return throwableHolder[0].getMessage();
                }
            }.initCause(throwableHolder[0]);
        }
    }
}
Example 32
Project: glassfish-master  File: TestableThread.java View source code
@SuppressWarnings("serial")
public synchronized void startJoinAndCheckForFailures() {
    start();
    try {
        join();
    } catch (InterruptedException e) {
        throwableHolder[0] = e;
    }
    if (throwableHolder[0] != null) {
        if (throwableHolder[0] instanceof ComparisonFailure) {
            throw (ComparisonFailure) throwableHolder[0];
        } else {
            throw (StoppedByUserException) new StoppedByUserException() {

                @Override
                public String getMessage() {
                    return throwableHolder[0].getMessage();
                }
            }.initCause(throwableHolder[0]);
        }
    }
}
Example 33
Project: idea-multimarkdown-master  File: TestSuggestionListBasic.java View source code
@Test(expected = ComparisonFailure.class)
public void testAddSuggestionFailure() {
    SuggestionList suggestionList = new SuggestionList();
    assertEquals(0, suggestionList.size());
    Suggestion.Param<Boolean> param = new Suggestion.Param<Boolean>(PARAM_NAME, true);
    Suggestion suggestion = new Suggestion(TEST_TEXT, param);
    Suggestion suggestion1 = new Suggestion(TEST_TEXT);
    suggestionList.add(suggestion);
    assertSuggestionListHasSuggestions(suggestionList, suggestion1);
}
Example 34
Project: ogham-master  File: AssertEmail.java View source code
/**
	 * Checks if the received body equals the expected body. It handles HTML
	 * content and pure text content.
	 * <p>
	 * For text, the check can be done either strictly (totally equal) or not
	 * (ignore new lines).
	 * </p>
	 * <p>
	 * For HTML, the string content is parsed and DOM trees are compared. The
	 * comparison can be done either strictly (DOM trees are totally equals,
	 * attributes are in the same order) or not (attributes can be in any
	 * order).
	 * </p>
	 * 
	 * @param expectedBody
	 *            the expected content as string
	 * @param actualBody
	 *            the received content as string
	 * @param strict
	 *            true for strict checking (totally equals) or false to ignore
	 *            new line characters
	 */
private static void assertBody(String expectedBody, String actualBody, boolean strict) {
    if (isHtml(expectedBody)) {
        if (strict) {
            AssertHtml.assertIdentical(expectedBody, actualBody);
        } else {
            AssertHtml.assertSimilar(expectedBody, actualBody);
        }
    } else {
        if (strict ? !expectedBody.equals(actualBody) : !sanitize(expectedBody).equals(sanitize(actualBody))) {
            throw new ComparisonFailure("body should be '" + expectedBody + "'", expectedBody, actualBody);
        }
    }
}
Example 35
Project: Payara-master  File: TestableThread.java View source code
@SuppressWarnings("serial")
public synchronized void startJoinAndCheckForFailures() {
    start();
    try {
        join();
    } catch (InterruptedException e) {
        throwableHolder[0] = e;
    }
    if (throwableHolder[0] != null) {
        if (throwableHolder[0] instanceof ComparisonFailure) {
            throw (ComparisonFailure) throwableHolder[0];
        } else {
            throw (StoppedByUserException) new StoppedByUserException() {

                @Override
                public String getMessage() {
                    return throwableHolder[0].getMessage();
                }
            }.initCause(throwableHolder[0]);
        }
    }
}
Example 36
Project: reactor-master  File: AbstractRestTest.java View source code
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
    if (interactionContext.isDone()) {
        throw new IllegalStateException("Additional request received: " + request);
    }
    interactionContext.setDone(true);
    try {
        interactionContext.getRequest().assertEquals(request);
        return interactionContext.getResponse().getMockResponse();
    } catch (ComparisonFailure e) {
        e.printStackTrace();
        return new MockResponse().setResponseCode(400);
    }
}
Example 37
Project: sonarqube-master  File: JsonAssertTest.java View source code
@Test
public void isSimilarAs_strings() {
    assertJson("{}").isSimilarTo("{}");
    try {
        assertJson("{}").isSimilarTo("[]");
        fail();
    } catch (ComparisonFailure error) {
        assertThat(error.getMessage()).isEqualTo("Not a super-set of expected JSON - expected:<[[]]> but was:<[{}]>");
        assertThat(error.getActual()).isEqualTo("{}");
        assertThat(error.getExpected()).isEqualTo("[]");
    }
}
Example 38
Project: uml-auto-assessment-master  File: PlistJUnitResultFormatter.java View source code
// ----------------------------------------------------------
/**
     * Look up the error code associated with an exception.
     * @param error the exception to code, or null
     * @return the code
     */
protected int codeOf(Throwable error) {
    if (error == null)
        return 1;
    // First-pass code assignment is made by the code table
    int code = 0;
    for (int i = 0; i < codeTable.length; i++) {
        if (codeTable[i] != null) {
            if (codeTable[i].isAssignableFrom(error.getClass()) || codeTable[i].getName().equals(error.getClass().getName())) {
                // error instanceof codeTable[i]
                code = i;
                break;
            }
        }
    }
    // alone, so we must break down the message to refine the code
    if (error instanceof AssertionFailedError) {
        // adapters used by the ANT JUnit task
        if (error instanceof junit.framework.ComparisonFailure || error instanceof org.junit.ComparisonFailure || (error.getCause() != null && error.getCause() instanceof org.junit.ComparisonFailure)) {
            code = 2;
        } else {
            code = 13;
            StackTraceElement[] trace = error.getStackTrace();
            String methodName = null;
            int pos = 0;
            if (error.getCause() != null) {
                // Then it is a 4.x-style error, wrapped by the ANT 1.7
                // JUnit test adapter
                trace = error.getCause().getStackTrace();
            }
            pos = findLast(trace, 0, "junit.framework.Assert");
            if (pos < trace.length && trace[pos].getClassName().equals("junit.framework.Assert")) {
                methodName = trace[pos].getMethodName();
            } else {
                pos = findLast(trace, 0, "student.TestCase");
                if (pos < trace.length && trace[pos].getClassName().equals("student.TestCase")) {
                    methodName = trace[pos].getMethodName();
                } else {
                    pos = findLast(trace, 0, "org.junit.Assert");
                    if (pos < trace.length && trace[pos].getClassName().equals("org.junit.Assert")) {
                        methodName = trace[pos].getMethodName();
                    }
                }
            }
            if (methodName != null) {
                code = assertFailCodeOf(methodName);
                // Next, check for a fuzzy equals
                pos++;
                if (pos < trace.length && trace[pos].getClassName().equals("net.sf.webcat.junit.Assert")) {
                    code = 10;
                }
                // Last, check for a custom assert
                pos = findFirst(trace, pos, currentSuite.getName());
                if (pos < trace.length && trace[pos].getMethodName().startsWith("assert")) {
                    // custom assert
                    code = 11;
                }
            } else if (pos < trace.length) {
                // Must be a wrapped AssertionError from some other
                // code
                code = 29;
            }
        }
    }
    return code;
}
Example 39
Project: afc-master  File: AbstractVector2DTest.java View source code
public final void assertEpsilonEquals(double expected, PowerResult<?> actual) {
    if (actual == null) {
        //$NON-NLS-1$
        fail("Result is null");
        return;
    }
    if (actual.isVectorial()) {
        //$NON-NLS-1$
        throw new ComparisonFailure("Not same result type", Double.toString(expected), actual.toString());
    }
    assertEpsilonEquals(expected, actual.getScalar());
}
Example 40
Project: calcite-master  File: DiffRepository.java View source code
public void assertEquals(String tag, String expected, String actual) {
    final String testCaseName = getCurrentTestCaseName(true);
    String expected2 = expand(tag, expected);
    if (expected2 == null) {
        update(testCaseName, expected, actual);
        throw new AssertionError("reference file does not contain resource '" + expected + "' for test case '" + testCaseName + "'");
    } else {
        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 = expected2.replace(Util.LINE_SEPARATOR, "\n");
            String actualCanonical = actual.replace(Util.LINE_SEPARATOR, "\n");
            Assert.assertEquals(tag, expected2Canonical, actualCanonical);
        } catch (ComparisonFailure e) {
            amend(expected, actual);
            throw e;
        }
    }
}
Example 41
Project: ceylon-compiler-master  File: ModelLoaderTests.java View source code
@Test
public void functionalParameterParameterNames() {
    compile("FunctionalParameterParameterNames.ceylon");
    try {
        verifyCompilerClassLoading("functionalparameterparameternamestest.ceylon", new RunnableTest() {

            @Override
            public void test(ModelLoader loader) {
                Module mod = loader.getLoadedModule(moduleForJavaModelLoading(), moduleVersionForJavaModelLoading());
                Assert.assertNotNull(mod);
                Package p = mod.getDirectPackage(packageForJavaModelLoading());
                Assert.assertNotNull(p);
                Declaration fpClass = p.getDirectMember("FunctionalParameterParameterNames", Collections.<Type>emptyList(), false);
                Assert.assertNotNull(fpClass);
                {
                    // functionalParameter
                    Function fp = (Function) fpClass.getDirectMember("functionalParameter", null, false);
                    Assert.assertNotNull(fp);
                    Assert.assertEquals(1, fp.getParameterLists().size());
                    Assert.assertEquals(1, fp.getParameterLists().get(0).getParameters().size());
                    Assert.assertEquals("Anything(Anything(String))", typeName(fp));
                    Parameter paramF = fp.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertTrue(paramF.isDeclaredAnything());
                    Assert.assertEquals("f", paramF.getName());
                    Assert.assertTrue(paramF.getModel() instanceof Function);
                    Function modelF = (Function) paramF.getModel();
                    Assert.assertTrue(modelF.isDeclaredVoid());
                    Assert.assertEquals("Anything(String)", typeName(modelF));
                    Assert.assertEquals("f", modelF.getName());
                    Assert.assertEquals(1, modelF.getParameterLists().size());
                    Assert.assertEquals(1, modelF.getParameterLists().get(0).getParameters().size());
                    Parameter paramS = modelF.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("s", paramS.getName());
                    Assert.assertTrue(paramS.getModel() instanceof Value);
                    Value modelS = (Value) paramS.getModel();
                    Assert.assertEquals("s", modelS.getName());
                    Assert.assertEquals("String", typeName(modelS));
                }
                {
                    // callableValueParameter
                    Function fp = (Function) fpClass.getDirectMember("callableValueParameter", null, false);
                    Assert.assertNotNull(fp);
                    Assert.assertEquals(1, fp.getParameterLists().size());
                    Assert.assertEquals(1, fp.getParameterLists().get(0).getParameters().size());
                    Assert.assertEquals("Anything(Anything(String))", typeName(fp));
                    Parameter paramF = fp.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("f", paramF.getName());
                    Assert.assertFalse(paramF.isDeclaredAnything());
                    Assert.assertTrue(paramF.getModel() instanceof Value);
                    Value modelF = (Value) paramF.getModel();
                    Assert.assertEquals("f", modelF.getName());
                    Assert.assertEquals("Anything(String)", typeName(modelF));
                }
                {
                    // functionalParameterNested
                    Function fp = (Function) fpClass.getDirectMember("functionalParameterNested", null, false);
                    Assert.assertNotNull(fp);
                    Assert.assertEquals(1, fp.getParameterLists().size());
                    Assert.assertEquals(1, fp.getParameterLists().get(0).getParameters().size());
                    Assert.assertEquals("Anything(Anything(Anything(String)))", typeName(fp));
                    Parameter paramF = fp.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("f", paramF.getName());
                    Assert.assertTrue(paramF.isDeclaredAnything());
                    Assert.assertTrue(paramF.getModel() instanceof Function);
                    Function modelF = (Function) paramF.getModel();
                    Assert.assertEquals("Anything(Anything(String))", typeName(modelF));
                    Assert.assertEquals("f", modelF.getName());
                    Assert.assertTrue(modelF.isDeclaredVoid());
                    Assert.assertEquals(1, modelF.getParameterLists().size());
                    Assert.assertEquals(1, modelF.getParameterLists().get(0).getParameters().size());
                    Parameter paramF2 = modelF.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertTrue(paramF2.isDeclaredAnything());
                    Assert.assertEquals("f2", paramF2.getName());
                    Assert.assertTrue(paramF2.getModel() instanceof Function);
                    Function modelF2 = (Function) paramF2.getModel();
                    Assert.assertEquals("Anything(String)", typeName(modelF2));
                    Assert.assertEquals("f2", modelF2.getName());
                    Assert.assertTrue(modelF2.isDeclaredVoid());
                    Assert.assertEquals(1, modelF2.getParameterLists().size());
                    Assert.assertEquals(1, modelF2.getParameterLists().get(0).getParameters().size());
                    Parameter paramS = modelF2.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("s", paramS.getName());
                    Assert.assertTrue(paramS.getModel() instanceof Value);
                    Value modelS = (Value) paramS.getModel();
                    Assert.assertEquals("s", modelS.getName());
                    Assert.assertEquals("String", typeName(modelS));
                }
                {
                    // functionalParameterNested2
                    Function fp = (Function) fpClass.getDirectMember("functionalParameterNested2", null, false);
                    Assert.assertNotNull(fp);
                    Assert.assertEquals(1, fp.getParameterLists().size());
                    Assert.assertEquals(1, fp.getParameterLists().get(0).getParameters().size());
                    Assert.assertEquals("Anything(Anything(Anything(String, Anything(Boolean, Integer))))", typeName(fp));
                    Parameter paramF = fp.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("f", paramF.getName());
                    Assert.assertTrue(paramF.getModel() instanceof Function);
                    Function modelF = (Function) paramF.getModel();
                    Assert.assertEquals("f", modelF.getName());
                    Assert.assertEquals("Anything(Anything(String, Anything(Boolean, Integer)))", typeName(modelF));
                    Assert.assertEquals(1, modelF.getParameterLists().size());
                    Assert.assertEquals(1, modelF.getParameterLists().get(0).getParameters().size());
                    Parameter paramF2 = modelF.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("f2", paramF2.getName());
                    Assert.assertTrue(paramF2.getModel() instanceof Function);
                    Function modelF2 = (Function) paramF2.getModel();
                    Assert.assertEquals("Anything(String, Anything(Boolean, Integer))", typeName(modelF2));
                    Assert.assertEquals("f2", modelF2.getName());
                    Assert.assertEquals(1, modelF2.getParameterLists().size());
                    Assert.assertEquals(2, modelF2.getParameterLists().get(0).getParameters().size());
                    Parameter paramS = modelF2.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("s", paramS.getName());
                    Assert.assertTrue(paramS.getModel() instanceof Value);
                    Value modelS = (Value) paramS.getModel();
                    Assert.assertEquals("String", typeName(modelS));
                    Assert.assertEquals("s", modelS.getName());
                    Parameter paramF3 = modelF2.getParameterLists().get(0).getParameters().get(1);
                    Assert.assertEquals("f3", paramF3.getName());
                    Assert.assertTrue(paramF3.getModel() instanceof Function);
                    Function modelF3 = (Function) paramF3.getModel();
                    Assert.assertEquals("Anything(Boolean, Integer)", typeName(modelF3));
                    Assert.assertEquals("f3", modelF3.getName());
                    Assert.assertEquals(1, modelF3.getParameterLists().size());
                    Assert.assertEquals(2, modelF3.getParameterLists().get(0).getParameters().size());
                    Parameter paramB1 = modelF3.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("b1", paramB1.getName());
                    Assert.assertTrue(paramB1.getModel() instanceof Value);
                    Value modelB1 = (Value) paramB1.getModel();
                    Assert.assertEquals("Boolean", typeName(modelB1));
                    Assert.assertEquals("b1", modelB1.getName());
                    Parameter paramI2 = modelF3.getParameterLists().get(0).getParameters().get(1);
                    Assert.assertEquals("i2", paramI2.getName());
                    Assert.assertTrue(paramI2.getModel() instanceof Value);
                    Value modelI2 = (Value) paramI2.getModel();
                    Assert.assertEquals("i2", modelI2.getName());
                    Assert.assertEquals("Integer", typeName(modelI2));
                }
                {
                    // functionalParameterMpl
                    Function fp = (Function) fpClass.getDirectMember("functionalParameterMpl", null, false);
                    Assert.assertNotNull(fp);
                    Assert.assertEquals(1, fp.getParameterLists().size());
                    Assert.assertEquals(1, fp.getParameterLists().get(0).getParameters().size());
                    Assert.assertEquals("Anything(Anything(Integer)(String))", typeName(fp));
                    Parameter paramF = fp.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertTrue(paramF.isDeclaredAnything());
                    Assert.assertEquals("mpl", paramF.getName());
                    Assert.assertTrue(paramF.getModel() instanceof Function);
                    Function modelF = (Function) paramF.getModel();
                    Assert.assertTrue(modelF.isDeclaredVoid());
                    Assert.assertEquals("Anything(Integer)(String)", typeName(modelF));
                    Assert.assertEquals("mpl", modelF.getName());
                    Assert.assertEquals(2, modelF.getParameterLists().size());
                    Assert.assertEquals(1, modelF.getParameterLists().get(0).getParameters().size());
                    Assert.assertEquals(1, modelF.getParameterLists().get(1).getParameters().size());
                    Parameter paramS = modelF.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("s", paramS.getName());
                    Assert.assertTrue(paramS.getModel() instanceof Value);
                    Value modelS = (Value) paramS.getModel();
                    Assert.assertEquals("s", modelS.getName());
                    Assert.assertEquals("String", typeName(modelS));
                    Parameter paramS2 = modelF.getParameterLists().get(1).getParameters().get(0);
                    Assert.assertEquals("i2", paramS2.getName());
                    Assert.assertTrue(paramS2.getModel() instanceof Value);
                    Value modelS2 = (Value) paramS2.getModel();
                    Assert.assertEquals("i2", modelS2.getName());
                    Assert.assertEquals("Integer", typeName(modelS2));
                }
                {
                    // functionalParameterMpl2
                    Function fp = (Function) fpClass.getDirectMember("functionalParameterMpl2", null, false);
                    Assert.assertNotNull(fp);
                    Assert.assertEquals(1, fp.getParameterLists().size());
                    Assert.assertEquals(1, fp.getParameterLists().get(0).getParameters().size());
                    Parameter paramMpl = fp.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("mpl", paramMpl.getName());
                    Assert.assertTrue(paramMpl.getModel() instanceof Function);
                    Function modelMpl = (Function) paramMpl.getModel();
                    Assert.assertEquals("mpl", modelMpl.getName());
                    Assert.assertEquals(2, modelMpl.getParameterLists().size());
                    Assert.assertEquals(1, modelMpl.getParameterLists().get(0).getParameters().size());
                    Assert.assertEquals(1, modelMpl.getParameterLists().get(1).getParameters().size());
                    Parameter paramS = modelMpl.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("s", paramS.getName());
                    Assert.assertTrue(paramS.getModel() instanceof Value);
                    Value modelS = (Value) paramS.getModel();
                    Assert.assertEquals("s", modelS.getName());
                    Assert.assertEquals("String", typeName(modelS));
                    Parameter paramF = modelMpl.getParameterLists().get(1).getParameters().get(0);
                    Assert.assertEquals("f", paramF.getName());
                    Assert.assertTrue(paramF.getModel() instanceof Function);
                    Function modelF = (Function) paramF.getModel();
                    Assert.assertEquals("f", modelF.getName());
                    Assert.assertEquals(1, modelF.getParameterLists().size());
                    Assert.assertEquals(2, modelF.getParameterLists().get(0).getParameters().size());
                    Parameter paramB1 = modelF.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("b1", paramB1.getName());
                    Assert.assertTrue(paramB1.getModel() instanceof Value);
                    Value modelB1 = (Value) paramB1.getModel();
                    Assert.assertEquals("b1", modelB1.getName());
                    Assert.assertEquals("Boolean", typeName(modelB1));
                    Parameter paramI2 = modelF.getParameterLists().get(0).getParameters().get(1);
                    Assert.assertEquals("i2", paramI2.getName());
                    Assert.assertTrue(paramI2.getModel() instanceof Value);
                    Value modelI2 = (Value) paramI2.getModel();
                    Assert.assertEquals("i2", modelI2.getName());
                    Assert.assertEquals("Integer", typeName(modelI2));
                }
                {
                    // functionalParameterMpl3
                    Function fp = (Function) fpClass.getDirectMember("functionalParameterMpl3", null, false);
                    Assert.assertNotNull(fp);
                    Assert.assertEquals(1, fp.getParameterLists().size());
                    Assert.assertEquals(1, fp.getParameterLists().get(0).getParameters().size());
                    Parameter paramMpl = fp.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("mpl", paramMpl.getName());
                    Assert.assertTrue(paramMpl.getModel() instanceof Function);
                    Function modelMpl = (Function) paramMpl.getModel();
                    Assert.assertEquals("mpl", modelMpl.getName());
                    Assert.assertEquals(2, modelMpl.getParameterLists().size());
                    Assert.assertEquals(1, modelMpl.getParameterLists().get(0).getParameters().size());
                    Assert.assertEquals(1, modelMpl.getParameterLists().get(1).getParameters().size());
                    Parameter paramF = modelMpl.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("f", paramF.getName());
                    Assert.assertTrue(paramF.getModel() instanceof Function);
                    Function modelF = (Function) paramF.getModel();
                    Assert.assertEquals("f", modelF.getName());
                    Assert.assertEquals(1, modelF.getParameterLists().size());
                    Assert.assertEquals(2, modelF.getParameterLists().get(0).getParameters().size());
                    Parameter paramB1 = modelF.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("b1", paramB1.getName());
                    Assert.assertTrue(paramB1.getModel() instanceof Value);
                    Value modelB1 = (Value) paramB1.getModel();
                    Assert.assertEquals("b1", modelB1.getName());
                    Assert.assertEquals("Boolean", typeName(modelB1));
                    Parameter paramI2 = modelF.getParameterLists().get(0).getParameters().get(1);
                    Assert.assertEquals("i2", paramI2.getName());
                    Assert.assertTrue(paramI2.getModel() instanceof Value);
                    Value modelI2 = (Value) paramI2.getModel();
                    Assert.assertEquals("i2", modelI2.getName());
                    Assert.assertEquals("Integer", typeName(modelI2));
                    Parameter paramS = modelMpl.getParameterLists().get(1).getParameters().get(0);
                    Assert.assertEquals("s", paramS.getName());
                    Assert.assertTrue(paramS.getModel() instanceof Value);
                    Value modelS = (Value) paramS.getModel();
                    Assert.assertEquals("s", modelS.getName());
                    Assert.assertEquals("String", typeName(modelS));
                }
                {
                    // functionalParameterReturningCallable
                    Function fp = (Function) fpClass.getDirectMember("functionalParameterReturningCallable", null, false);
                    Assert.assertNotNull(fp);
                    Assert.assertEquals(1, fp.getParameterLists().size());
                    Assert.assertEquals(1, fp.getParameterLists().get(0).getParameters().size());
                    Parameter paramF = fp.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("f", paramF.getName());
                    Assert.assertTrue(paramF.getModel() instanceof Function);
                    Function modelF = (Function) paramF.getModel();
                    Assert.assertEquals("f", modelF.getName());
                    Assert.assertEquals("Anything()", modelF.getType().asString());
                    Assert.assertEquals(1, modelF.getParameterLists().size());
                    Assert.assertEquals(1, modelF.getParameterLists().get(0).getParameters().size());
                    Parameter paramS = modelF.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("s", paramS.getName());
                    Assert.assertTrue(paramS.getModel() instanceof Value);
                    Value modelS = (Value) paramS.getModel();
                    Assert.assertEquals("s", modelS.getName());
                    Assert.assertEquals("String", modelS.getType().asString());
                }
                {
                    // functionalParameterReturningCallable
                    Function fp = (Function) fpClass.getDirectMember("functionalParameterTakingCallable", null, false);
                    Assert.assertNotNull(fp);
                    Assert.assertEquals(1, fp.getParameterLists().size());
                    Assert.assertEquals(1, fp.getParameterLists().get(0).getParameters().size());
                    Parameter paramF = fp.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("f", paramF.getName());
                    Assert.assertTrue(paramF.getModel() instanceof Function);
                    Function modelF = (Function) paramF.getModel();
                    Assert.assertEquals("f", modelF.getName());
                    Assert.assertEquals("Anything", modelF.getType().asString());
                    Assert.assertEquals(1, modelF.getParameterLists().size());
                    Assert.assertEquals(1, modelF.getParameterLists().get(0).getParameters().size());
                    Parameter paramF2 = modelF.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("f2", paramF2.getName());
                    Assert.assertTrue(paramF2.getModel() instanceof Value);
                    Value modelF2 = (Value) paramF2.getModel();
                    Assert.assertEquals("f2", modelF2.getName());
                    Assert.assertEquals("Anything(String)", modelF2.getType().asString());
                }
                {
                    // functionalParameterVariadicStar
                    Function fp = (Function) fpClass.getDirectMember("functionalParameterVariadicStar", null, false);
                    Assert.assertNotNull(fp);
                    Assert.assertEquals(1, fp.getParameterLists().size());
                    Assert.assertEquals(1, fp.getParameterLists().get(0).getParameters().size());
                    Assert.assertEquals("Anything(Anything(String*))", typeName(fp));
                    Parameter paramF = fp.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertTrue(paramF.isDeclaredAnything());
                    Assert.assertEquals("f", paramF.getName());
                    Assert.assertTrue(paramF.getModel() instanceof Function);
                    Function modelF = (Function) paramF.getModel();
                    Assert.assertTrue(modelF.isDeclaredVoid());
                    Assert.assertEquals("Anything(String*)", typeName(modelF));
                    Assert.assertEquals("f", modelF.getName());
                    Assert.assertEquals(1, modelF.getParameterLists().size());
                    Assert.assertEquals(1, modelF.getParameterLists().get(0).getParameters().size());
                    Parameter paramS = modelF.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("s", paramS.getName());
                    Assert.assertTrue(paramS.isSequenced());
                    Assert.assertFalse(paramS.isAtLeastOne());
                    Assert.assertTrue(paramS.getModel() instanceof Value);
                    Value modelS = (Value) paramS.getModel();
                    Assert.assertEquals("s", modelS.getName());
                    Assert.assertEquals("String[]", typeName(modelS));
                }
                {
                    // functionalParameterVariadicPlus
                    Function fp = (Function) fpClass.getDirectMember("functionalParameterVariadicPlus", null, false);
                    Assert.assertNotNull(fp);
                    Assert.assertEquals(1, fp.getParameterLists().size());
                    Assert.assertEquals(1, fp.getParameterLists().get(0).getParameters().size());
                    Assert.assertEquals("Anything(Anything(String+))", typeName(fp));
                    Parameter paramF = fp.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertTrue(paramF.isDeclaredAnything());
                    Assert.assertEquals("f", paramF.getName());
                    Assert.assertTrue(paramF.getModel() instanceof Function);
                    Function modelF = (Function) paramF.getModel();
                    Assert.assertTrue(modelF.isDeclaredVoid());
                    Assert.assertEquals("Anything(String+)", typeName(modelF));
                    Assert.assertEquals("f", modelF.getName());
                    Assert.assertEquals(1, modelF.getParameterLists().size());
                    Assert.assertEquals(1, modelF.getParameterLists().get(0).getParameters().size());
                    Parameter paramS = modelF.getParameterLists().get(0).getParameters().get(0);
                    Assert.assertEquals("s", paramS.getName());
                    Assert.assertTrue(paramS.isSequenced());
                    Assert.assertTrue(paramS.isAtLeastOne());
                    Assert.assertTrue(paramS.getModel() instanceof Value);
                    Value modelS = (Value) paramS.getModel();
                    Assert.assertEquals("s", modelS.getName());
                    Assert.assertEquals("[String+]", typeName(modelS));
                }
            }

            private String typeName(FunctionOrValue fp) {
                if (fp instanceof Function) {
                    return fp.appliedTypedReference(null, Collections.<Type>emptyList()).getFullType().asString();
                } else if (fp instanceof Value) {
                    return fp.getType().asString();
                }
                return null;
            }
        });
    } catch (RuntimeException e) {
        if (e.getCause() instanceof org.junit.ComparisonFailure) {
            throw (org.junit.ComparisonFailure) e.getCause();
        } else if (e.getCause() instanceof java.lang.AssertionError) {
            throw (java.lang.AssertionError) e.getCause();
        }
        throw e;
    }
}
Example 42
Project: FreeBuilder-master  File: UtilTests.java View source code
private void assertSameType(TypeMirror expected, TypeMirror actual) {
    if (!model.typeUtils().isSameType(expected, actual)) {
        String expectedString = (expected == null) ? "null" : expected.toString();
        String actualString = (actual == null) ? "null" : actual.toString();
        if (expectedString.equals(actualString)) {
            expectedString = extendedToString(expected);
            actualString = extendedToString(actual);
        }
        throw new ComparisonFailure("", expectedString, actualString);
    }
}
Example 43
Project: js-parser-master  File: SpecialOracleTest.java View source code
@Test
public void testAllSqlsParseDeparse() throws IOException {
    int count = 0;
    int success = 0;
    File[] sqlTestFiles = SQLS_DIR.listFiles();
    for (File file : sqlTestFiles) {
        if (file.isFile()) {
            count++;
            LOG.log(Level.INFO, "testing {0}", file.getName());
            String sql = FileUtils.readFileToString(file);
            try {
                assertSqlCanBeParsedAndDeparsed(sql, true);
                success++;
                LOG.info("   -> SUCCESS");
            } catch (JSQLParserException ex) {
                LOG.log(Level.INFO, "   -> PROBLEM {0}", ex.toString());
            } catch (TokenMgrError ex) {
                LOG.log(Level.INFO, "   -> PROBLEM {0}", ex.toString());
            } catch (Exception ex) {
                LOG.log(Level.INFO, "   -> PROBLEM {0}", ex.toString());
            } catch (ComparisonFailure ex) {
                LOG.log(Level.INFO, "   -> PROBLEM {0}", ex.toString());
            }
        }
    }
    LOG.log(Level.INFO, "tested {0} files. got {1} correct parse results", new Object[] { count, success });
    assertTrue(success >= 140);
}
Example 44
Project: JSqlParser-master  File: SpecialOracleTest.java View source code
@Test
public void testAllSqlsParseDeparse() throws IOException {
    int count = 0;
    int success = 0;
    File[] sqlTestFiles = SQLS_DIR.listFiles();
    for (File file : sqlTestFiles) {
        if (file.isFile()) {
            count++;
            LOG.log(Level.INFO, "testing {0}", file.getName());
            String sql = FileUtils.readFileToString(file);
            try {
                assertSqlCanBeParsedAndDeparsed(sql, true);
                success++;
                LOG.info("   -> SUCCESS");
            } catch (JSQLParserException ex) {
                LOG.log(Level.INFO, "   -> PROBLEM {0}", ex.toString());
            } catch (TokenMgrError ex) {
                LOG.log(Level.INFO, "   -> PROBLEM {0}", ex.toString());
            } catch (Exception ex) {
                LOG.log(Level.INFO, "   -> PROBLEM {0}", ex.toString());
            } catch (ComparisonFailure ex) {
                LOG.log(Level.INFO, "   -> PROBLEM {0}", ex.toString());
            }
        }
    }
    LOG.log(Level.INFO, "tested {0} files. got {1} correct parse results", new Object[] { count, success });
    assertTrue(success >= 140);
}
Example 45
Project: kafka-unit-master  File: KafkaUnit.java View source code
public List<T> call() throws Exception {
    List<T> messages = new ArrayList<>();
    try {
        for (MessageAndMetadata<String, String> kafkaStream : kafkaStreams) {
            T message = messageExtractor.extract(kafkaStream);
            LOGGER.info("Received message: {}", kafkaStream.message());
            messages.add(message);
        }
    } catch (ConsumerTimeoutException e) {
    }
    if (messages.size() != expectedMessages) {
        throw new ComparisonFailure("Incorrect number of messages returned", Integer.toString(expectedMessages), Integer.toString(messages.size()));
    }
    return messages;
}
Example 46
Project: kawala-master  File: AssertTest.java View source code
@Test
public void assertBigDecimalEquals2() {
    try {
        assertBigDecimalEquals(new BigDecimal("1.0000000000000000000000000001"), new BigDecimal("1.0000000000000000000000000002"));
        fail();
    } catch (ComparisonFailure e) {
        assertEquals("expected:<...00000000000000000000[1]> " + "but was:<...00000000000000000000[2]>", e.getMessage());
    }
}
Example 47
Project: objectlabkit-master  File: CukeUtils.java View source code
public static <T> void compareResults(final Class<T> classType, final List<T> actual, final DataTable expected) {
    final List<String> fieldsToCompare = expected.topCells();
    final T[] expectedEntities = convertDataTableToExpected(classType, expected, fieldsToCompare);
    final List<T> actualEntities = actual.stream().map( sea -> copyFieldValues(fieldsToCompare, sea, classType)).collect(Collectors.toList());
    try {
        assertThat(actualEntities).usingElementComparator(comparator(buildExclusionFields(classType, fieldsToCompare))).containsOnly(expectedEntities);
    } catch (final java.lang.AssertionError e) {
        final String actualDataAsStr = convertToString(actual, fieldsToCompare);
        throw new ComparisonFailure("Table comparison for " + classType.getSimpleName() + " does not match\n", expected.toString(), actualDataAsStr);
    }
}
Example 48
Project: optiq-master  File: TestUtil.java View source code
//~ Methods ----------------------------------------------------------------
public static void assertEqualsVerbose(String expected, String actual) {
    if (actual == null) {
        if (expected == null) {
            return;
        } else {
            String message = "Expected:\n" + expected + "\nActual: null";
            throw new ComparisonFailure(message, expected, null);
        }
    }
    if ((expected != null) && expected.equals(actual)) {
        return;
    }
    String s = toJavaString(actual);
    String message = "Expected:\n" + expected + "\nActual:\n " + actual + "\nActual java:\n" + s + '\n';
    throw new ComparisonFailure(message, expected, actual);
}
Example 49
Project: sarl-master  File: AbstractSarlTest.java View source code
protected static void assertOsgiVersionEquals(Version expected, Version actual) {
    if (Objects.equal(expected, actual)) {
        return;
    }
    if (expected == null) {
        fail("Version not null");
    }
    if (actual == null) {
        fail("Unexpected null value");
    }
    if (expected.getMajor() == actual.getMajor() && expected.getMinor() == actual.getMinor() && expected.getMicro() == actual.getMicro()) {
        if (!Strings.isNullOrEmpty(expected.getQualifier())) {
            final String expectedQualifier = expected.getQualifier();
            if ("qualifier".equals(expectedQualifier)) {
                if (!Strings.isNullOrEmpty(actual.getQualifier())) {
                    return;
                }
            }
            if (Objects.equal(expected, actual.getQualifier())) {
                return;
            }
        } else {
            return;
        }
    }
    throw new ComparisonFailure("Not same versions", expected.toString(), actual.toString());
}
Example 50
Project: sql-layer-master  File: IndexScanUnboundedMixedOrderDT.java View source code
@SuppressWarnings("unchecked")
protected void compare(List<List<Integer>> expectedResults, List<List<?>> results) {
    int eSize = expectedResults.size();
    int aSize = results.size();
    boolean match = true;
    for (int i = 0; match && i < Math.min(eSize, aSize); ++i) {
        match = rowComparator.compare(expectedResults.get(i), (List<Integer>) results.get(i)) == 0;
    }
    if (!match || (eSize != aSize)) {
        throw new ComparisonFailure("row mismatch", Strings.join(expectedResults), Strings.join(results));
    }
}
Example 51
Project: vert.x-master  File: AsyncTestBaseTest.java View source code
@Test
public void testAssertionFailedFromOtherThreadAwaitBeforeAssertAndTestComplete() {
    executor.execute(() -> {
        //Pause to make sure await() is called before assertion and testComplete
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            fail(e.getMessage());
        }
        assertEquals("foo", "bar");
        testComplete();
    });
    try {
        await();
    } catch (ComparisonFailure error) {
        assertTrue(error.getMessage().startsWith("expected:"));
    }
}
Example 52
Project: Achilles-master  File: CassandraLogAsserter.java View source code
public void assertSerialConsistencyLevels(ConsistencyLevel serialConsistencyLevel, ConsistencyLevel... consistencyLevels) {
    final List<ConsistencyLevel> expectedConsistencyLevels = consistencyLevels != null ? asList(consistencyLevels) : Arrays.<ConsistencyLevel>asList();
    final Iterator<ConsistencyLevel> clIterator = expectedConsistencyLevels.iterator();
    final Iterator<String> standardOutputs = asList(split(logStream.toString(), "\n")).iterator();
    try {
        if (expectedConsistencyLevels.isEmpty()) {
            boolean foundSerialCL = false;
            while (standardOutputs.hasNext()) {
                final String logLine = standardOutputs.next();
                if (pattern.matcher(logLine).find() && logLine.contains("serialCl=" + serialConsistencyLevel.name())) {
                    foundSerialCL |= true;
                }
            }
            if (!foundSerialCL) {
                throw new ComparisonFailure("Cannot find serialConsistencyLevel", serialConsistencyLevel.name(), "nothing found");
            }
        } else {
            List<ConsistencyLevel> founds = new LinkedList<>();
            ConsistencyLevel consistencyLevel = clIterator.next();
            boolean foundSerialCL = false;
            while (standardOutputs.hasNext()) {
                final String logLine = standardOutputs.next();
                if (pattern.matcher(logLine).find() && logLine.contains("cl=" + consistencyLevel.name())) {
                    founds.add(consistencyLevel);
                    if (logLine.contains("serialCl=" + serialConsistencyLevel.name())) {
                        foundSerialCL |= true;
                    }
                    if (clIterator.hasNext()) {
                        consistencyLevel = clIterator.next();
                    } else {
                        break;
                    }
                }
            }
            assertThat(foundSerialCL).describedAs("serialConsistencyLevel " + serialConsistencyLevel.name() + " has been found").isTrue();
            assertThat(founds).describedAs("expected consistency levels").isEqualTo(expectedConsistencyLevels);
        }
    } finally {
        logStream = null;
        logger.setLevel(Level.WARN);
        logger.detachAppender(writerAppender);
        writerAppender.stop();
    }
}
Example 53
Project: keycloak-master  File: AdminEventAuthDetailsTest.java View source code
@Test
public void testAuth() {
    testClient(MASTER, ADMIN, ADMIN, Constants.ADMIN_CLI_CLIENT_ID, MASTER, masterAdminCliUuid, masterAdminUserId);
    testClient(MASTER, "admin2", "password", Constants.ADMIN_CLI_CLIENT_ID, MASTER, masterAdminCliUuid, masterAdminUser2Id);
    testClient("test", "admin1", "password", Constants.ADMIN_CLI_CLIENT_ID, realmUuid, adminCliUuid, admin1Id);
    testClient("test", "admin2", "password", Constants.ADMIN_CLI_CLIENT_ID, realmUuid, adminCliUuid, admin2Id);
    testClient("test", "admin1", "password", "client1", realmUuid, client1Uuid, admin1Id);
    testClient("test", "admin2", "password", "client1", realmUuid, client1Uuid, admin2Id);
    // Should fail due to different client UUID
    try {
        testClient("test", "admin1", "password", "client1", realmUuid, adminCliUuid, admin1Id);
        Assert.fail("Not expected to pass");
    } catch (ComparisonFailure expected) {
    }
    // Should fail due to different user ID
    try {
        testClient("test", "admin1", "password", "client1", realmUuid, client1Uuid, admin2Id);
        Assert.fail("Not expected to pass");
    } catch (ComparisonFailure expected) {
    }
}
Example 54
Project: spock-master  File: JUnitSupervisor.java View source code
// enables IDE support (diff dialog)
private Throwable convertToComparisonFailure(Throwable exception) {
    assert isFailedEqualityComparison(exception);
    ConditionNotSatisfiedError conditionNotSatisfiedError = (ConditionNotSatisfiedError) exception;
    Condition condition = conditionNotSatisfiedError.getCondition();
    ExpressionInfo expr = condition.getExpression();
    String actual = renderValue(expr.getChildren().get(0).getValue());
    String expected = renderValue(expr.getChildren().get(1).getValue());
    ComparisonFailure failure = new SpockComparisonFailure(condition, expected, actual);
    failure.setStackTrace(exception.getStackTrace());
    if (conditionNotSatisfiedError.getCause() != null) {
        failure.initCause(conditionNotSatisfiedError.getCause());
    }
    return failure;
}
Example 55
Project: Spoon-master  File: CtGenerationTest.java View source code
@Test
public void testGenerateReplacementVisitor() throws Exception {
    //use always LINUX line separator, because generated files are committed to Spoon repository which expects that. 
    System.setProperty("line.separator", "\n");
    final Launcher launcher = new Launcher();
    launcher.getEnvironment().setAutoImports(false);
    launcher.getEnvironment().setNoClasspath(true);
    launcher.getEnvironment().setCommentEnabled(true);
    launcher.getEnvironment().useTabulations(true);
    //launcher.getEnvironment().setAutoImports(true);
    launcher.setSourceOutputDirectory("./target/generated/");
    // interfaces.
    launcher.addInputResource("./src/main/java/spoon/reflect/code");
    launcher.addInputResource("./src/main/java/spoon/reflect/declaration");
    launcher.addInputResource("./src/main/java/spoon/reflect/reference");
    launcher.addInputResource("./src/main/java/spoon/reflect/internal");
    // Utils.
    launcher.addInputResource("./src/main/java/spoon/reflect/visitor/CtScanner.java");
    launcher.addInputResource("./src/main/java/spoon/generating/replace/");
    launcher.addProcessor(new ReplacementVisitorGenerator());
    launcher.setOutputFilter(new RegexFilter("spoon.support.visitor.replace.*"));
    launcher.run();
    // cp ./target/generated/spoon/support/visitor/replace/ReplacementVisitor.java ./src/main/java/spoon/support/visitor/replace/ReplacementVisitor.java
    CtClass<Object> actual = build(new File(launcher.getModelBuilder().getSourceOutputDirectory() + "/spoon/support/visitor/replace/ReplacementVisitor.java")).Class().get("spoon.support.visitor.replace.ReplacementVisitor");
    CtClass<Object> expected = build(new File("./src/main/java/spoon/support/visitor/replace/ReplacementVisitor.java")).Class().get("spoon.support.visitor.replace.ReplacementVisitor");
    try {
        assertThat(actual).isEqualTo(expected);
    } catch (AssertionError e) {
        throw new ComparisonFailure("ReplacementVisitor different", expected.toString(), actual.toString());
    }
}
Example 56
Project: spotless-master  File: ResourceHarness.java View source code
@Override
protected void failed(Throwable e, Description description) {
    if (e instanceof ComparisonFailure) {
        ComparisonFailure failure = (ComparisonFailure) e;
        String msg = "";
        msg += String.format("Output:  %n%1$s%n%2$s%n%1$s%n", COMPARISON_SEPARATOR, failure.getActual());
        msg += String.format("Expected:%n%1$s%n%2$s%n%1$s%n", COMPARISON_SEPARATOR, failure.getExpected());
        logFailure(msg, description);
    }
}
Example 57
Project: streamflyer-master  File: RegexModifierUnitTest.java View source code
/**
     * See <a href="http://www.regular-expressions.info/continue.html>Continuing at The End of The Previous Match</a>
     * 
     * @throws Exception
     */
@Test
public void testBoundaryMatchers6_G_TheEndOfThePreviousMatch_MISSING_FEATURE() throws Exception {
    // it's nice that this works here but this is because it matches at
    // EVERY position here
    assertReplacementByReader("yzyz", "\\G(y|z)", "x", 1, 1024, "xxxx", 0);
    assertReplacementByReader("yzyzyzyzyzyz", "\\G(y|z)", "x", 1, 2, "xxxxxxxxxxxx", 0);
    // there are other cases that are not supported:
    try {
        assertReplacementByReader("azyzazyz", "(y)|(\\Gz)", "x", 1, 2, "azxxazxx", 0);
        fail("ComparisonFailure expected");
    } catch (ComparisonFailure e) {
        assertEquals("expected:<a[zxxaz]xx> but was:<a[xxxax]xx>", e.getMessage());
    }
}
Example 58
Project: truth-master  File: ThrowableSubjectTest.java View source code
@Test
public void hasMessageThat_failure() {
    NullPointerException actual = new NullPointerException("message");
    try {
        assertThat(actual).hasMessageThat().isEqualTo("foobar");
        throw new Error("Expected to fail.");
    } catch (ComparisonFailure expected) {
        assertThat(expected.getMessage()).isEqualTo("Unexpected message for java.lang.NullPointerException: " + "expected:<[foobar]> but was:<[message]>");
        assertErrorHasActualAsCause(actual, expected);
    }
}
Example 59
Project: xwiki-rendering-master  File: RenderingTest.java View source code
/**
     * Compare the passed expected string with the passed result.
     * We support regexes for comparison usng the format: ${{{regex:...}}}. For example:
     * <code>
     *  .#-----------------------------------------------------
     *  .expect|event/1.0
     *  .#-----------------------------------------------------
     *  beginDocument
     *  beginMacroMarkerStandalone [useravatar] [username=XWiki.UserNotExisting]
     *  beginGroup [[class]=[xwikirenderingerror]]
     *  onWord [Failed to execute the [useravatar] macro]
     *  endGroup [[class]=[xwikirenderingerror]]
     *  beginGroup [[class]=[xwikirenderingerrordescription hidden]]
     *  onVerbatim [org.xwiki.rendering.macro.MacroExecutionException: User [XWiki.UserNotExisting]${{{regex:.*}}}]
     *  endGroup [[class]=[xwikirenderingerrordescription hidden]]
     *  endMacroMarkerStandalone [useravatar] [username=XWiki.UserNotExisting]
     *  endDocument
     * </code>
     */
private void assertExpectedResult(String expected, String result) {
    StringBuilder builder = new StringBuilder();
    normalizeExpectedValue(builder, expected);
    Pattern pattern = Pattern.compile(builder.toString(), Pattern.DOTALL);
    Matcher matcher = pattern.matcher(result);
    if (!matcher.matches()) {
        throw new ComparisonFailure("", expected, result);
    }
}
Example 60
Project: cxf-master  File: ProcessorTestBase.java View source code
public boolean assertXmlEquals(final File expected, final File source, final List<String> ignoreAttr) throws Exception {
    List<Tag> expectedTags = ToolsStaxUtils.getTags(expected);
    List<Tag> sourceTags = ToolsStaxUtils.getTags(source);
    Iterator<Tag> iterator = sourceTags.iterator();
    for (Tag expectedTag : expectedTags) {
        Tag sourceTag = iterator.next();
        if (!expectedTag.getName().equals(sourceTag.getName())) {
            throw new ComparisonFailure("Tags not equal: ", expectedTag.getName().toString(), sourceTag.getName().toString());
        }
        for (Map.Entry<QName, String> attr : expectedTag.getAttributes().entrySet()) {
            if (ignoreAttr.contains(attr.getKey().getLocalPart())) {
                continue;
            }
            if (sourceTag.getAttributes().containsKey(attr.getKey())) {
                if (!sourceTag.getAttributes().get(attr.getKey()).equals(attr.getValue())) {
                    throw new ComparisonFailure("Attributes not equal: ", attr.getKey() + ":" + attr.getValue(), attr.getKey() + ":" + sourceTag.getAttributes().get(attr.getKey()));
                }
            } else {
                throw new AssertionError("Attribute: " + attr + " is missing in the source file.");
            }
        }
        if (!StringUtils.isEmpty(expectedTag.getText()) && !expectedTag.getText().equals(sourceTag.getText())) {
            throw new ComparisonFailure("Text not equal: ", expectedTag.getText(), sourceTag.getText());
        }
    }
    return true;
}
Example 61
Project: kotlin-master  File: KotlinDebuggerTestCase.java View source code
@Override
protected void checkTestOutput() throws Exception {
    if (KotlinTestUtils.isAllFilesPresentTest(getTestName(false))) {
        return;
    }
    try {
        super.checkTestOutput();
    } catch (ComparisonFailure e) {
        KotlinTestUtils.assertEqualsToFile(new File(getTestAppPath() + File.separator + "outs" + File.separator + getTestName(true) + ".out"), e.getActual());
    }
}
Example 62
Project: spring-loaded-master  File: GenerativeTest.java View source code
/**
	 * This method is called by the test runner to compare predicted results against actual results.
	 * <p>
	 * Override this method to customise how you want these compared.
	 * 
	 * @param expected Result from the 'generative' test run.
	 * @param actual Result from the actual test run.
	 */
protected final void assertEqualIResults(IResult expected, IResult actual) {
    if (expected.equals(actual)) {
        return;
    }
    if (expected.getClass() != actual.getClass()) {
        //ever be treated as equivalent!
        throw new ComparisonFailure(null, expected.toString(), actual.toString());
    }
    if (expected instanceof Result) {
        assertEqualResults((Result) expected, (Result) actual);
    } else if (expected instanceof ResultException) {
        assertEqualExceptions((ResultException) expected, (ResultException) actual);
    } else {
        //I don't what it is?? There are only two implementations of the interface
        throw new ComparisonFailure(null, expected.toString(), actual.toString());
    }
}
Example 63
Project: oakgp-master  File: NodeSimplifierTest.java View source code
@Test
public void testSanityCheckDoesFail() {
    // check that the "when/expect" pattern used in these tests does actually fail when the results are not as expected
    try {
        when("(+ v0 v1)").expect("(+ v1 v0)");
        fail();
    } catch (ComparisonFailure e) {
        assertEquals("9 vs. 9 expected:<(+ v[1 v0])> but was:<(+ v[0 v1])>", e.getMessage());
    }
}
Example 64
Project: parquet-mr-master  File: TestParquetWriteProtocol.java View source code
@Test
public void testMap() throws Exception {
    String[] expectations = { "startMessage()", "startField(name, 0)", "addBinary(map_name)", "endField(name, 0)", "startField(names, 1)", "startGroup()", "startField(map, 0)", "startGroup()", "startField(key, 0)", "addBinary(foo)", "endField(key, 0)", "startField(value, 1)", "addBinary(bar)", "endField(value, 1)", "endGroup()", "startGroup()", "startField(key, 0)", "addBinary(foo2)", "endField(key, 0)", "startField(value, 1)", "addBinary(bar2)", "endField(value, 1)", "endGroup()", "endField(map, 0)", "endGroup()", "endField(names, 1)", "endMessage()" };
    String[] expectationsAlt = { "startMessage()", "startField(name, 0)", "addBinary(map_name)", "endField(name, 0)", "startField(names, 1)", "startGroup()", "startField(map, 0)", "startGroup()", "startField(key, 0)", "addBinary(foo2)", "endField(key, 0)", "startField(value, 1)", "addBinary(bar2)", "endField(value, 1)", "endGroup()", "startGroup()", "startField(key, 0)", "addBinary(foo)", "endField(key, 0)", "startField(value, 1)", "addBinary(bar)", "endField(value, 1)", "endGroup()", "endField(map, 0)", "endGroup()", "endField(names, 1)", "endMessage()" };
    final Map<String, String> map = new TreeMap<String, String>();
    map.put("foo", "bar");
    map.put("foo2", "bar2");
    TestMap testMap = new TestMap("map_name", map);
    try {
        validatePig(expectations, testMap);
    } catch (ComparisonFailure e) {
        validatePig(expectationsAlt, testMap);
    }
    validateThrift(expectations, testMap);
}
Example 65
Project: pig-master  File: TestPigTest.java View source code
@Test
public void testSpecificOrderOutput() throws Exception {
    String[] args = { "n=3", "reducers=1", "input=top_queries_input_data.txt", "output=top_3_queries" };
    test = new PigTest(PIG_SCRIPT, args);
    String[] reorderedExpectedOutput = { "(twitter,7)", "(yahoo,25)", "(facebook,15)" };
    try {
        test.assertOutput(reorderedExpectedOutput);
        fail("assertOutput should fail when the records are unordered.");
    } catch (ComparisonFailure e) {
    }
}
Example 66
Project: rapidminer-5-master  File: RapidAssert.java View source code
/**
	 * Tests if the two IOObjects are equal and appends the given message.
	 * @param assertEqualAnnotations if true, annotations will be compared. If false, they will be ignored.
	 * @param expectedIOO
	 * @param actualIOO
	 */
public static void assertEquals(String message, IOObject expectedIOO, IOObject actualIOO, boolean assertEqualAnnotations) {
    /*
		 * Do not forget to add a newly supported class to the 
		 * ASSERTER_REGISTRY!!!
		 */
    List<Asserter> asserterList = ASSERTER_REGISTRY.getAsserterForObjects(expectedIOO, actualIOO);
    if (asserterList != null) {
        for (Asserter asserter : asserterList) {
            asserter.assertEquals(message, expectedIOO, actualIOO);
        }
    } else {
        throw new ComparisonFailure("Comparison of the two given IOObject classes " + expectedIOO.getClass() + " and " + actualIOO.getClass() + " is not supported. ", expectedIOO.toString(), actualIOO.toString());
    }
    // last, compare annotations:
    if (assertEqualAnnotations) {
        Annotations expectedAnnotations = expectedIOO.getAnnotations();
        Annotations actualAnnotations = actualIOO.getAnnotations();
        if (ignoreRepositoryNameForSourceAnnotation) {
            // (that's what all the regular expressions here are for)
            for (String key : expectedAnnotations.getKeys()) {
                String expectedValue = expectedAnnotations.getAnnotation(key);
                String actualValue = actualAnnotations.getAnnotation(key);
                if (expectedValue != null) {
                    Assert.assertNotNull(message + "objects are equal, but annotation '" + key + "' is missing", actualValue);
                }
                if (Annotations.KEY_SOURCE.equals(key)) {
                    if (expectedValue != null && expectedValue.startsWith("//") && expectedValue.matches("//[^/]+/.*")) {
                        expectedValue = expectedValue.replaceAll("^//[^/]+/", "//repository/");
                        if (actualValue != null) {
                            actualValue = actualValue.replaceAll("^//[^/]+/", "//repository/");
                        }
                    }
                }
                Assert.assertEquals(message + "objects are equal, but annotation '" + key + "' differs: ", expectedValue, actualValue);
            }
        } else {
            Assert.assertEquals(message + "objects are equal, but annotations differ: ", expectedAnnotations, actualAnnotations);
        }
    }
}
Example 67
Project: streamex-master  File: TestHelpers.java View source code
/**
     * Run the runnable automatically adding given message to every failed assertion
     * 
     * @param message message to prepend
     * @param r runnable to run
     */
private static void withMessage(String message, Runnable r) {
    try {
        r.run();
    } catch (ComparisonFailure cmp) {
        ComparisonFailure ex = new ComparisonFailure(message + ": " + cmp.getMessage(), cmp.getExpected(), cmp.getActual());
        ex.setStackTrace(cmp.getStackTrace());
        throw ex;
    } catch (AssertionError err) {
        AssertionError ex = new AssertionError(message + ": " + err.getMessage(), err.getCause());
        ex.setStackTrace(err.getStackTrace());
        throw ex;
    } catch (RuntimeExceptionError |  err) {
        throw new RuntimeException(message + ": " + err.getMessage(), err);
    }
}
Example 68
Project: xapi-master  File: GwtcSteps.java View source code
@Then("^confirm source \"([^\"]*)\" matches:$")
public void confirmSourceMatches(String componentName, List<String> lines) throws Throwable {
    class Matches {

        int expectedLine;

        String expected;

        int actualLine;

        String actual;

        public Matches(int expectedLine, String expected) {
            this.expectedLine = expectedLine;
            this.expected = expected;
        }
    }
    List<Matches> matches = new ArrayList<>();
    lines.stream().filter( line -> !line.trim().isEmpty()).forEach( line -> {
        for (String subLine : line.split("\n|\\\\n")) {
            if (!subLine.trim().isEmpty()) {
                matches.add(new Matches(matches.size(), subLine));
            }
        }
    });
    final String source = sources.get(componentName);
    assertNotNull(source);
    int lineNum = 0;
    for (String line : source.split("\n|\\\\n")) {
        if (!line.trim().isEmpty()) {
            if (lineNum >= matches.size()) {
                // failure just in line size...
                break;
            }
            final Matches match = matches.get(lineNum);
            match.actualLine = lineNum++;
            match.actual = line;
        }
    }
    final Iterator<Matches> itr = matches.iterator();
    while (itr.hasNext()) {
        Matches match = itr.next();
        if (match.actual == null || !match.expected.replaceAll("\\s+", "").equals(match.actual.replaceAll("\\s+", ""))) {
            StringBuilder restExpected = new StringBuilder();
            StringBuilder restActual = new StringBuilder();
            while (true) {
                restExpected.append(match.expectedLine).append('\t').append(match.expected).append("\n");
                restActual.append(match.actualLine).append('\t').append(match.actual).append("\n");
                if (!itr.hasNext()) {
                    break;
                }
                match = itr.next();
            }
            throw new ComparisonFailure("Expected source failed on line " + match.expectedLine + ": \n" + match.expected + "\n" + "Action source match @ line " + match.actualLine + "\n" + match.actual + "\n" + "Rest of expected source:\n" + restExpected + "\n" + "Rest of actual source:\n" + restActual + "\n" + " Full actual source: \n" + source, match.expected, match.actual);
        }
    }
}
Example 69
Project: apache_ant-master  File: IntrospectionHelperTest.java View source code
@Test
public void testAddText() throws BuildException {
    ih.addText(p, this, "test");
    try {
        ih.addText(p, this, "test2");
        fail("test2 shouldn\'t be equal to test");
    } catch (BuildException be) {
        assertTrue(be.getCause() instanceof ComparisonFailure);
    }
    ih = IntrospectionHelper.getHelper(String.class);
    try {
        ih.addText(p, "", "test");
        fail("String doesn\'t support addText");
    } catch (BuildException be) {
    }
}
Example 70
Project: constellio-master  File: RecordsCacheAcceptanceTest.java View source code
@Test
public void testZeTestUtilityMethods() throws Exception {
    Transaction transaction = new Transaction();
    TestRecord record1 = (TestRecord) transaction.add(newRecordOf("1", zeCollectionSchemaWithoutCache).withTitle("a"));
    TestRecord record2 = (TestRecord) transaction.add(newRecordOf("2", zeCollectionSchemaWithPermanentCache).withTitle("b"));
    TestRecord record3 = (TestRecord) transaction.add(newRecordOf("3", zeCollectionSchemaWithPermanentCache).withTitle("c"));
    recordServices.execute(transaction);
    resetCacheAndQueries();
    recordServices.getDocumentById("2");
    recordServices.getDocumentById("3");
    assertThatRecord("2").isInCache();
    assertThatRecords("2", "3").areInCache();
    try {
        assertThatRecords("1", "2", "3").areInCache();
        fail("Exception expected");
    } catch (ComparisonFailure e) {
    }
    try {
        assertThatRecords("2", "3", "1").areInCache();
        fail("Exception expected");
    } catch (ComparisonFailure e) {
    }
    try {
        assertThatRecords("1", "inexistentRecord").areInCache();
        fail("Exception expected");
    } catch (ComparisonFailure e) {
    }
    try {
        assertThatRecords("2", "inexistentRecord").areInCache();
        fail("Exception expected");
    } catch (ComparisonFailure e) {
    }
    assertThatRecord("1").isNotInCache();
    assertThatRecords("1", "4").areNotInCache();
    assertThatRecords("1", "inexistentRecord").areNotInCache();
    try {
        assertThatRecords("2", "3").areNotInCache();
        fail("Exception expected");
    } catch (ComparisonFailure e) {
    }
    try {
        assertThatRecords("1", "2").areNotInCache();
        fail("Exception expected");
    } catch (ComparisonFailure e) {
    }
    try {
        assertThatRecords("2", "3", "1").areNotInCache();
        fail("Exception expected");
    } catch (ComparisonFailure e) {
    }
    assertThat(queriesListener.queries).isNotEmpty();
    try {
        recordServices.getDocumentById("42");
    } catch (NoSuchRecordWithId e) {
    }
    try {
        recordServices.getDocumentById("is");
    } catch (NoSuchRecordWithId e) {
    }
    try {
        recordServices.getDocumentById("magic");
    } catch (NoSuchRecordWithId e) {
    }
    assertThat(queriesListener.byIds).containsOnlyOnce("42", "is", "magic");
    queriesListener.clear();
    assertThat(queriesListener.queries).isEmpty();
    assertThat(queriesListener.byIds).isEmpty();
    Record modifiedRecord1 = record1.getCopyOfOriginalRecord().set(Schemas.TITLE, "modified title");
    recordServices.update(modifiedRecord1);
    assertThatGetDocumentsByIdReturnEqualRecord(modifiedRecord1);
    try {
        assertThatGetDocumentsByIdReturnEqualRecord(record1);
    } catch (ComparisonFailure e) {
    }
    assertThat(recordServices.getDocumentById(record1.getId()).getVersion()).isNotEqualTo(record1.getVersion()).isEqualTo(modifiedRecord1.getVersion());
}
Example 71
Project: framework-master  File: EscalatorSpacerTest.java View source code
@Test
public void scrollToRowWorksProperlyWithSpacers() throws Exception {
    selectMenuPath(FEATURES, SPACERS, ROW_MINUS1, SET_100PX);
    selectMenuPath(FEATURES, SPACERS, ROW_1, SET_100PX);
    /*
         * we check for row -2 instead of -1, because escalator has the one row
         * buffered underneath the footer
         */
    selectMenuPath(COLUMNS_AND_ROWS, BODY_ROWS, SCROLL_TO, ROW_75);
    Thread.sleep(500);
    assertEquals("Row 75: 0,75", getBodyCell(-2, 0).getText());
    selectMenuPath(COLUMNS_AND_ROWS, BODY_ROWS, SCROLL_TO, ROW_25);
    Thread.sleep(500);
    try {
        assertEquals("Row 25: 0,25", getBodyCell(0, 0).getText());
    } catch (ComparisonFailure retryForIE10andIE11) {
        assertEquals("Row 24: 0,24", getBodyCell(0, 0).getText());
    }
}
Example 72
Project: linuxtools-master  File: SWTUtils.java View source code
/**
	 * Executes <strong>synchronously</strong> the given {@link Runnable} in the
	 * default Display. The given {@link Runnable} is ran into a rapping
	 * {@link Runnable} that will catch the {@link ComparisonFailure} that may
	 * be raised during an assertion.
	 *
	 * @param runnable
	 *            the {@link Runnable} to execute
	 * @throws ComparisonFailure
	 *             if an assertion failed.
	 * @throws SWTException
	 *             if an {@link SWTException} occurred
	 */
public static void syncAssert(final Runnable runnable) throws SWTException, ComparisonFailure {
    final Queue<ComparisonFailure> failure = new ArrayBlockingQueue<>(1);
    final Queue<SWTException> swtException = new ArrayBlockingQueue<>(1);
    Display.getDefault().syncExec(() -> {
        try {
            runnable.run();
        } catch (ComparisonFailure e1) {
            failure.add(e1);
        } catch (SWTException e2) {
            swtException.add(e2);
        }
    });
    if (!failure.isEmpty()) {
        throw failure.poll();
    }
    if (!swtException.isEmpty()) {
        throw swtException.poll();
    }
}
Example 73
Project: nifi-master  File: TestListFile.java View source code
@Test
public void testAttributesSet() throws Exception {
    // create temp file and time constant
    final File file1 = new File(TESTDIR + "/file1.txt");
    assertTrue(file1.createNewFile());
    FileOutputStream fos = new FileOutputStream(file1);
    fos.write(new byte[1234]);
    fos.close();
    assertTrue(file1.setLastModified(time3millis));
    Long time3rounded = time3millis - time3millis % 1000;
    String userName = System.getProperty("user.name");
    // validate the file transferred
    runner.setProperty(ListFile.DIRECTORY, testDir.getAbsolutePath());
    runNext();
    runner.assertAllFlowFilesTransferred(ListFile.REL_SUCCESS);
    final List<MockFlowFile> successFiles1 = runner.getFlowFilesForRelationship(ListFile.REL_SUCCESS);
    assertEquals(1, successFiles1.size());
    // get attribute check values
    final Path file1Path = file1.toPath();
    final Path directoryPath = new File(TESTDIR).toPath();
    final Path relativePath = directoryPath.relativize(file1.toPath().getParent());
    String relativePathString = relativePath.toString();
    relativePathString = relativePathString.isEmpty() ? "." + File.separator : relativePathString + File.separator;
    final Path absolutePath = file1.toPath().toAbsolutePath();
    final String absolutePathString = absolutePath.getParent().toString() + File.separator;
    final FileStore store = Files.getFileStore(file1Path);
    final DateFormat formatter = new SimpleDateFormat(ListFile.FILE_MODIFY_DATE_ATTR_FORMAT, Locale.US);
    final String time3Formatted = formatter.format(time3rounded);
    // check standard attributes
    MockFlowFile mock1 = successFiles1.get(0);
    assertEquals(relativePathString, mock1.getAttribute(CoreAttributes.PATH.key()));
    assertEquals("file1.txt", mock1.getAttribute(CoreAttributes.FILENAME.key()));
    assertEquals(absolutePathString, mock1.getAttribute(CoreAttributes.ABSOLUTE_PATH.key()));
    assertEquals("1234", mock1.getAttribute(ListFile.FILE_SIZE_ATTRIBUTE));
    // check attributes dependent on views supported
    if (store.supportsFileAttributeView("basic")) {
        assertEquals(time3Formatted, mock1.getAttribute(ListFile.FILE_LAST_MODIFY_TIME_ATTRIBUTE));
        assertNotNull(mock1.getAttribute(ListFile.FILE_CREATION_TIME_ATTRIBUTE));
        assertNotNull(mock1.getAttribute(ListFile.FILE_LAST_ACCESS_TIME_ATTRIBUTE));
    }
    if (store.supportsFileAttributeView("owner")) {
        // look for username containment to handle Windows domains as well as Unix user names
        // org.junit.ComparisonFailure: expected:<[]username> but was:<[DOMAIN\]username>
        assertTrue(mock1.getAttribute(ListFile.FILE_OWNER_ATTRIBUTE).contains(userName));
    }
    if (store.supportsFileAttributeView("posix")) {
        assertNotNull("Group name should be set", mock1.getAttribute(ListFile.FILE_GROUP_ATTRIBUTE));
        assertNotNull("File permissions should be set", mock1.getAttribute(ListFile.FILE_PERMISSIONS_ATTRIBUTE));
    }
}
Example 74
Project: rapidminer-studio-master  File: RapidAssert.java View source code
/**
	 * Tests if the two IOObjects are equal and appends the given message.
	 *
	 * @param assertEqualAnnotations
	 *            if true, annotations will be compared. If false, they will be ignored.
	 * @param expectedIOO
	 * @param actualIOO
	 */
public static void assertEquals(String message, IOObject expectedIOO, IOObject actualIOO, boolean assertEqualAnnotations) {
    /*
		 * Do not forget to add a newly supported class to the ASSERTER_REGISTRY!!!
		 */
    List<Asserter> asserterList = ASSERTER_REGISTRY.getAsserterForObjects(expectedIOO, actualIOO);
    if (asserterList != null) {
        for (Asserter asserter : asserterList) {
            asserter.assertEquals(message, expectedIOO, actualIOO);
        }
    } else {
        throw new ComparisonFailure("Comparison of the two given IOObject classes " + expectedIOO.getClass() + " and " + actualIOO.getClass() + " is not supported. ", expectedIOO.toString(), actualIOO.toString());
    }
    // last, compare annotations:
    if (assertEqualAnnotations) {
        Annotations expectedAnnotations = expectedIOO.getAnnotations();
        Annotations actualAnnotations = actualIOO.getAnnotations();
        if (ignoreRepositoryNameForSourceAnnotation) {
            // (that's what all the regular expressions here are for)
            for (String key : expectedAnnotations.getKeys()) {
                String expectedValue = expectedAnnotations.getAnnotation(key);
                String actualValue = actualAnnotations.getAnnotation(key);
                if (expectedValue != null) {
                    Assert.assertNotNull(message + "objects are equal, but annotation '" + key + "' is missing", actualValue);
                }
                if (Annotations.KEY_SOURCE.equals(key)) {
                    if (expectedValue != null && expectedValue.startsWith("//") && expectedValue.matches("//[^/]+/.*")) {
                        expectedValue = expectedValue.replaceAll("^//[^/]+/", "//repository/");
                        if (actualValue != null) {
                            actualValue = actualValue.replaceAll("^//[^/]+/", "//repository/");
                        }
                    }
                }
                Assert.assertEquals(message + "objects are equal, but annotation '" + key + "' differs: ", expectedValue, actualValue);
            }
        } else {
            Assert.assertEquals(message + "objects are equal, but annotations differ: ", expectedAnnotations, actualAnnotations);
        }
    }
}
Example 75
Project: rapidminer-vega-master  File: RapidAssert.java View source code
/**
	 * Tests if the two IOObjects are equal and appends the given message.
	 * 
	 * @param expectedIOO
	 * @param actualIOO
	 */
public static void assertEquals(String message, IOObject expectedIOO, IOObject actualIOO) {
    if (expectedIOO instanceof ExampleSet && actualIOO instanceof ExampleSet)
        RapidAssert.assertEquals(message + "ExampleSets are not equal", (ExampleSet) expectedIOO, (ExampleSet) actualIOO, -1);
    else if (expectedIOO instanceof NumericalMatrix && actualIOO instanceof NumericalMatrix)
        RapidAssert.assertEquals(message + "Numerical matrices are not equal", (NumericalMatrix) expectedIOO, (NumericalMatrix) actualIOO);
    else if (expectedIOO instanceof IOObjectCollection) {
        @SuppressWarnings("unchecked") IOObjectCollection<IOObject> expectedCollection = (IOObjectCollection<IOObject>) expectedIOO;
        @SuppressWarnings("unchecked") IOObjectCollection<IOObject> actualCollection = (IOObjectCollection<IOObject>) actualIOO;
        RapidAssert.assertEquals(message + "Collection of IOObjects are not equal: ", expectedCollection, actualCollection);
    } else if (expectedIOO instanceof PerformanceVector && actualIOO instanceof PerformanceVector)
        RapidAssert.assertEquals(message + "Performance vectors are not equal", (PerformanceVector) expectedIOO, (PerformanceVector) actualIOO);
    else if (expectedIOO instanceof AverageVector && actualIOO instanceof AverageVector)
        RapidAssert.assertEquals(message + "Average vectors are not equals", (AverageVector) expectedIOO, (AverageVector) actualIOO);
    else {
        throw new ComparisonFailure("Comparison of the two given IOObject classes is not supported yet", expectedIOO.toString(), actualIOO.toString());
    }
}
Example 76
Project: vaadin-master  File: EscalatorSpacerTest.java View source code
@Test
public void scrollToRowWorksProperlyWithSpacers() throws Exception {
    selectMenuPath(FEATURES, SPACERS, ROW_MINUS1, SET_100PX);
    selectMenuPath(FEATURES, SPACERS, ROW_1, SET_100PX);
    /*
         * we check for row -3 instead of -1, because escalator has two rows
         * buffered underneath the footer
         */
    selectMenuPath(COLUMNS_AND_ROWS, BODY_ROWS, SCROLL_TO, ROW_75);
    Thread.sleep(500);
    assertEquals("Row 75: 0,75", getBodyCell(-3, 0).getText());
    selectMenuPath(COLUMNS_AND_ROWS, BODY_ROWS, SCROLL_TO, ROW_25);
    Thread.sleep(500);
    try {
        assertEquals("Row 25: 0,25", getBodyCell(0, 0).getText());
    } catch (ComparisonFailure retryForIE10andIE11) {
        assertEquals("Row 24: 0,24", getBodyCell(0, 0).getText());
    }
}
Example 77
Project: wala-mirror-master  File: TestForInBodyExtraction.java View source code
public void testRewriter(String testName, String in, String out) {
    File tmp = null;
    String expected = null;
    String actual = null;
    try {
        tmp = File.createTempFile("test", ".js");
        FileUtil.writeFile(tmp, in);
        CAstImpl ast = new CAstImpl();
        actual = new CAstDumper().dump(new ClosureExtractor(ast, ForInBodyExtractionPolicy.FACTORY).rewrite(parseJS(tmp, ast)));
        actual = eraseGeneratedNames(actual);
        FileUtil.writeFile(tmp, out);
        expected = new CAstDumper().dump(parseJS(tmp, ast));
        expected = eraseGeneratedNames(expected);
        Assert.assertEquals(testName, expected, actual);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ComparisonFailure e) {
        System.err.println("Comparison Failure in " + testName + "!");
        System.err.println(expected);
        System.err.println(actual);
        throw e;
    } finally {
        if (tmp != null && tmp.exists())
            tmp.delete();
    }
}
Example 78
Project: wro4j-master  File: WroTestUtils.java View source code
/**
   * Compares two strings by removing trailing spaces & tabs for correct comparison.
   */
public static void compare(final String expected, final String actual) {
    try {
        final String in = replaceTabsWithSpaces(expected.trim());
        final String out = replaceTabsWithSpaces(actual.trim());
        Assert.assertEquals(in, out);
        LOG.debug("Compare.... [OK]");
    } catch (final ComparisonFailure e) {
        LOG.error("Compare.... [FAIL]", e.getMessage());
        throw e;
    }
}
Example 79
Project: biojava-master  File: TestLongPdbVsMmCifParsing.java View source code
private void testSingleEntry(String pdbId) throws IOException, StructureException {
    Structure sCif = getCifStructure(pdbId);
    Structure sPdb = getPdbStructure(pdbId);
    assertNotNull(sCif);
    assertNotNull(sPdb);
    try {
        testStructureMethods(sPdb, sCif);
        testHeader(sPdb, sCif);
        testChains(sPdb, sCif);
    } catch (ComparisonFailure e) {
        System.out.println("\nComparison failure! Values follow:");
        System.out.println("Actual  : " + e.getActual());
        System.out.println("Expected: " + e.getExpected());
        throw e;
    }
}
Example 80
Project: delivery-pipeline-plugin-master  File: DeliveryPipelineViewTest.java View source code
private void assertEqualsList(List<ParametersAction> a1, List<ParametersAction> a2) {
    if (a1.size() != a2.size()) {
        throw new ComparisonFailure("Size not equal!", String.valueOf(a1.size()), String.valueOf(a2.size()));
    }
    for (int i = 0; i < a1.size(); i++) {
        ParametersAction action1 = a1.get(i);
        ParametersAction action2 = a2.get(i);
        assertEquals(action1.getParameters(), action2.getParameters());
    }
}
Example 81
Project: epp.mpc-master  File: SolutionCompatibilityFilterTest.java View source code
protected AssertionError adaptAssertionError(AssertionError error, String message) {
    if (message == null || message.equals(error.getMessage())) {
        return error;
    }
    AssertionError newError;
    if (error.getClass() == AssertionError.class) {
        newError = new AssertionError(message);
    } else if (error.getClass() == ComparisonFailure.class) {
        ComparisonFailure comparisonFailure = (ComparisonFailure) error;
        newError = new ComparisonFailure(message, comparisonFailure.getExpected(), comparisonFailure.getActual());
    } else {
        newError = new AssertionError(message);
        newError.initCause(error);
    }
    newError.setStackTrace(error.getStackTrace());
    return newError;
}
Example 82
Project: OkapiBarcode-master  File: SymbolTest.java View source code
/**
     * Verifies that the specified images match.
     *
     * @param expected the expected image to check against
     * @param actual the actual image
     */
private static void assertEqual(BufferedImage expected, BufferedImage actual) {
    int w = expected.getWidth();
    int h = expected.getHeight();
    Assert.assertEquals("width", w, actual.getWidth());
    Assert.assertEquals("height", h, actual.getHeight());
    int[] expectedPixels = new int[w * h];
    expected.getRGB(0, 0, w, h, expectedPixels, 0, w);
    int[] actualPixels = new int[w * h];
    actual.getRGB(0, 0, w, h, actualPixels, 0, w);
    for (int i = 0; i < expectedPixels.length; i++) {
        int expectedPixel = expectedPixels[i];
        int actualPixel = actualPixels[i];
        if (expectedPixel != actualPixel) {
            int x = i % w;
            int y = i / w;
            throw new ComparisonFailure("pixel at " + x + ", " + y, toHexString(expectedPixel), toHexString(actualPixel));
        }
    }
}
Example 83
Project: Owl-master  File: OutputSyntaxSortTestCase.java View source code
@Test
public void shouldOutputAllInSameOrder() throws OWLOntologyStorageException, OWLOntologyCreationException {
    masterConfigurator.withRemapAllAnonymousIndividualsIds(false);
    try {
        List<OWLOntology> ontologies = new ArrayList<>();
        List<String> set = new ArrayList<>();
        for (String s : input) {
            OWLOntology o = loadOntologyFromString(new StringDocumentSource(s, IRI.generateDocumentIRI(), new FunctionalSyntaxDocumentFormat(), null));
            set.add(saveOntology(o, format).toString());
            ontologies.add(o);
        }
        for (int i = 0; i < ontologies.size() - 1; i++) {
            equal(ontologies.get(i), ontologies.get(i + 1));
        }
        for (int i = 0; i < set.size() - 1; i++) {
            assertEquals(format.getKey() + " " + new ComparisonFailure("", set.get(i), set.get(i + 1)).getMessage(), set.get(i), set.get(i + 1));
        }
    } finally {
        masterConfigurator.withRemapAllAnonymousIndividualsIds(true);
    }
}
Example 84
Project: thucydides-master  File: WhenRecordingNewTestOutcomes.java View source code
@Test
public void a_failing_step_should_the_error_message_for_errors_with_complex_constructors() {
    Screenshot screenshot = new Screenshot("step_1.png", "Step 1", 800, new FailureCause(new ComparisonFailure("oh crap", "a", "b")));
    assertThat(screenshot.getError().getMessage(), is("oh crap expected:<[a]> but was:<[b]>"));
    assertThat(screenshot.getError().getStackTrace().length, is(greaterThan(0)));
}
Example 85
Project: jumi-master  File: Asserts.java View source code
public static void assertContainsSubStrings(String message, String actual, String[] expectedSubStrings) {
    if (!Strings.containsSubStrings(actual, expectedSubStrings)) {
        throw new ComparisonFailure(message, Strings.asLines(expectedSubStrings), actual);
    }
}
Example 86
Project: brave-master  File: ITSparkTracing.java View source code
/**
   * Async tests are ignored until https://github.com/perwendel/spark/issues/208
   */
@Override
@Test(expected = ComparisonFailure.class)
public void async() throws Exception {
    super.async();
}
Example 87
Project: FluentLenium-master  File: PageTest.java View source code
@Test(expectedExceptions = ComparisonFailure.class)
public void checkIsAtFailed() {
    page2.isAt();
}
Example 88
Project: junit-master  File: ComparisonFailureTest.java View source code
@Test
public void compactFailureMessage() {
    ComparisonFailure failure = new ComparisonFailure("", expected, actual);
    assertEquals(message, failure.getMessage());
}
Example 89
Project: junit4-master  File: ComparisonFailureTest.java View source code
@Test
public void compactFailureMessage() {
    ComparisonFailure failure = new ComparisonFailure("", expected, actual);
    assertEquals(message, failure.getMessage());
}
Example 90
Project: lambda-tutorial-master  File: StringWithComparisonMatcher.java View source code
@Override
protected boolean matchesSafely(String actual, Description mismatchDescription) {
    if (!expected.equals(actual)) {
        String compactedMismatch = new ComparisonFailure("did not match:", expected, actual).getMessage();
        mismatchDescription.appendText(compactedMismatch);
        return false;
    }
    return true;
}
Example 91
Project: RoboBuggy-master  File: ComparisonFailureTest.java View source code
@Test
public void compactFailureMessage() {
    ComparisonFailure failure = new ComparisonFailure("", expected, actual);
    assertEquals(message, failure.getMessage());
}
Example 92
Project: sosies-generator-master  File: ComparisonFailureTest.java View source code
@Test
public void compactFailureMessage() {
    ComparisonFailure failure = new ComparisonFailure("", expected, actual);
    assertEquals(message, failure.getMessage());
}
Example 93
Project: fest-assertions-android-master  File: ShouldBeEqual.java View source code
private AssertionError newComparisonFailure(String description) throws Exception {
    String className = "org.junit.ComparisonFailure";
    Object o = constructorInvoker.newInstance(className, MSG_ARG_TYPES, msgArgs(description));
    if (o instanceof AssertionError)
        return (AssertionError) o;
    return null;
}
Example 94
Project: nuxeo-master  File: Assert.java View source code
/**
     * Asserts that two strings are equal even if their EOL are different. If they are not, an {@link AssertionError} is
     * thrown with the given message. If <code>expected</code> and <code>actual</code> are <code>null</code>, they are
     * considered equal.
     *
     * @param message the identifying message for the {@link AssertionError} ( <code>null</code> okay)
     * @param expected expected String with Windows or Unix like EOL
     * @param actual actual String with Windows or Unix like EOL
     * @see FileUtils#areFilesContentEquals(String, String)
     */
public static void assertFilesContentEquals(String message, String expected, String actual) {
    if (FileUtils.areFilesContentEquals(expected, actual)) {
        return;
    } else {
        String cleanMessage = message == null ? "" : message;
        throw new ComparisonFailure(cleanMessage, expected, actual);
    }
}
Example 95
Project: elasticsearch-river-jira-master  File: TestUtils.java View source code
/**
	 * Assert two strings with JSON to be equal.
	 * 
	 * @param expected
	 * @param actual
	 */
public static void assertJsonEqual(String expected, String actual) {
    if (!toJsonNode(expected).equals(toJsonNode(actual))) {
        throw new ComparisonFailure("JSON's are not equal", expected, actual);
    }
}
Example 96
Project: elasticsearch-river-remote-master  File: TestUtils.java View source code
/**
	 * Assert two strings with JSON to be equal.
	 * 
	 * @param expected
	 * @param actual
	 */
public static void assertJsonEqual(String expected, String actual) {
    if (!toJsonNode(expected).equals(toJsonNode(actual))) {
        throw new ComparisonFailure("JSON's are not equal", expected, actual);
    }
}
Example 97
Project: spring-batch-master  File: AssertFileTests.java View source code
@Test
public void testAssertEquals_notEqual() throws Exception {
    try {
        executeAssertEquals("input1.txt", "input2.txt");
        fail();
    } catch (ComparisonFailure e) {
        assertTrue(e.getMessage().startsWith("Line number 3 does not match."));
    }
}
Example 98
Project: tablesaw-master  File: SortTest.java View source code
/**
     * Verify data that is not sorted descending does match data that has been
     * (this test verifies the accuracy of our positive tests)
     */
@Test(expected = ComparisonFailure.class)
public void sortDescendingNegative() {
    Table sortedTable = unsortedTable.sortDescendingOn("IQ", "DOB");
    Table expectedResults = TestData.SIMPLE_SORTED_DATA_BY_INTEGER_AND_DATE_ASCENDING.getTable();
    compareTables(sortedTable, expectedResults);
}
Example 99
Project: cassandra-counters-master  File: IntegerTypeTest.java View source code
private static void assertSignum(String message, int expected, double value) {
    int signum = (int) Math.signum(value);
    if (signum != expected)
        throw new ComparisonFailure(message, Integer.toString(expected), Integer.toString(signum));
}
Example 100
Project: sql-parser-master  File: TestBase.java View source code
public static void assertEqualsWithoutPattern(String caseName, String expected, String actual, String regex) throws IOException {
    CompareWithoutHashes comparer = new CompareWithoutHashes(regex);
    if (!comparer.match(new StringReader(expected), new StringReader(actual)))
        throw new ComparisonFailure(caseName, comparer.converter(expected, actual), actual);
}
Example 101
Project: ACaZoo-master  File: IntegerTypeTest.java View source code
private static void assertSignum(String message, int expected, double value) {
    int signum = (int) Math.signum(value);
    if (signum != expected)
        throw new ComparisonFailure(message, Integer.toString(expected), Integer.toString(signum));
}