org.junit.ComparisonFailure Java Examples
The following examples show how to use
org.junit.ComparisonFailure.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TransactionPoolPropagationTest.java From besu with Apache License 2.0 | 6 votes |
/** * 2nd order test to verify the framework correctly fails if a disconnect occurs It could have a * more detailed exception check - more than just the class. */ @Test(expected = ComparisonFailure.class) public void disconnectShouldThrow() throws Exception { try (final TestNodeList txNodes = new TestNodeList()) { // Create & Start Nodes final TestNode node1 = txNodes.create(vertx, null, null, noDiscovery); txNodes.create(vertx, null, null, noDiscovery); txNodes.create(vertx, null, null, noDiscovery); initTest(txNodes); node1.network.getPeers().iterator().next().disconnect(DisconnectReason.BREACH_OF_PROTOCOL); wrapup(txNodes); } }
Example #2
Source File: XpectCompareCommandHandler.java From n4js with Eclipse Public License 1.0 | 6 votes |
/** * Display comparison view of test file with expected and actual xpect expectation */ private void displayComparisonView(ComparisonFailure cf, Description desc) { IXpectURIProvider uriProfider = XpectRunner.INSTANCE.getUriProvider(); IFile fileTest = null; if (uriProfider instanceof N4IDEXpectTestURIProvider) { N4IDEXpectTestURIProvider fileCollector = (N4IDEXpectTestURIProvider) uriProfider; fileTest = ResourcesPlugin.getWorkspace().getRoot() .getFileForLocation(new Path(fileCollector.findRawLocation(desc))); } if (fileTest != null && fileTest.isAccessible()) { N4IDEXpectCompareEditorInput inp = new N4IDEXpectCompareEditorInput(fileTest, cf); CompareUI.openCompareEditor(inp); } else { throw new RuntimeException("paths in descriptions changed!"); } }
Example #3
Source File: KafkaSecUtilsIT.java From bdt with Apache License 2.0 | 6 votes |
@Test public void checkTopicDoesNotExistWithExistentTopicTest() { String topic = "checktopicdoesnotexistwithexistenttopic"; Assertions.assertThatCode(() -> kafka_utils.createTopic(topic, null)).doesNotThrowAnyException(); Assertions.assertThatCode(() -> kafka_utils.checkTopicExists(topic)).doesNotThrowAnyException(); try { kafka_utils.checkTopicDoesNotExist(topic); } catch (AssertionError|Exception e) { Assertions.assertThat(e).isInstanceOf(ComparisonFailure.class); Assertions.assertThat(e).hasMessage("[Topic " + topic + " exists.] expected:<[fals]e> but was:<[tru]e>"); } Assertions.assertThatCode(() -> kafka_utils.deleteTopic(topic)).doesNotThrowAnyException(); Assertions.assertThatCode(() -> kafka_utils.checkTopicDoesNotExist(topic)).doesNotThrowAnyException(); }
Example #4
Source File: TestSpanMatcher.java From Markwon with Apache License 2.0 | 6 votes |
public static void textMatches( @NonNull Spanned spanned, int start, int end, @NonNull TestSpan.Text text) { final String expected = text.literal(); final String actual = spanned.subSequence(start, end).toString(); if (!expected.equals(actual)) { throw new ComparisonFailure( String.format(Locale.US, "Text mismatch at {start: %d, end: %d}", start, end), expected, actual ); } }
Example #5
Source File: PoetMatchers.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
public static Matcher<PoetClass> generatesTo(String expectedTestFile) { return new TypeSafeMatcher<PoetClass>() { @Override protected boolean matchesSafely(PoetClass spec) { String expectedClass = getExpectedClass(spec, expectedTestFile); String actualClass = generateClass(spec); try { assertThat(actualClass, equalToIgnoringWhiteSpace(expectedClass)); } catch (AssertionError e) { //Unfortunately for string comparisons Hamcrest doesn't really give us a nice diff. On the other hand //IDEs know how to nicely display JUnit's ComparisonFailure - makes debugging tests much easier throw new ComparisonFailure(String.format("Output class does not match expected [test-file: %s]", expectedTestFile), expectedClass, actualClass); } return true; } @Override public void describeTo(Description description) { //Since we bubble an exception this will never actually get called } }; }
Example #6
Source File: PoetMatchers.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
public static Matcher<ClassSpec> generatesTo(String expectedTestFile) { return new TypeSafeMatcher<ClassSpec>() { @Override protected boolean matchesSafely(ClassSpec spec) { String expectedClass = getExpectedClass(spec, expectedTestFile); String actualClass = generateClass(spec); try { assertThat(actualClass, equalToIgnoringWhiteSpace(expectedClass)); } catch (AssertionError e) { //Unfortunately for string comparisons Hamcrest doesn't really give us a nice diff. On the other hand //IDEs know how to nicely display JUnit's ComparisonFailure - makes debugging tests much easier throw new ComparisonFailure(String.format("Output class does not match expected [test-file: %s]", expectedTestFile), expectedClass, actualClass); } return true; } @Override public void describeTo(Description description) { //Since we bubble an exception this will never actually get called } }; }
Example #7
Source File: Assert.java From openCypher with Apache License 2.0 | 6 votes |
public static void assertEquals( Supplier<String> message, Object expected, Object actual ) { if ( !Objects.equals( expected, actual ) ) { if ( expected instanceof String && actual instanceof String ) { String cleanMessage = message.get(); if ( cleanMessage == null ) { cleanMessage = ""; } throw new ComparisonFailure( cleanMessage, (String) expected, (String) actual ); } else { fail( format( message.get(), expected, actual ) ); } } }
Example #8
Source File: PartialParsingProcessor.java From xtext-core with Eclipse Public License 2.0 | 6 votes |
@Override public String processFile(String completeData, String data, int offset, int len, String change) throws Exception { IParseResult initialParseResult = parser.parse(new StringReader(data)); String newData = applyDelta(data, offset, len, change); ReplaceRegion replaceRegion = new ReplaceRegion(offset, len, change); try { IParseResult reparsed = parser.reparse(initialParseResult, replaceRegion); IParseResult parsedFromScratch = parser.parse(new StringReader(newData)); assertEqual(data, newData, parsedFromScratch, reparsed); return newData; } catch(Throwable e) { ComparisonFailure throwMe = new ComparisonFailure(e.getMessage(), newData, replaceRegion + DELIM + data); throwMe.initCause(e); throw throwMe; } }
Example #9
Source File: RestApiTester.java From vespa with Apache License 2.0 | 6 votes |
public void assertFile(Request request, String responseFile) throws IOException { String expectedResponse = IOUtils.readFile(new File(responsesPath + responseFile)); expectedResponse = include(expectedResponse); expectedResponse = expectedResponse.replaceAll("(\"[^\"]*\")|\\s*", "$1"); // Remove whitespace String responseString = container.handleRequest(request).getBodyAsString(); if (expectedResponse.contains("(ignore)")) { // Convert expected response to a literal pattern and replace any ignored field with a pattern that matches // until the first stop character String stopCharacters = "[^,:\\\\[\\\\]{}]"; String expectedResponsePattern = Pattern.quote(expectedResponse) .replaceAll("\"?\\(ignore\\)\"?", "\\\\E" + stopCharacters + "*\\\\Q"); if (!Pattern.matches(expectedResponsePattern, responseString)) { throw new ComparisonFailure(responseFile + " (with ignored fields)", expectedResponsePattern, responseString); } } else { assertEquals(responseFile, expectedResponse, responseString); } }
Example #10
Source File: ProcessorTestBase.java From cxf with Apache License 2.0 | 6 votes |
protected void assertAttributesEquals(QName element, Map<QName, String> q1, Map<QName, String> q2, Collection<String> ignoreAttr) { for (Map.Entry<QName, String> attr : q1.entrySet()) { if (ignoreAttr.contains(attr.getKey().getLocalPart()) || ignoreAttr.contains(element.getLocalPart() + "@" + attr.getKey().getLocalPart())) { continue; } String found = q2.get(attr.getKey()); if (found == null) { throw new AssertionError("Attribute: " + attr.getKey() + " is missing in " + element); } if (!found.equals(attr.getValue())) { throw new ComparisonFailure("Attribute not equal: ", attr.getKey() + ":" + attr.getValue(), attr.getKey() + ":" + found); } } }
Example #11
Source File: XMLHttpRequestTest.java From htmlunit with Apache License 2.0 | 6 votes |
private void assertLog(final WebDriver driver, final String expected) throws InterruptedException { final long maxWait = System.currentTimeMillis() + DEFAULT_WAIT_TIME; while (true) { try { final String text = driver.findElement(By.id("log")).getAttribute("value").trim().replaceAll("\r", ""); assertEquals(expected, text); return; } catch (final ComparisonFailure e) { if (System.currentTimeMillis() > maxWait) { throw e; } Thread.sleep(10); } } }
Example #12
Source File: WebDriverTestCase.java From htmlunit with Apache License 2.0 | 6 votes |
/** * Asserts the current title is equal to the expectation string. * @param webdriver the driver in use * @param expected the expected object * @throws Exception in case of failure */ protected void assertTitle(final WebDriver webdriver, final String expected) throws Exception { final long maxWait = System.currentTimeMillis() + DEFAULT_WAIT_TIME; while (true) { try { assertEquals(expected, webdriver.getTitle()); return; } catch (final ComparisonFailure e) { if (System.currentTimeMillis() > maxWait) { throw e; } Thread.sleep(10); } } }
Example #13
Source File: MultithreadCustomerRepositoryTest.java From strategy-spring-security-acl with Apache License 2.0 | 6 votes |
private void prepareTaskAs(Runnable runnable, String lastName) { range(0, TIMES).forEach(i -> { tasks.add(() -> { Session.login(lastName); try { runnable.run(); } catch (ComparisonFailure failure) { throw new ComparisonFailure(lastName + ": " + failure.getMessage(), failure.getExpected(), failure.getActual()); } finally { Session.logout(); } return lastName; }); }); }
Example #14
Source File: AbstractFunctionalQuery.java From datawave with Apache License 2.0 | 6 votes |
/** * assertQuery is almost the same as Assert.assertEquals except that it will allow for different orderings of the terms within an AND or and OR. * * @param expected * The expected query * @param query * The query being tested */ protected void assertPlanEquals(String expected, String query) throws ParseException { // first do the quick check if (expected.equals(query)) { return; } ASTJexlScript expectedTree = JexlASTHelper.parseJexlQuery(expected); expectedTree = TreeFlatteningRebuildingVisitor.flattenAll(expectedTree); ASTJexlScript queryTree = JexlASTHelper.parseJexlQuery(query); queryTree = TreeFlatteningRebuildingVisitor.flattenAll(queryTree); TreeEqualityVisitor.Reason reason = new TreeEqualityVisitor.Reason(); boolean equal = TreeEqualityVisitor.isEqual(expectedTree, queryTree, reason); if (!equal) { throw new ComparisonFailure(reason.reason, expected, query); } }
Example #15
Source File: JedisCommandTestBase.java From cachecloud with Apache License 2.0 | 6 votes |
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 #16
Source File: AbstractSarlMavenTest.java From sarl with Apache License 2.0 | 6 votes |
/** Check if one of the markers has the given message part. * * @param messagePart * @param markers */ protected void assertContainsMarker(String messagePart, IMarker... markers) { StringBuilder markerText = new StringBuilder(); for (IMarker marker : markers) { try { String markerMsg = marker.getAttribute(IMarker.MESSAGE).toString(); if (markerMsg.contains(messagePart)) { return; } markerText.append(markerMsg); markerText.append("\n"); } catch (CoreException exception) { // } } throw new ComparisonFailure("Missed marker: " + messagePart, messagePart, markerText.toString()); }
Example #17
Source File: MultipleAssertionError.java From ogham with Apache License 2.0 | 5 votes |
private static String generateComparison(List<Throwable> failures, String name, Function<ComparisonFailure, String> getter) { StringJoiner joiner = new StringJoiner(FAILURE_SEPARATOR, name + " (" + failures.size() + "):\n", FAILURE_SEPARATOR); int idx = 1; for (Throwable f : failures) { String prefix = "Failure " + idx + ": " + getMessage(f) + "\n\n"; if (f instanceof ComparisonFailure) { joiner.add(indent(prefix + getter.apply((ComparisonFailure) f))); } else { joiner.add(indent(prefix + "</!\\ no comparison available>")); } idx++; } return joiner.toString(); }
Example #18
Source File: OrcasCoreSpoolTest.java From orcas with Apache License 2.0 | 5 votes |
@Test( expected = ComparisonFailure.class ) public void test() { String lTestFolderName = "spool_" + testName; deleteRecursive( new File( orcasCoreIntegrationConfig.getWorkfolder() + lTestFolderName ) ); resetUser( _connectParametersTargetUser ); executeScript( _connectParametersTargetUser, "testspool/tests/" + testName + "/" + "a.sql", orcasCoreIntegrationConfig.getAlternateTablespace1(), orcasCoreIntegrationConfig.getAlternateTablespace2() ); OrcasCoreIntegrationTest.extractSchema( _connectParametersTargetUser, "a", true, lTestFolderName, OrcasCoreIntegrationTest.DEFAULT_EXCLUDE, "dd.mm.yyyy", false, "" ); resetUser( _connectParametersTargetUser ); executeScript( _connectParametersTargetUser, "testspool/tests/" + testName + "/" + "b.sql", orcasCoreIntegrationConfig.getAlternateTablespace1(), orcasCoreIntegrationConfig.getAlternateTablespace2() ); OrcasCoreIntegrationTest.asserSchemaEqual( "a", "b", true, lTestFolderName, OrcasCoreIntegrationTest.DEFAULT_EXCLUDE, "dd.mm.yyyy", _connectParametersTargetUser, false ); }
Example #19
Source File: TestValidator.java From sarl with Apache License 2.0 | 5 votes |
public Validator assertNoIssues() { final List<Issue> issues = getIssues(); if (!isEmpty(issues)) { final String actual = this.testHelper.getIssuesAsString(this.resource, issues, new StringBuilder()).toString(); throw new ComparisonFailure("Expected no issues, but got :" + actual, "", actual); } return this; }
Example #20
Source File: TestRestApi.java From wicket-orientdb with Apache License 2.0 | 5 votes |
private static void assertContains(String where, String what) { if(what!=null && !what.contains(where)) { throw new ComparisonFailure("Expected containing.", where, what); } }
Example #21
Source File: CukeUtils.java From objectlabkit with Apache License 2.0 | 5 votes |
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 #22
Source File: RunOnServerTest.java From keycloak with Apache License 2.0 | 5 votes |
@Test public void runOnServerAssertOnServer() { try { testingClient.server().run(session -> assertEquals("foo", "bar")); fail("Expected exception"); } catch (ComparisonFailure e) { assertEquals("expected:<[foo]> but was:<[bar]>", e.getMessage()); } }
Example #23
Source File: ProcessorTestBase.java From cxf with Apache License 2.0 | 5 votes |
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 #24
Source File: TestValidator.java From sarl with Apache License 2.0 | 5 votes |
public Validator assertNoErrors() { final List<Issue> issues = getIssues(); final Iterable<Issue> fissues = filter(issues, input -> Severity.ERROR == input.getSeverity()); if (!isEmpty(fissues)) { final String actual = this.testHelper.getIssuesAsString(this.resource, issues, new StringBuilder()).toString(); throw new ComparisonFailure("Expected no errors, but got :" + actual, "", actual); } return this; }
Example #25
Source File: TestBase.java From sql-parser with Eclipse Public License 1.0 | 5 votes |
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 #26
Source File: IndexScanUnboundedMixedOrderDT.java From sql-layer with GNU Affero General Public License v3.0 | 5 votes |
@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 #27
Source File: DomainMappingTest.java From jcypher with Apache License 2.0 | 5 votes |
@Test public void testDomainInformation() { List<JcError> errors; IDomainAccess da = DomainAccessFactory.createDomainAccess(dbAccess, "TEST-1-DOMAIN"); IDomainAccess da1 = DomainAccessFactory.createDomainAccess(dbAccess, "TEST-2-DOMAIN"); Address address = new Address(); address.setCity("Vienna"); address.setStreet("Alserstrasse"); address.setNumber(10); errors = dbAccess.clearDatabase(); if (errors.size() > 0) { printErrors(errors); throw new JcResultException(errors); } errors = da.store(address); if (errors.size() > 0) { printErrors(errors); throw new JcResultException(errors); } errors = da1.store(address); if (errors.size() > 0) { printErrors(errors); throw new JcResultException(errors); } List<String> available = DomainInformation.availableDomains(dbAccess); try { assertEquals("[TEST-1-DOMAIN, TEST-2-DOMAIN]", available.toString()); } catch(ComparisonFailure e) { assertEquals("[TEST-2-DOMAIN, TEST-1-DOMAIN]", available.toString()); } return; }
Example #28
Source File: CompletionHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
@Test public void testCompletion_method_withLSPV3() throws JavaModelException{ ICompilationUnit unit = getWorkingCopy( "src/java/Foo.java", "public class Foo {\n"+ " void foo() {\n"+ "System.out.print(\"Hello\");\n" + "System.out.println(\" World!\");\n"+ "HashMap<String, String> map = new HashMap<>();\n"+ "map.pu\n" + " }\n"+ "}\n"); int[] loc = findCompletionLocation(unit, "map.pu"); CompletionList list = server.completion(JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]))).join().getRight(); assertNotNull(list); CompletionItem ci = list.getItems().stream() .filter( item-> item.getLabel().matches("put\\(String \\w+, String \\w+\\) : String")) .findFirst().orElse(null); assertNotNull(ci); assertEquals("put", ci.getInsertText()); assertTrue(ci.getDetail().matches("java.util.HashMap.put\\(String \\w+, String \\w+\\) : String")); assertEquals(CompletionItemKind.Method, ci.getKind()); assertEquals("999999019", ci.getSortText()); assertNotNull(ci.getTextEdit()); try { assertTextEdit(5, 4, 6, "put(${1:key}, ${2:value})", ci.getTextEdit()); } catch (ComparisonFailure e) { //In case the JDK has no sources assertTextEdit(5, 4, 6, "put(${1:arg0}, ${2:arg1})", ci.getTextEdit()); } assertNotNull(ci.getAdditionalTextEdits()); List<TextEdit> edits = ci.getAdditionalTextEdits(); assertEquals(2, edits.size()); }
Example #29
Source File: UnixPathTest.java From vespa with Apache License 2.0 | 5 votes |
private <T extends RuntimeException> void assertRuntimeException(Class<T> baseClass, String message, Runnable runnable) { try { runnable.run(); fail("No exception was thrown"); } catch (RuntimeException e) { if (!baseClass.isInstance(e)) { throw new ComparisonFailure("Exception class mismatch", baseClass.getName(), e.getClass().getName()); } assertEquals(message, e.getMessage()); } }
Example #30
Source File: ContainerTester.java From vespa with Apache License 2.0 | 5 votes |
public void assertResponse(Request request, File responseFile, int expectedStatusCode) { String expectedResponse = readTestFile(responseFile.toString()); expectedResponse = include(expectedResponse); expectedResponse = expectedResponse.replaceAll("(\"[^\"]*\")|\\s*", "$1"); // Remove whitespace FilterResult filterResult = invokeSecurityFilters(request); request = filterResult.request; Response response = filterResult.response != null ? filterResult.response : container.handleRequest(request); String responseString; try { responseString = response.getBodyAsString(); } catch (CharacterCodingException e) { throw new UncheckedIOException(e); } if (expectedResponse.contains("(ignore)")) { // Convert expected response to a literal pattern and replace any ignored field with a pattern that matches // until the first stop character String stopCharacters = "[^,:\\\\[\\\\]{}]"; String expectedResponsePattern = Pattern.quote(expectedResponse) .replaceAll("\"?\\(ignore\\)\"?", "\\\\E" + stopCharacters + "*\\\\Q"); if (!Pattern.matches(expectedResponsePattern, responseString)) { throw new ComparisonFailure(responseFile.toString() + " (with ignored fields)", expectedResponsePattern, responseString); } } else { assertEquals(responseFile.toString(), expectedResponse, responseString); } assertEquals("Status code", expectedStatusCode, response.getStatus()); }