private static void assertMatches(String message, String expected, String actual) { int posInExpected = 0; int posInActual = 0; while (posInExpected < expected.length()) { int placeholderPos = expected.indexOf(PLATFORM_SPECIFIC_PLACEHOLDER, posInExpected); if (placeholderPos < 0) { if (posInExpected == 0 ? actual.equals(expected) : actual.substring(posInActual).endsWith(expected.substring(posInExpected))) { return; } else { throw new ComparisonFailure(message, expected, actual); } } String fixedSubstring = expected.substring(posInExpected, placeholderPos); int matchedPosInActual = actual.indexOf(fixedSubstring, posInActual); if (matchedPosInActual < 0 || posInExpected == 0 && matchedPosInActual > 0) { throw new ComparisonFailure(message, expected, actual); } posInExpected = placeholderPos + PLATFORM_SPECIFIC_PLACEHOLDER.length(); posInActual = matchedPosInActual + fixedSubstring.length(); } }
protected void assertTranslation(String hql, Map replacements) { ComparisonFailure cf = null; try { assertTranslation( hql, replacements, false, null ); } catch ( ComparisonFailure e ) { e.printStackTrace(); cf = e; } if ("false".equals(System.getProperty("org.hibernate.test.hql.SkipScalarQuery","false"))) { // Run the scalar translation anyway, even if there was a comparison failure. assertTranslation( hql, replacements, true, null ); } if (cf != null) throw cf; }
@Test @TargetApi(24) public void testGetMobileNetworkTypeWith4G() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 24); try { TelephonyManager mockedTelephonyManager = mock(TelephonyManager.class); when(mockedTelephonyManager.getDataNetworkType()).thenReturn(TelephonyManager.NETWORK_TYPE_LTE); NetworkMonitor mockedNetworkMonitor = mock(NetworkMonitor.class); when(mockedNetworkMonitor.getTelephonyManager()).thenReturn(mockedTelephonyManager); when(mockedNetworkMonitor.getMobileNetworkType()).thenCallRealMethod(); assertEquals("4G", mockedNetworkMonitor.getMobileNetworkType()); } catch (NullPointerException | ComparisonFailure e){ } }
/** * Test if group cipher can handle high amounts of tasks and still work properly * * @throws Exception */ public void testGroupCipher() throws Exception { if(CipherSuiteTestsUtility.logReport) appendHeader("GroupCipherTest", outputs); ComparisonFailure ex = null; //initialise input byte[] plaintext = CipherTestVectors.getByteInput(); //start test byte[][] result = uut.encrypt(plaintext, keyList); for (int i = 0; i < result.length; ++i) { byte[] decrypted = uut.tryDecrypt(result[i], keyList); try { Assert.assertEquals(CipherSuiteTestsUtility.PLAINSIZE, decrypted.length); Assert.assertEquals(CipherTestVectors.testInput, new String(decrypted, CipherSuiteTestsUtility.charEncoding).trim()); } catch (ComparisonFailure e) { if(CipherSuiteTestsUtility.logReport) { appendDataSplit(outputs); appendGroupInfo(keyList.get(i), result[i], decrypted, true); } ex = e; } } if (ex != null) throw ex; }
/** * Check the mac collisions in the test input * @throws Exception */ public void testMacCollisions() throws Exception { if(CipherSuiteTestsUtility.logReport) appendHeader("Mac collisions",outputs); ComparisonFailure ex = null; byte[][] input = CipherSuiteTestsUtility.getSubArraysFromPacketArray(encryptedInput, CipherSuiteTestsUtility.macOffset, CipherSuiteTestsUtility.macLength); for(int j = 0; j < stressTestAmount - 1; j ++) for(int k = j+1; k < stressTestAmount; k++) try { assertFalse(bytesEqual(input[j], input[k], 0)); } catch (ComparisonFailure e){ if(CipherSuiteTestsUtility.logReport) { appendDataSplit(outputs); appendGroupInfo(keyList.get(j), encryptedInput[j], new byte[1], true); appendGroupInfo(keyList.get(k), encryptedInput[k], new byte[1], true); } ex = e; } if(ex != null) throw ex; }
/** * Check if any generated mac keys are equal */ public void testEqualMacKeys() { if(CipherSuiteTestsUtility.logReport) appendHeader("Mac key equals", outputs); ComparisonFailure ex = null; List<SecretKey> keys = CipherSuiteTestsUtility.getSpecificKeysFromGroupKeyList(keyList, false); for(int j = 0; j < stressTestAmount - 1; j ++) for(int k = j+1; k < stressTestAmount; k++) try { assertFalse(bytesEqual(keys.get(j).getEncoded(), keys.get(k).getEncoded(), 0)); } catch (ComparisonFailure e){ if(CipherSuiteTestsUtility.logReport) { appendDataSplit(outputs); appendMacKeyInfo(keys.get(j), j, outputs); appendMacKeyInfo(keys.get(k), k, outputs); } ex = e; } if(ex != null) throw ex; }
/** * Executes a scalar expression, and asserts that the result is within * delta of the expected result. * * @param expr MDX scalar expression * @param expected Expected value * @param delta Maximum allowed deviation from expected value */ public void assertExprReturns( String expr, double expected, double delta) { Object value = getTestContext().executeExprRaw(expr).getValue(); try { double actual = ((Number) value).doubleValue(); if (Double.isNaN(expected) && Double.isNaN(actual)) { return; } Assert.assertEquals( null, expected, actual, delta); } catch (ClassCastException ex) { String msg = "Actual value \"" + value + "\" is not a number."; throw new ComparisonFailure( msg, Double.toString(expected), String.valueOf(value)); } }
/** * {@link Processor} が生成したソースをクラスパス上のリソースと比較・検証します. * * @param expectedResource * 生成されたソースに期待される内容を持つリソースのパス * @param className * 生成されたクラスの完全限定名 * @throws IllegalStateException * {@link #compile()} が呼び出されていない場合 * @throws IOException * 入出力例外が発生した場合 * @throws SourceNotGeneratedException * ソースが生成されなかった場合 * @throws ComparisonFailure * 生成されたソースが期待される内容と一致しなかった場合 */ protected void assertEqualsGeneratedSourceWithResource( final String expectedResource, final String className) throws IllegalStateException, IOException, SourceNotGeneratedException, ComparisonFailure { assertNotEmpty("expectedResource", expectedResource); assertNotEmpty("className", className); assertCompiled(); final URL url = Thread .currentThread() .getContextClassLoader() .getResource(expectedResource); if (url == null) { throw new FileNotFoundException(expectedResource); } assertEqualsGeneratedSourceWithResource(url, className); }
/** * @param msg Message that should be reported to the template ns.author. Null means don't care. */ private void assertRewriteFails(@Nullable String msg, String... inputs) { try { rewrite(inputs); fail(); } catch (SoyAutoescapeException ex) { // Find the root cause; during contextualization, we re-wrap exceptions on the path to a // template. while (ex.getCause() instanceof SoyAutoescapeException) { ex = (SoyAutoescapeException) ex.getCause(); } if (msg != null && !msg.equals(ex.getMessage())) { throw (ComparisonFailure) new ComparisonFailure("", msg, ex.getMessage()).initCause(ex); } } }
protected void assertEpsilonEquals(MapLayer expected, MapLayer actual) { if (!Objects.equals(expected.getClass(), actual.getClass())) { throw new ComparisonFailure("Not same type", expected.getClass().toString(), //$NON-NLS-1$ actual.getClass().toString()); } if (!Objects.equals(actual.getGeoId(), expected.getGeoId())) { throw new ComparisonFailure("Not same GeoId", expected.getGeoId().toString(), //$NON-NLS-1$ actual.getGeoId().toString()); } if (!Objects.equals(expected.getClass(), actual.getClass())) { throw new ComparisonFailure("Not same hashCode", expected.hashKey().toString(), //$NON-NLS-1$ actual.getClass().toString()); } if (!Objects.equals(expected, actual)) { throw new ComparisonFailure("Not same objects", expected.toString(), //$NON-NLS-1$ actual.toString()); } }
protected void assertEpsilonEquals(MapElement expected, MapElement actual) { if (!Objects.equals(expected.getClass(), actual.getClass())) { throw new ComparisonFailure("Not same type", expected.getClass().toString(), //$NON-NLS-1$ actual.getClass().toString()); } if (!Objects.equals(actual.getGeoId(), expected.getGeoId())) { throw new ComparisonFailure("Not same GeoId", expected.getGeoId().toString(), //$NON-NLS-1$ actual.getGeoId().toString()); } if (!Objects.equals(expected.getClass(), actual.getClass())) { throw new ComparisonFailure("Not same hashCode", expected.hashKey().toString(), //$NON-NLS-1$ actual.getClass().toString()); } if (!Objects.equals(expected, actual)) { throw new ComparisonFailure("Not same objects", expected.toString(), //$NON-NLS-1$ actual.toString()); } }
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; }
private static void assertEvent(MockEventListener mockEventListener, EventType eventType, String value) { Event event = mockEventListener.pop(); if (event == null) { throw new AssertionFailedError( "Event expected, but no more events available"); } if (event.eventType != eventType) { throw new ComparisonFailure("Wrong Event Type", eventType.name(), event.eventType.name()); } if (value == null) { if (event.value != null) { throw new ComparisonFailure("Wrong Event Value", value, event.value); } } else if (!value.equals(event.value)) { throw new ComparisonFailure("Wrong Event Value", value, event.value); } }
public void intercept(IMethodInvocation invocation) throws Throwable { try { invocation.proceed(); } catch (Throwable t) { if (!annotation.type().isInstance(t)) { throw new WrongExceptionThrownError(annotation.type(), t); } if (!annotation.message().equals(t.getMessage())) { throw new ComparisonFailure("Unexpected message for exception.", annotation.message(), t.getMessage()); } return; } throw new WrongExceptionThrownError(annotation.type(), null); }
private void assertExactlyOrdered(List<String> proposals, List<String> required, CommaSeparatedValuesExpectationImpl expectation) { assertContainingMatchAllOrdered(proposals, required, expectation); // assert same length: if (proposals.size() != required.size()) throw new ComparisonFailure( "Ambiguity: All required proposal (right side) could match the ones the system provides." + " But, at least two required labels matched the same proposal." + " Your requirement on the right side is to sloppy. Please provide more specific labels." + " See the full proposal display strings in the comparison", required.stream().collect( Collectors.joining(",")), proposals.stream().collect(Collectors.joining(","))); }
/** Unordered comparison: same number of required and proposed */ private void assertExactly(List<String> proposals, List<String> required, ICommaSeparatedValuesExpectation expectation) { // ensure, that there are not more proposals then required/expected // assert same length: if (proposals.size() != required.size()) throw new ComparisonFailure( "System provides " + proposals.size() + " proposals, expected have been " + required.size() + ".", required.stream().collect(Collectors.joining(",")), proposals.stream().collect( Collectors.joining(","))); // ensure, that all required match a proposal. assertContainingMatchAll(proposals, required, expectation); }
/** * Assert that the given parameters contains an entry for * <code>paramValue</code> under the <code>paramName</code> key. <p/> * * @param parameters the map of parameters to check into * @param paramName the key of the value to be checked * @param paramValue the value to check for */ static void assertHasParameter(Map parameters, String paramName, String paramValue) { Object value = parameters.get(paramName); if (value == null) { throw new AssertionFailedError("Parameter [" + paramName + "] not found"); } if (value instanceof String) { if (!paramValue.equals(value)) { throw new ComparisonFailure("Incorrect value found", paramValue, (String) value); } } else if (value instanceof String[]) { // see if our value is among those in the array String[] values = (String[]) value; for (int i = 0; i < values.length; i++) { if (paramValue.equals(values[i])) { return; } } throw new AssertionFailedError( "Expected value not found for parameter [" + paramName + "]"); } else { // can't recognize the value throw new AssertionFailedError( "Unexpected type found as parameter value for [" + paramName + "]"); } }
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; }
private void checkResult(@NotNull String expectedFile, final boolean stripTrailingSpaces, @NotNull SelectionAndCaretMarkupLoader loader, @NotNull String actualText) { assertInitialized(); Project project = getProject(); Editor editor = getEditor(); if (editor instanceof EditorWindow) { editor = ((EditorWindow)editor).getDelegate(); } UsefulTestCase.doPostponedFormatting(getProject()); if (stripTrailingSpaces) { actualText = stripTrailingSpaces(actualText); } PsiDocumentManager.getInstance(project).commitAllDocuments(); String newFileText1 = loader.newFileText; if (stripTrailingSpaces) { newFileText1 = stripTrailingSpaces(newFileText1); } actualText = StringUtil.convertLineSeparators(actualText); if (!Comparing.equal(newFileText1, actualText)) { if (loader.filePath != null) { throw new FileComparisonFailure(expectedFile, newFileText1, actualText, loader.filePath); } else { throw new ComparisonFailure(expectedFile, newFileText1, actualText); } } EditorTestUtil.verifyCaretAndSelectionState(editor, loader.caretState, expectedFile); }
private static PacketFactory createExceptionNotification(Error assertion) { if (assertion instanceof KnownException) return ((KnownException)assertion).getPacketFactory(); if (assertion instanceof ComparisonFailure || assertion.getClass().getName().equals("org.junit.ComparisonFailure")) { return ComparisonDetailsExtractor.create(assertion); } return new ExceptionPacketFactory(PoolOfTestStates.FAILED_INDEX, assertion); }
public void testAssertNullNotEqualsString() { try { assertEquals(null, "foo"); fail(); } catch (ComparisonFailure e) { } }
public void testAssertStringNotEqualsNull() { try { assertEquals("foo", null); fail(); } catch (ComparisonFailure e) { e.getMessage(); // why no assertion? } }
public void testThrowing() { try { assertEquals("a", "b"); } catch (ComparisonFailure e) { return; } fail(); }
public static void assertEqualStreams(InputStream expected, InputStream actual) throws IOException { byte[] expectedBytes = ByteStreams.toByteArray(expected); byte[] actualBytes = ByteStreams.toByteArray(actual); if(!Arrays.equals(expectedBytes, actualBytes)) { throw new ComparisonFailure("Streams differ.", new String(expectedBytes), new String(actualBytes)); } }
@Test @TargetApi(24) public void testGetMobileNetworkTypeWith2G() throws Exception { setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 24); try { TelephonyManager mockedTelephonyManager = mock(TelephonyManager.class); when(mockedTelephonyManager.getDataNetworkType()).thenReturn(TelephonyManager.NETWORK_TYPE_GPRS); NetworkMonitor mockedNetworkMonitor = mock(NetworkMonitor.class); when(mockedNetworkMonitor.getTelephonyManager()).thenReturn(mockedTelephonyManager); when(mockedNetworkMonitor.getMobileNetworkType()).thenCallRealMethod(); assertEquals("2G", mockedNetworkMonitor.getMobileNetworkType()); when(mockedTelephonyManager.getDataNetworkType()).thenReturn(TelephonyManager.NETWORK_TYPE_EDGE); assertEquals("2G", mockedNetworkMonitor.getMobileNetworkType()); when(mockedTelephonyManager.getDataNetworkType()).thenReturn(TelephonyManager.NETWORK_TYPE_CDMA); assertEquals("2G", mockedNetworkMonitor.getMobileNetworkType()); when(mockedTelephonyManager.getDataNetworkType()).thenReturn(TelephonyManager.NETWORK_TYPE_1xRTT); assertEquals("2G", mockedNetworkMonitor.getMobileNetworkType()); when(mockedTelephonyManager.getDataNetworkType()).thenReturn(TelephonyManager.NETWORK_TYPE_IDEN); assertEquals("2G", mockedNetworkMonitor.getMobileNetworkType()); } catch (NullPointerException | ComparisonFailure e){ } }
@Override public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { try { base.evaluate(); } catch (ResultNotAcceptedException e) { throw new ComparisonFailure("unexpected result: ", e.getExpected().toString(), e.getActual().toString()); } } }; }
public void testExceptionToStringWithMessage() { try { assertEquals("woops!", "a", "b"); } catch (ComparisonFailure e) { if (!e.toString().startsWith("junit.framework.ComparisonFailure: woops! expected:<")) { fail("Unexpected message: " + e); } return; } fail(); }
public void testExceptionToStringWithoutMessage() { try { assertEquals("a", "b"); } catch (ComparisonFailure e) { if (!e.toString().startsWith("junit.framework.ComparisonFailure: expected:<")) { fail("Unexpected message: " + e); } return; } fail(); }
public static void assertEquals(String expected, String actual) { try { Assert.assertEquals(expected, actual); } catch (ComparisonFailure e) { throw new ComparisonFailure(String.format( "expected: \"%s\", was \"%s\"", expected, actual), expected, actual); } }