Java Examples for junit.framework.AssertionFailedError

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

Example 1
Project: android-15-master  File: InstrumentationTestRunner.java View source code
public void addFailure(Test test, AssertionFailedError t) {
    mTestResult.putString(REPORT_KEY_STACK, BaseTestRunner.getFilteredTrace(t));
    mTestResultCode = REPORT_VALUE_RESULT_FAILURE;
    // pretty printing
    mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT, String.format("\nFailure in %s:\n%s", ((TestCase) test).getName(), BaseTestRunner.getFilteredTrace(t)));
}
Example 2
Project: RoboBuggy-master  File: ForwardCompatibilityTest.java View source code
public void testNotifyResult() {
    JUnit4TestAdapter adapter = new JUnit4TestAdapter(ErrorTest.class);
    TestResult result = new TestResult();
    final StringBuffer log = new StringBuffer();
    result.addListener(new TestListener() {

        public void startTest(junit.framework.Test test) {
            log.append(" start ").append(test);
        }

        public void endTest(junit.framework.Test test) {
            log.append(" end ").append(test);
        }

        public void addFailure(junit.framework.Test test, AssertionFailedError t) {
            log.append(" failure ").append(test);
        }

        public void addError(junit.framework.Test test, Throwable e) {
            log.append(" error " + test);
        }
    });
    adapter.run(result);
    String testName = String.format("error(%s)", ErrorTest.class.getName());
    assertEquals(String.format(" start %s error %s end %s", testName, testName, testName), log.toString());
}
Example 3
Project: cdo-master  File: ResourceTest.java View source code
public void testDeleteResourceDifferentSessionFresh() throws Exception {
    CDOSession session = openSession();
    CDOTransaction transaction = session.openTransaction();
    CDOSession session2 = openSession();
    CDOView view = session2.openView();
    CDOResource resource = createResource(transaction, "/resource1");
    CDOID resourceID = resource.cdoID();
    CDOObject object = CDOUtil.getCDOObject(resource.getContents().get(0));
    CDOID objectID = object.cdoID();
    transaction.commit();
    assertEquals(true, view.hasResource(getResourcePath("/resource1")));
    assertEquals(resource.getURI(), view.getResource(getResourcePath("/resource1")).getURI());
    resource.delete(null);
    commitAndSync(transaction, view);
    transaction.close();
    clearCache(getRepository().getRevisionManager());
    assertEquals(false, view.hasResource(getResourcePath("/resource1")));
    try {
        view.getResourceNode("/resource1");
        fail("Exception expected");
    } catch (Exception expected) {
    }
    try {
        CDOResource resource1 = view.getResource(getResourcePath("/resource1"));
        assertNull(resource1);
        fail("Exception expected");
    // TODO Fails on automated build:
    // junit.framework.AssertionFailedError: Exception expected
    // at org.eclipse.emf.cdo.tests.ResourceTest.testDeleteResourceDifferentSessionFresh(ResourceTest.java:859)
    // at org.eclipse.net4j.tests.AbstractOMTest.runBare(AbstractOMTest.java:86)
    // at org.eclipse.net4j.tests.AbstractOMTest.run(AbstractOMTest.java:108)
    // at org.eclipse.emf.cdo.tests.config.impl.ConfigTestSuite$TestWrapper.runTest(ConfigTestSuite.java:126)
    // at org.eclipse.test.EclipseTestRunner.run(EclipseTestRunner.java:332)
    // at org.eclipse.test.EclipseTestRunner.run(EclipseTestRunner.java:202)
    // at org.eclipse.test.CoreTestApplication.runTests(CoreTestApplication.java:35)
    // at org.eclipse.test.CoreTestApplication.run(CoreTestApplication.java:31)
    // at org.eclipse.equinox.internal.app.EclipseAppContainer.callMethodWithException(EclipseAppContainer.java:574)
    // at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    // at org.eclipse.equinox.internal.app.MainApplicationLauncher.run(MainApplicationLauncher.java:32)
    // at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    // at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    // at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:368)
    // at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    // at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:559)
    // at org.eclipse.equinox.launcher.Main.basicRun(Main.java:514)
    // at org.eclipse.equinox.launcher.Main.run(Main.java:1311)
    // at org.eclipse.equinox.launcher.Main.main(Main.java:1287)
    // at org.eclipse.core.launcher.Main.main(Main.java:34)
    } catch (Exception expected) {
        expected.printStackTrace();
    }
    try {
        view.getObject(resourceID);
        fail("ObjectNotFoundException expected");
    } catch (ObjectNotFoundException expected) {
    }
    try {
        view.getObject(objectID);
        fail("ObjectNotFoundException expected");
    } catch (ObjectNotFoundException expected) {
    }
    session.close();
}
Example 4
Project: cdt-tests-runner-master  File: FormattedValueTests.java View source code
private void setFormatAndValidate(String formatId, ArrayList<ElementFormatSetting> setElementFormats, ArrayList<ElementFormatSetting> expectElementFormats, boolean expectContentCached, boolean expectFormattedValuesCached, boolean expectCacheMissError) {
    fViewerListener.reset();
    fViewerListener.addUpdates(TreePath.EMPTY, ((TestElementVMContext) fViewer.getInput()).getElement(), -1, ALL_UPDATES_COMPLETE | PROPERTY_UPDATES);
    fVMListener.reset();
    int vmUpdateFlags = PROPERTY_UPDATES;
    if (!expectContentCached) {
        vmUpdateFlags |= ALL_UPDATES_COMPLETE;
    }
    fVMListener.addUpdates(TreePath.EMPTY, fModel.getRootElement(), vmListenerLevel, vmUpdateFlags);
    fFormattedValuesListener.reset();
    if (expectFormattedValuesCached && !expectCacheMissError) {
        fFormattedValuesListener.setCachedFormats(new String[] { formatId });
    }
    if (fVMProvider instanceof IElementFormatProvider && setElementFormats != null) {
        IElementFormatProvider ep = ((IElementFormatProvider) fVMProvider);
        for (ElementFormatSetting es : setElementFormats) {
            ep.setActiveFormat(fViewer.getPresentationContext(), es.nodes.toArray(new IVMNode[es.nodes.size()]), fViewer.getInput(), es.elementPaths.toArray(new TreePath[es.elementPaths.size()]), es.formatId);
        }
    } else {
        // Set the new number format to the viewer.
        fViewer.getPresentationContext().setProperty(PROP_FORMATTED_VALUE_FORMAT_PREFERENCE, formatId);
    }
    while (!fViewerListener.isFinished(ALL_UPDATES_COMPLETE | PROPERTY_UPDATES) || !fVMListener.isFinished(CONTENT_UPDATES | PROPERTY_UPDATES)) if (!fDisplay.readAndDispatch())
        fDisplay.sleep();
    if (expectCacheMissError) {
        try {
            validateModel(expectElementFormats, formatId, "", formatId, "");
            throw new RuntimeException("Expected validateModel to fail");
        } catch (AssertionFailedError e) {
        }
    } else {
        validateModel(expectElementFormats, formatId, "", formatId, "");
    }
    if (expectCacheMissError) {
        String formatProperty = FormattedValueVMUtil.getPropertyForFormatId(formatId);
        Assert.assertTrue(fFormattedValuesListener.getFormattedValuesCompleted().isEmpty());
        Assert.assertFalse(fFormattedValuesListener.getPropertiesUpdates().isEmpty());
        for (IPropertiesUpdate update : fFormattedValuesListener.getPropertiesUpdates()) {
            PropertiesUpdateStatus status = (PropertiesUpdateStatus) update.getStatus();
            assertEquals(IDsfStatusConstants.INVALID_STATE, status.getCode());
            ElementFormatSetting elementFormat = null;
            if (expectElementFormats != null) {
                TreePath viewerPath = update.getElementPath();
                for (ElementFormatSetting es : expectElementFormats) {
                    if (es.elementPaths.indexOf(viewerPath) >= 0) {
                        elementFormat = es;
                        break;
                    }
                }
            }
            if (elementFormat != null) {
                assertEquals("Cache contains stale data. Refresh view.", status.getStatus(FormattedValueVMUtil.getPropertyForFormatId(elementFormat.formatId)).getMessage());
            } else {
                assertEquals("Cache contains stale data. Refresh view.", status.getStatus(formatProperty).getMessage());
            }
            assertEquals("Cache contains stale data. Refresh view.", status.getStatus(PROP_FORMATTED_VALUE_ACTIVE_FORMAT_VALUE).getMessage());
            assertEquals(1, status.getChildren().length);
        }
    } else {
        Assert.assertTrue(fFormattedValuesListener.isFinished());
    }
}
Example 5
Project: rabbitmq-java-client-master  File: ConfirmBase.java View source code
protected void waitForConfirms(final String testTitle) throws Exception {
    try {
        FutureTask<?> waiter = new FutureTask<Object>(new Runnable() {

            public void run() {
                try {
                    channel.waitForConfirmsOrDie();
                } catch (IOException e) {
                    throw (ShutdownSignalException) e.getCause();
                } catch (InterruptedException _e) {
                    fail(testTitle + ": interrupted");
                }
            }
        }, null);
        (Executors.newSingleThreadExecutor()).execute(waiter);
        waiter.get(10, TimeUnit.SECONDS);
    } catch (ExecutionException ee) {
        Throwable t = ee.getCause();
        if (t instanceof ShutdownSignalException)
            throw (ShutdownSignalException) t;
        if (t instanceof AssertionFailedError)
            throw (AssertionFailedError) t;
        throw (Exception) t;
    } catch (TimeoutException _e) {
        fail(testTitle + ": timeout");
    }
}
Example 6
Project: closure-stylesheets-master  File: RecordingSubstitutionMapTest.java View source code
public final void testReadAndWrite() throws IOException {
    for (OutputRenamingMapFormat format : OutputRenamingMapFormat.values()) {
        RecordingSubstitutionMap recording = new RecordingSubstitutionMap.Builder().withSubstitutionMap(createDelegate()).build();
        // Put some stuff into the map.
        // TIL: there are a lot of websites on the A-Z of fruits & vegetables.
        assertEquals("x-a", recording.get("apple"));
        assertEquals("x-b", recording.get("banana"));
        assertEquals("x-d", recording.get("durian"));
        assertEquals("x-f-g", recording.get("figgy-goop"));
        // Write it out.
        StringWriter out = new StringWriter();
        String formatted;
        try {
            format.writeRenamingMap(recording.getMappings(), out);
            formatted = out.toString();
        } finally {
            out.close();
        }
        // Reconstitute it.
        RecordingSubstitutionMap recordingFromString;
        StringReader in = new StringReader(formatted);
        try {
            recordingFromString = new RecordingSubstitutionMap.Builder().withSubstitutionMap(createDelegate()).withMappings(format.readRenamingMap(in)).build();
            assertEquals(-1, in.read());
        } catch (IOExceptionRuntimeException |  ex) {
            throw (AssertionFailedError) new AssertionFailedError("Problem with input formatted according to " + format + "\n```\n" + formatted + "\n```").initCause(ex);
        } finally {
            in.close();
        }
        // Vary the order to check that we get stable values from the
        // earlier uses, and unambiguous new values.
        assertEquals("x-b", recordingFromString.get("banana"));
        assertEquals("x-h", recordingFromString.get("honeydew"));
        assertEquals("x-a", recordingFromString.get("apple"));
        assertEquals("x-f-g", recordingFromString.get("figgy-goop"));
        assertEquals("x-d", recordingFromString.get("durian"));
        assertEquals("x-j", recordingFromString.get("jalapeno"));
    }
}
Example 7
Project: android_platform_libcore-master  File: DomTest.java View source code
public void testAdoptionImmediatelyAfterParsing() throws Exception {
    Document newDocument = builder.newDocument();
    try {
        assertSame(name, newDocument.adoptNode(name));
        assertSame(newDocument, name.getOwnerDocument());
        assertSame(newDocument, standard.getOwnerDocument());
        assertSame(newDocument, waffles.getOwnerDocument());
    } catch (Throwable e) {
        AssertionFailedError failure = new AssertionFailedError("This implementation fails to adopt nodes before the " + "document has been traversed");
        failure.initCause(e);
        throw failure;
    }
}
Example 8
Project: eclipse.jdt.ui-master  File: ImportOrganizeTest.java View source code
public void test1() throws Exception {
    File junitSrcArchive = JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC_381);
    assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists());
    JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", junitSrcArchive, JavaProjectHelper.JUNIT_SRC_ENCODING);
    ICompilationUnit cu = (ICompilationUnit) fJProject1.findElement(new Path("junit/runner/BaseTestRunner.java"));
    assertNotNull("BaseTestRunner.java", cu);
    IPackageFragmentRoot root = (IPackageFragmentRoot) cu.getParent().getParent();
    IPackageFragment pack = root.createPackageFragment("mytest", true, null);
    ICompilationUnit colidingCU = pack.getCompilationUnit("TestListener.java");
    colidingCU.createType("public abstract class TestListener {\n}\n", null, true, null);
    String[] order = new String[0];
    IChooseImportQuery query = createQuery("BaseTestRunner", new String[] { "junit.framework.TestListener" }, new int[] { 2 });
    OrganizeImportsOperation op = createOperation(cu, order, 99, false, true, true, query);
    op.run(null);
    assertImports(cu, new String[] { "java.io.BufferedReader", "java.io.File", "java.io.FileInputStream", "java.io.FileOutputStream", "java.io.IOException", "java.io.InputStream", "java.io.PrintWriter", "java.io.StringReader", "java.io.StringWriter", "java.lang.reflect.InvocationTargetException", "java.lang.reflect.Method", "java.lang.reflect.Modifier", "java.text.NumberFormat", "java.util.Properties", "junit.framework.AssertionFailedError", "junit.framework.Test", "junit.framework.TestListener", "junit.framework.TestSuite" });
}
Example 9
Project: android-sdk-sources-for-api-level-23-master  File: UiAutomatorInstrumentationTestRunner.java View source code
@Override
protected AndroidTestRunner getAndroidTestRunner() {
    AndroidTestRunner testRunner = super.getAndroidTestRunner();
    testRunner.addTestListener(new TestListener() {

        @Override
        public void startTest(Test test) {
            if (test instanceof UiAutomatorTestCase) {
                ((UiAutomatorTestCase) test).initialize(getArguments());
            }
        }

        @Override
        public void endTest(Test test) {
        }

        @Override
        public void addFailure(Test test, AssertionFailedError e) {
        }

        @Override
        public void addError(Test test, Throwable t) {
        }
    });
    return testRunner;
}
Example 10
Project: modeshape-master  File: SingleUseAbstractTest.java View source code
/**
     * Make sure that a workspace with the supplied name exists.
     * 
     * @param workspaceName the name of the workspace; may not be null
     */
protected void predefineWorkspace(RepositoryConfiguration configuration, String workspaceName) {
    assertThat(workspaceName, is(notNullValue()));
    // Edit the configuration ...
    Editor editor = configuration.edit();
    EditableDocument workspaces = editor.getOrCreateDocument("workspaces");
    EditableArray predefined = workspaces.getOrCreateArray("predefined");
    predefined.addStringIfAbsent(workspaceName);
    // And apply the changes ...
    Changes changes = editor.getChanges();
    if (changes.isEmpty())
        return;
    try {
        repository.apply(changes);
    } catch (Exception e) {
        e.printStackTrace();
        throw new AssertionFailedError("Unexpected error while predefining the \"" + workspaceName + "\" workspace:" + e.getMessage());
    }
}
Example 11
Project: google-web-toolkit-svnmirror-master  File: JUnitShell.java View source code
private void processTestResult(TestCase testCase, TestResult testResult, Strategy strategy) {
    Map<ClientStatus, JUnitResult> results = messageQueue.getResults(currentTestInfo);
    assert results != null;
    assert results.size() == messageQueue.getNumClients() : results.size() + " != " + messageQueue.getNumClients();
    for (Entry<ClientStatus, JUnitResult> entry : results.entrySet()) {
        ClientStatus client = entry.getKey();
        JUnitResult result = entry.getValue();
        assert (result != null);
        Throwable exception = result.getException();
        // Let the user know the browser in which the failure happened.
        if (exception != null) {
            String msg = "Remote test failed at " + client.getDesc();
            if (exception instanceof AssertionFailedError) {
                String oldMessage = exception.getMessage();
                if (oldMessage != null) {
                    msg += "\n" + exception.getMessage();
                }
                AssertionFailedError newException = new AssertionFailedError(msg);
                newException.setStackTrace(exception.getStackTrace());
                newException.initCause(exception.getCause());
                exception = newException;
            } else {
                exception = new RuntimeException(msg, exception);
            }
        }
        // A "successful" failure.
        if (exception instanceof AssertionFailedError) {
            testResult.addFailure(testCase, (AssertionFailedError) exception);
        } else if (exception != null) {
            // A real failure
            if (exception instanceof JUnitFatalLaunchException) {
                lastLaunchFailed = true;
            }
            testResult.addError(testCase, exception);
        }
        strategy.processResult(testCase, result);
    }
}
Example 12
Project: hibernate-core-ogm-master  File: BulkManipulationTest.java View source code
@Test
public void testUpdateSetNullUnionSubclass() {
    TestData data = new TestData();
    data.prepare();
    // These should reach out into *all* subclass tables...
    Session s = openSession();
    Transaction t = s.beginTransaction();
    int count = s.createQuery("update Vehicle set owner = 'Steve'").executeUpdate();
    assertEquals("incorrect restricted update count", 4, count);
    count = s.createQuery("update Vehicle set owner = null where owner = 'Steve'").executeUpdate();
    assertEquals("incorrect restricted update count", 4, count);
    try {
        count = s.createQuery("delete Vehicle where owner is null").executeUpdate();
        assertEquals("incorrect restricted delete count", 4, count);
    } catch (AssertionFailedError afe) {
        if (H2Dialect.class.isInstance(getDialect())) {
            count = s.createQuery("delete Vehicle").executeUpdate();
            assertEquals("incorrect count", 4, count);
        } else {
            throw afe;
        }
    }
    t.commit();
    s.close();
    data.cleanup();
}
Example 13
Project: JBossAS51-master  File: MBeanServerTEST.java View source code
/**
    * Tests removing a broadcaster
    */
public synchronized void testRemoveBroadcaster() throws Exception {
    MBeanServer server = MBeanServerFactory.newMBeanServer();
    class MyNotificationListener implements NotificationListener {

        long result = 0;

        public MyNotificationListener() {
        }

        public void handleNotification(Notification notification, Object handback) {
            result = notification.getSequenceNumber();
        }
    }
    // Register the broadcaster
    ObjectName broadcasterName = new ObjectName("test:type=broadcaster");
    Broadcaster broadcaster = new Broadcaster();
    server.registerMBean(broadcaster, broadcasterName);
    // Add the listener
    MyNotificationListener listener = new MyNotificationListener();
    server.addNotificationListener(broadcasterName, listener, null, null);
    // Test we get a notification
    broadcaster.doSomething();
    assertEquals(1, listener.result);
    // Remove the broadcaster
    server.unregisterMBean(broadcasterName);
    // This notification shouldn't work
    broadcaster.doSomething();
    try {
        assertEquals(1, listener.result);
    } catch (AssertionFailedError e) {
        fail("FAILS IN RI: Removing a notification broadcaster does not " + "remove the listeners registered against the object name.");
    }
}
Example 14
Project: eclipselink.runtime-master  File: EntityManagerJUnitTestSuite.java View source code
//Glassfish bug 702 - prevent primary key updates
public void testPrimaryKeyUpdate() {
    EntityManager em = createEntityManager();
    beginTransaction(em);
    Employee emp = new Employee();
    emp.setFirstName("Groucho");
    emp.setLastName("Marx");
    em.persist(emp);
    Integer id = emp.getId();
    commitTransaction(em);
    beginTransaction(em);
    emp = em.merge(emp);
    emp.setId(id + 1);
    try {
        commitTransaction(em);
    } catch (Exception exception) {
        if (isTransactionActive(em)) {
            rollbackTransaction(em);
        }
        Throwable persistenceException = exception;
        while (persistenceException != null && !(persistenceException instanceof ValidationException)) {
            persistenceException = persistenceException.getCause();
        }
        if (persistenceException instanceof ValidationException) {
            ValidationException ve = (ValidationException) persistenceException;
            if (ve.getErrorCode() == ValidationException.PRIMARY_KEY_UPDATE_DISALLOWED) {
                return;
            } else {
                AssertionFailedError failure = new AssertionFailedError("Wrong error code for ValidationException: " + ve.getErrorCode());
                failure.initCause(ve);
                throw failure;
            }
        } else {
            AssertionFailedError failure = new AssertionFailedError("ValiationException expected, thrown: " + exception);
            failure.initCause(exception);
            throw failure;
        }
    } finally {
        closeEntityManager(em);
    }
    fail("No exception thrown when primary key update attempted.");
}
Example 15
Project: newFunf-master  File: ContactProbeTest.java View source code
public void testProbe() {
    Bundle params = new Bundle();
    params.putLong(Parameter.Builtin.PERIOD.name, 0L);
    params.putBoolean(ContactProbe.FULL_PARAM.getName(), true);
    startProbe(params);
    Bundle data = getData(30);
    assertNotNull(data.get(BaseProbeKeys.TIMESTAMP));
    ArrayList<Parcelable> contactData = data.getParcelableArrayList(ContactProbe.CONTACT_DATA);
    assertNotNull(contactData);
    int count = 1;
    while (data != null) {
        try {
            data = getData(5);
            count++;
        } catch (AssertionFailedError e) {
            assertTrue(contactData.size() > 0);
            Log.i("ContactProbeTest", "Contact keys: " + Utils.join(Utils.getValues(data).keySet(), ", "));
            for (Parcelable dataRow : contactData) {
                Bundle b = (Bundle) dataRow;
                Log.i("ContactProbeTest", "Data keys: " + b.getString(Data.MIMETYPE) + ":" + String.valueOf(b.get(Data.DATA1)) + " - Others: " + Utils.join(Utils.getValues(b).keySet(), ", "));
            }
            data = null;
        }
    }
    Log.i("ContactProbeTest", "Count: " + String.valueOf(count));
}
Example 16
Project: sisu-guice-master  File: TypeConversionTest.java View source code
public void testStringIsConvertedOnlyOnce() {
    final TypeConverter converter = new TypeConverter() {

        boolean converted = false;

        @Override
        public Object convert(String value, TypeLiteral<?> toType) {
            if (converted) {
                throw new AssertionFailedError("converted multiple times!");
            }
            converted = true;
            return new Date();
        }
    };
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            convertToTypes(Matchers.only(TypeLiteral.get(Date.class)), converter);
            bindConstant().annotatedWith(NumericValue.class).to("unused");
        }
    });
    Date first = injector.getInstance(Key.get(Date.class, NumericValue.class));
    Date second = injector.getInstance(Key.get(Date.class, NumericValue.class));
    assertSame(first, second);
}
Example 17
Project: strongback-java-master  File: ExecutableTimerTest.java View source code
/**
     * Time for the given duration the execution using the supplied mode and execution period.
     *
     * @param mode the execution wait mode; may not be null
     * @param millisecondExecutionPeriod the execution period in milliseconds
     * @param sampleTimeInMilliseconds the sample time in milliseconds
     */
protected void runTimer(TimerMode mode, int millisecondExecutionPeriod, int sampleTimeInMilliseconds) {
    try {
        Strongback.configure().useExecutionTimerMode(mode).useExecutionPeriod(millisecondExecutionPeriod, TimeUnit.MILLISECONDS).initialize();
        assertThat(ExecutableTimer.measureTimingAndPrint(Strongback.executor(), mode.toString() + " for " + millisecondExecutionPeriod + " ms", sampleTimeInMilliseconds / millisecondExecutionPeriod).await(10, TimeUnit.SECONDS).isComplete());
    } catch (InterruptedException e) {
        Thread.interrupted();
        throw new AssertionFailedError();
    }
}
Example 18
Project: eclipse.jdt.core-master  File: ASTTest.java View source code
public void testNodeTypeConstants() throws Exception {
    int[] nodeTypes = { ASTNode.ANONYMOUS_CLASS_DECLARATION, ASTNode.ARRAY_ACCESS, ASTNode.ARRAY_CREATION, ASTNode.ARRAY_INITIALIZER, ASTNode.ARRAY_TYPE, ASTNode.ASSERT_STATEMENT, ASTNode.ASSIGNMENT, ASTNode.BLOCK, ASTNode.BOOLEAN_LITERAL, ASTNode.BREAK_STATEMENT, ASTNode.CAST_EXPRESSION, ASTNode.CATCH_CLAUSE, ASTNode.CHARACTER_LITERAL, ASTNode.CLASS_INSTANCE_CREATION, ASTNode.COMPILATION_UNIT, ASTNode.CONDITIONAL_EXPRESSION, ASTNode.CONSTRUCTOR_INVOCATION, ASTNode.CONTINUE_STATEMENT, ASTNode.DO_STATEMENT, ASTNode.EMPTY_STATEMENT, ASTNode.EXPRESSION_STATEMENT, ASTNode.FIELD_ACCESS, ASTNode.FIELD_DECLARATION, ASTNode.FOR_STATEMENT, ASTNode.IF_STATEMENT, ASTNode.IMPORT_DECLARATION, ASTNode.INFIX_EXPRESSION, ASTNode.INITIALIZER, ASTNode.JAVADOC, ASTNode.LABELED_STATEMENT, ASTNode.METHOD_DECLARATION, ASTNode.METHOD_INVOCATION, ASTNode.NULL_LITERAL, ASTNode.NUMBER_LITERAL, ASTNode.PACKAGE_DECLARATION, ASTNode.PARENTHESIZED_EXPRESSION, ASTNode.POSTFIX_EXPRESSION, ASTNode.PREFIX_EXPRESSION, ASTNode.PRIMITIVE_TYPE, ASTNode.QUALIFIED_NAME, ASTNode.RETURN_STATEMENT, ASTNode.SIMPLE_NAME, ASTNode.SIMPLE_TYPE, ASTNode.SINGLE_VARIABLE_DECLARATION, ASTNode.STRING_LITERAL, ASTNode.SUPER_CONSTRUCTOR_INVOCATION, ASTNode.SUPER_FIELD_ACCESS, ASTNode.SUPER_METHOD_INVOCATION, ASTNode.SWITCH_CASE, ASTNode.SWITCH_STATEMENT, ASTNode.SYNCHRONIZED_STATEMENT, ASTNode.THIS_EXPRESSION, ASTNode.THROW_STATEMENT, ASTNode.TRY_STATEMENT, ASTNode.TYPE_DECLARATION, ASTNode.TYPE_DECLARATION_STATEMENT, ASTNode.TYPE_LITERAL, ASTNode.VARIABLE_DECLARATION_EXPRESSION, ASTNode.VARIABLE_DECLARATION_FRAGMENT, ASTNode.VARIABLE_DECLARATION_STATEMENT, ASTNode.WHILE_STATEMENT, ASTNode.INSTANCEOF_EXPRESSION, ASTNode.LINE_COMMENT, ASTNode.BLOCK_COMMENT, ASTNode.TAG_ELEMENT, ASTNode.TEXT_ELEMENT, ASTNode.MEMBER_REF, ASTNode.METHOD_REF, ASTNode.METHOD_REF_PARAMETER, ASTNode.ENHANCED_FOR_STATEMENT, ASTNode.ENUM_DECLARATION, ASTNode.ENUM_CONSTANT_DECLARATION, ASTNode.TYPE_PARAMETER, ASTNode.PARAMETERIZED_TYPE, ASTNode.QUALIFIED_TYPE, ASTNode.WILDCARD_TYPE, ASTNode.NORMAL_ANNOTATION, ASTNode.MARKER_ANNOTATION, ASTNode.SINGLE_MEMBER_ANNOTATION, ASTNode.MEMBER_VALUE_PAIR, ASTNode.ANNOTATION_TYPE_DECLARATION, ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION, ASTNode.MODIFIER, ASTNode.UNION_TYPE, ASTNode.DIMENSION, ASTNode.LAMBDA_EXPRESSION, ASTNode.INTERSECTION_TYPE, ASTNode.NAME_QUALIFIED_TYPE, ASTNode.CREATION_REFERENCE, ASTNode.EXPRESSION_METHOD_REFERENCE, ASTNode.SUPER_METHOD_REFERENCE, ASTNode.TYPE_METHOD_REFERENCE };
    for (int i = 0; i < nodeTypes.length; i++) {
        assertSame(i + 1, nodeTypes[i]);
    }
    for (int i = 0; i < nodeTypes.length; i++) {
        int nodeType = nodeTypes[i];
        ASTNode node;
        try {
            node = this.ast.createInstance(nodeType);
        } catch (IllegalArgumentException e) {
            if (this.API_LEVEL < AST.JLS8 && e.getCause() instanceof UnsupportedOperationException) {
                continue;
            } else {
                throw new AssertionFailedError("missing node type: " + nodeType);
            }
        }
        assertEquals(nodeType, node.getNodeType());
    }
    Field[] fields = ASTNode.class.getDeclaredFields();
    HashSet declaredNodeTypes = new HashSet();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        if (field.getType() != int.class)
            continue;
        if (field.getModifiers() != (java.lang.reflect.Modifier.PUBLIC | java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.FINAL))
            continue;
        String name = field.getName();
        if ("MALFORMED".equals(name) || "ORIGINAL".equals(name) || "PROTECT".equals(name) || "RECOVERED".equals(name))
            continue;
        declaredNodeTypes.add(Integer.valueOf(field.getInt(null)));
    }
    for (int i = 0; i < nodeTypes.length; i++) {
        int nodeType = nodeTypes[i];
        assertTrue("node type " + nodeType + " from test is missing in ASTNode", declaredNodeTypes.remove(Integer.valueOf(nodeType)));
        nodeTypes[i] = -1;
    }
    for (int i = 0; i < nodeTypes.length; i++) {
        int nodeType = nodeTypes[i];
        assertEquals("node type " + nodeType + " missing in ASTNode", -1, nodeType);
    }
    assertEquals("node types missing in test", Collections.EMPTY_SET, declaredNodeTypes);
}
Example 19
Project: gatein-portal-master  File: TestDataStorage.java View source code
private void testGetAllSiteNames(String siteType, final String methodName) throws Exception {
    final List<String> names = (List<String>) storage_.getClass().getMethod(methodName).invoke(storage_);
    // Create new portal
    storage_.create(new PortalConfig(siteType, "testGetAllSiteNames"));
    // Test during tx we see the good names
    List<String> transientNames = (List<String>) storage_.getClass().getMethod(methodName).invoke(storage_);
    assertTrue("Was expecting " + transientNames + " to contain " + names, transientNames.containsAll(names));
    transientNames.removeAll(names);
    assertEquals(Collections.singletonList("testGetAllSiteNames"), transientNames);
    // Test we have not seen anything yet outside of tx
    final CountDownLatch addSync = new CountDownLatch(1);
    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
    new Thread() {

        @Override
        public void run() {
            begin();
            try {
                List<String> isolatedNames = (List<String>) storage_.getClass().getMethod(methodName).invoke(storage_);
                assertEquals(new HashSet<String>(names), new HashSet<String>(isolatedNames));
            } catch (Throwable t) {
                error.set(t);
            } finally {
                addSync.countDown();
                end();
            }
        }
    }.start();
    //
    addSync.await();
    if (error.get() != null) {
        AssertionFailedError afe = new AssertionFailedError();
        afe.initCause(error.get());
        throw afe;
    }
    // Now commit tx
    end(true);
    // We test we observe the change
    begin();
    List<String> afterNames = (List<String>) storage_.getClass().getMethod(methodName).invoke(storage_);
    assertTrue(afterNames.containsAll(names));
    afterNames.removeAll(names);
    assertEquals(Collections.singletonList("testGetAllSiteNames"), afterNames);
    // Then we remove the newly created portal
    storage_.remove(new PortalConfig(siteType, "testGetAllSiteNames"));
    // Test we are syeing the transient change
    transientNames.clear();
    transientNames = (List<String>) storage_.getClass().getMethod(methodName).invoke(storage_);
    assertEquals(names, transientNames);
    // Test we have not seen anything yet outside of tx
    error.set(null);
    final CountDownLatch removeSync = new CountDownLatch(1);
    new Thread() {

        public void run() {
            begin();
            try {
                List<String> isolatedNames = (List<String>) storage_.getClass().getMethod(methodName).invoke(storage_);
                assertTrue("Was expecting " + isolatedNames + " to contain " + names, isolatedNames.containsAll(names));
                isolatedNames.removeAll(names);
                assertEquals(Collections.singletonList("testGetAllSiteNames"), isolatedNames);
            } catch (Throwable t) {
                error.set(t);
            } finally {
                removeSync.countDown();
                end();
            }
        }
    }.start();
    //
    removeSync.await();
    if (error.get() != null) {
        AssertionFailedError afe = new AssertionFailedError();
        afe.initCause(error.get());
        throw afe;
    }
    //
    end(true);
    // Now test it is still removed
    begin();
    afterNames = (List<String>) storage_.getClass().getMethod(methodName).invoke(storage_);
    assertEquals(new HashSet<String>(names), new HashSet<String>(afterNames));
}
Example 20
Project: jeppetto-master  File: DatabaseAssert.java View source code
public static void assertDatabaseContentsEquals(Database database, InputStream inputStream, Map<String, String[]> ignoreMap) {
    Map<ITableFilter, IColumnFilter> filterMap = createFilterMap(ignoreMap);
    try {
        IDataSet databaseDataSet = database.getIDatabaseConnection().createDataSet();
        IDataSet actualDataSet = removeIgnoredColumns(databaseDataSet, filterMap);
        IDataSet xmlDataSet = new XmlDataSet(inputStream);
        IDataSet expectedDataSet = removeIgnoredColumns(xmlDataSet, filterMap);
        String[] expectedTableNames = expectedDataSet.getTableNames();
        for (String expectedTableName : expectedTableNames) {
            Assertion.assertEquals(new SortedTable(expectedDataSet.getTable(expectedTableName)), new SortedTable(actualDataSet.getTable(expectedTableName), expectedDataSet.getTable(expectedTableName).getTableMetaData()));
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } catch (DataSetException e) {
        throw new RuntimeException(e);
    } catch (DatabaseUnitException e) {
        throw new AssertionFailedError(e.getMessage());
    }
}
Example 21
Project: android_packages_apps-master  File: JNIBindingsTest.java View source code
public void printAssertionFailed(AssertionFailedError e) {
    Log.e(LOGTAG, "");
    Log.e(LOGTAG, "*** ASSERTION FAILED: " + e.getMessage());
    Log.e(LOGTAG, "*** Stack trace:");
    StackTraceElement[] trace = e.getStackTrace();
    for (StackTraceElement elem : trace) {
        Log.e(LOGTAG, "***\t" + elem.toString());
    }
    Log.e(LOGTAG, "");
}
Example 22
Project: android-libcore64-master  File: ECDHKeyAgreementTest.java View source code
private void invokeCallingMethodForEachKeyAgreementProvider() throws Exception {
    StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
    String callingMethodName = null;
    for (int i = 0; i < stackTrace.length; i++) {
        if ("invokeCallingMethodForEachKeyAgreementProvider".equals(stackTrace[i].getMethodName())) {
            callingMethodName = stackTrace[i + 1].getMethodName();
        }
    }
    if (callingMethodName == null) {
        throw new RuntimeException("Failed to deduce calling method name from stack trace");
    }
    String invokedMethodName = callingMethodName;
    Method method;
    try {
        method = getClass().getDeclaredMethod(invokedMethodName, Provider.class);
    } catch (NoSuchMethodError e) {
        throw new AssertionFailedError("Failed to find per-Provider test method " + getClass().getSimpleName() + "." + invokedMethodName + "(Provider)");
    }
    for (Provider provider : getKeyAgreementProviders()) {
        try {
            method.invoke(this, provider);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(getClass().getSimpleName() + "." + invokedMethodName + "(provider: " + provider.getName() + ") failed", e.getCause());
        }
    }
}
Example 23
Project: jena-master  File: SimpleTestRunner.java View source code
@Override
public void addFailure(Test test, AssertionFailedError arg1) {
    System.out.println("** Failure:  " + test);
    if (arg1 != null) {
        if (arg1.getMessage() != null)
            System.out.println("  " + arg1.getMessage());
        StackTraceElement st = arg1.getStackTrace()[0];
        System.out.println(st);
    }
}
Example 24
Project: guava-master  File: JSR166TestCase.java View source code
/**
     * Extra checks that get done for all test cases.
     *
     * Triggers test case failure if any thread assertions have failed,
     * by rethrowing, in the test harness thread, any exception recorded
     * earlier by threadRecordFailure.
     *
     * Triggers test case failure if interrupt status is set in the main thread.
     */
public void tearDown() throws Exception {
    Throwable t = threadFailure.getAndSet(null);
    if (t != null) {
        if (t instanceof Error)
            throw (Error) t;
        else if (t instanceof RuntimeException)
            throw (RuntimeException) t;
        else if (t instanceof Exception)
            throw (Exception) t;
        else {
            AssertionFailedError afe = new AssertionFailedError(t.toString());
            afe.initCause(t);
            throw afe;
        }
    }
    if (Thread.interrupted())
        throw new AssertionFailedError("interrupt status set in main thread");
}
Example 25
Project: windowtester-master  File: Robot.java View source code
public static void syncExec(Display dsply, Object obj, Runnable action) {
    try {
        dsply.syncExec(action);
    //Logger.trace("Didn't catch a NullPointerException");
    } catch (NullPointerException npe) {
        npe.printStackTrace();
    }/*
		 * The following hoping to get cleaner test failure handling. 
		 */
     catch (SWTException swtEx) {
        if (swtEx.throwable instanceof AssertionFailedError) {
            throw (AssertionFailedError) swtEx.throwable;
        } else if (swtEx.getCause() instanceof AssertionFailedError) {
            throw (AssertionFailedError) swtEx.getCause();
        } else {
            throw swtEx;
        }
    }
//Synchronizer.getSynchronizer().syncExec(dsply,obj,action);
//Synchronizer.getSynchronizer().syncExec(dsply,action);
}
Example 26
Project: dltk.ruby-master  File: TypeInferenceSuite.java View source code
@Override
public void check(ModuleDeclaration rootNode, ISourceModule cu, ITypeInferencer inferencer) throws Exception {
    final ASTNode[] result = new ASTNode[1];
    ASTVisitor visitor = new OffsetTargetedASTVisitor(namePos) {

        @Override
        protected boolean visitGeneralInteresting(ASTNode s) {
            if (s != null && result[0] == null)
                if (s.sourceStart() == namePos) {
                    result[0] = s;
                }
            return true;
        }
    };
    rootNode.traverse(visitor);
    if (result[0] == null)
        System.out.println("ExpressionTypeAssertion.check()");
    Assert.isLegal(result[0] != null);
    ExpressionTypeGoal goal = new ExpressionTypeGoal(new BasicContext(cu, rootNode), result[0]);
    IEvaluatedType type = inferencer.evaluateType(goal, -1);
    if (!correctClassRef.equals("recursion")) {
        if (type == null)
            throw new AssertionFailedError("null type fetched, but " + correctClassRef + " expected");
        assertNotNull(type);
        if (type instanceof SimpleType) {
            IEvaluatedType intrinsicType = getIntrinsicType(correctClassRef);
            assertEquals(intrinsicType, type);
        } else if (type instanceof RubyClassType) {
            RubyClassType rubyType = (RubyClassType) type;
            assertEquals(correctClassRef, rubyType.getModelKey());
        } else if (type instanceof AmbiguousType) {
            AmbiguousType ambiType = (AmbiguousType) type;
            Set<String> modelKeySet = new HashSet<>();
            IEvaluatedType[] possibleTypes = ambiType.getPossibleTypes();
            for (int cnt = 0, max = possibleTypes.length; cnt < max; cnt++) {
                if (possibleTypes[cnt] instanceof RubyClassType) {
                    modelKeySet.add(((RubyClassType) possibleTypes[cnt]).getModelKey());
                }
            }
            assertTrue(modelKeySet.contains(correctClassRef));
        } else {
            fail("Unrecognized IEvaluatedType was inferred: " + type.getClass().getName());
        }
    }
}
Example 27
Project: tcf-master  File: CoreTestCase.java View source code
/* (non-Javadoc)
		 * @see junit.framework.TestListener#addFailure(junit.framework.Test, junit.framework.AssertionFailedError)
		 */
@Override
public synchronized void addFailure(Test test, AssertionFailedError failure) {
    if (test != null && failure != null) {
        // Log the failure to the error log.
        IStatus status = new Status(IStatus.ERROR, UIPlugin.getUniqueIdentifier(), 1, //$NON-NLS-1$ //$NON-NLS-2$
        "Test case '" + test + "' failed. Failure: " + failure.getLocalizedMessage(), failure);
        UIPlugin.getDefault().getLog().log(status);
    }
}
Example 28
Project: guava-experimental-master  File: FuturesTest.java View source code
/**
   * Very rough equivalent of a timed get, produced by calling the no-arg get
   * method in another thread and waiting a short time for it.
   *
   * <p>We need this to test the behavior of no-arg get methods without hanging
   * the main test thread forever in the case of failure.
   */
private static <V> V pseudoTimedGet(final Future<V> input, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
    ExecutorService executor = newSingleThreadExecutor();
    Future<V> waiter = executor.submit(new Callable<V>() {

        @Override
        public V call() throws Exception {
            return input.get();
        }
    });
    try {
        return waiter.get(timeout, unit);
    } catch (ExecutionException e) {
        propagateIfInstanceOf(e.getCause(), ExecutionException.class);
        propagateIfInstanceOf(e.getCause(), CancellationException.class);
        AssertionFailedError error = new AssertionFailedError("Unexpected exception");
        error.initCause(e);
        throw error;
    } finally {
        executor.shutdownNow();
        assertTrue(executor.awaitTermination(10, SECONDS));
    }
}
Example 29
Project: geotools-old-master  File: ArcSDEFeatureStoreTest.java View source code
@Test
public void testSetFeaturesTransaction() throws Exception {
    testData.insertTestData();
    final SimpleFeatureCollection featuresToSet = testData.createTestFeatures(Point.class, 5);
    final DataStore ds = testData.getDataStore();
    final String typeName = testData.getTempTableName();
    final Transaction transaction = new DefaultTransaction("testSetFeaturesTransaction handle");
    final SimpleFeatureStore store;
    store = (SimpleFeatureStore) ds.getFeatureSource(typeName);
    store.setTransaction(transaction);
    final int initialCount = store.getCount(Query.ALL);
    assertTrue(initialCount > 0);
    assertTrue(initialCount != 5);
    try {
        store.setFeatures(DataUtilities.reader(featuresToSet));
        final int countInsideTransaction = store.getCount(Query.ALL);
        assertEquals(5, countInsideTransaction);
        final SimpleFeatureSource sourceNoTransaction;
        sourceNoTransaction = ds.getFeatureSource(typeName);
        int countNoTransaction = sourceNoTransaction.getCount(Query.ALL);
        if (databaseIsMsSqlServer) {
            // SQL Server always is at READ UNCOMMITTED isolation level...
            assertEquals(countInsideTransaction, countNoTransaction);
        } else {
            assertEquals(initialCount, countNoTransaction);
        }
        // now commit
        transaction.commit();
        countNoTransaction = sourceNoTransaction.getCount(Query.ALL);
        assertEquals(5, countNoTransaction);
    } catch (Exception e) {
        transaction.rollback();
        throw e;
    } catch (AssertionFailedError e) {
        transaction.rollback();
        throw e;
    } finally {
        transaction.close();
    }
}
Example 30
Project: sonar-java-master  File: TestActionRedirect.java View source code
/**
     * 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 + "]");
    }
}
Example 31
Project: MobileSensing-master  File: TestEncryption.java View source code
/**
   * Method to binary compare two files ( test method is copied from the
   * junit-addon project, to avoid adding a library. Refer to:
   * http://junit-addons.sourceforge.net/)
   * 
   * @param message
   *          the message
   * @param expected
   *          reference file
   * @param actual
   *          file to test
   * @throws AssertionFailedError
   */
public static final void assertBinaryEquals(String message, File expected, File actual) throws AssertionFailedError {
    FileInputStream isExpected = null;
    FileInputStream isActual = null;
    try {
        try {
            isExpected = new FileInputStream(expected);
            isActual = new FileInputStream(actual);
            assertNotNull(message, expected);
            assertNotNull(message, actual);
            byte[] expBuff = new byte[8192];
            byte[] actBuff = new byte[8192];
            long pos = 0;
            while (true) {
                int expLength = isExpected.read(expBuff, 0, 8192);
                int actLength = isActual.read(actBuff, 0, 8192);
                if (expLength < actLength) {
                    fail("actual file is longer");
                }
                if (expLength > actLength) {
                    fail("actual file is shorter");
                }
                if (expLength == 0) {
                    return;
                }
                for (int i = 0; i < expBuff.length; ++i) {
                    if (expBuff[i] != actBuff[i]) {
                        String formatted = "";
                        if (message != null) {
                            formatted = message + " ";
                        }
                        fail(formatted + "files differ at byte " + (pos + i + 1));
                    }
                }
                pos += expBuff.length;
                return;
            }
        } finally {
            isExpected.close();
            isActual.close();
        }
    } catch (IOException e) {
        throw new AssertionFailedError(e.getMessage());
    }
}
Example 32
Project: fdroidclient-master  File: Assert.java View source code
public static <T extends Comparable> void assertContainsOnly(List<T> actualList, List<T> expectedContains) {
    if (actualList.size() != expectedContains.size()) {
        String message = "List sizes don't match.\n" + "Expected: " + listToString(expectedContains) + "\n" + "Actual:   " + listToString(actualList);
        throw new AssertionFailedError(message);
    }
    for (T required : expectedContains) {
        boolean containsRequired = false;
        for (T itemInList : actualList) {
            if (required.equals(itemInList)) {
                containsRequired = true;
                break;
            }
        }
        if (!containsRequired) {
            String message = "List doesn't contain \"" + required + "\".\n" + "Expected: " + listToString(expectedContains) + "\n" + "Actual:   " + listToString(actualList);
            throw new AssertionFailedError(message);
        }
    }
}
Example 33
Project: Katari-master  File: FreemarkerTestEngineTest.java View source code
// Tests that runAndValidate throws an exception if a valid regexp is not
// found.
public void testRunAndValidate_validRegexpsFail() throws Exception {
    List<String> valid = new ArrayList<String>();
    valid.add(".*<title>NON EXISTENT TITLE</title>.*");
    FreemarkerTestEngine engine = new FreemarkerTestEngine("/com/globant/katari/tools", Locale.ENGLISH, buildModel());
    boolean exceptionThrown = false;
    try {
        engine.runAndValidate("freemarkerTestEngineTest.ftl", valid, Collections.<String>emptyList());
    // Cannot use fail() here because it throws AssertionFailedError.
    } catch (AssertionFailedError e) {
        exceptionThrown = true;
    }
    assertTrue(exceptionThrown);
}
Example 34
Project: spring-framework-2.5.x-master  File: AbstractAnnotationAwareTransactionalTests.java View source code
private void runTest(TestExecutionCallback tec, Method testMethod) throws Throwable {
    ExpectedException expectedExceptionAnnotation = testMethod.getAnnotation(ExpectedException.class);
    boolean exceptionIsExpected = (expectedExceptionAnnotation != null && expectedExceptionAnnotation.value() != null);
    Class<? extends Throwable> expectedException = (exceptionIsExpected ? expectedExceptionAnnotation.value() : null);
    Repeat repeat = testMethod.getAnnotation(Repeat.class);
    int runs = ((repeat != null) && (repeat.value() > 1)) ? repeat.value() : 1;
    for (int i = 0; i < runs; i++) {
        try {
            if (runs > 1 && this.logger != null && this.logger.isInfoEnabled()) {
                this.logger.info("Repetition " + (i + 1) + " of test " + testMethod.getName());
            }
            tec.run();
            if (exceptionIsExpected) {
                fail("Expected exception: " + expectedException.getName());
            }
        } catch (Throwable t) {
            if (!exceptionIsExpected) {
                throw t;
            }
            if (!expectedException.isAssignableFrom(t.getClass())) {
                AssertionFailedError assertionError = new AssertionFailedError("Unexpected exception, expected<" + expectedException.getName() + "> but was<" + t.getClass().getName() + ">");
                assertionError.initCause(t);
                throw assertionError;
            }
        }
    }
}
Example 35
Project: WaveInCloud-master  File: DocOpValidatorTest.java View source code
void doTest(TestData t) throws OperationException {
    DocOpBuffer d = new DocOpBuffer();
    DocOpBuffer m = new DocOpBuffer();
    boolean expected = t.build(d, m);
    BootstrapDocument doc = new BootstrapDocument();
    // initialize document
    doc.consume(d.finishUnchecked());
    // check whether m would apply
    ViolationCollector v = new ViolationCollector();
    ValidationResult result = DocOpValidator.validate(v, t.getSchemaConstraints(), doc, m.finishUnchecked());
    try {
        assertEquals(expected, v.isValid());
        assertEquals(result, v.getValidationResult());
    } catch (AssertionFailedError e) {
        System.err.println("test data:");
        System.err.println(DocOpUtil.toConciseString(d.finish()));
        System.err.println(DocOpUtil.toConciseString(m.finish()));
        System.err.println("violations:");
        v.printDescriptions(System.err);
        throw e;
    }
}
Example 36
Project: property-db-master  File: UiAutomatorTestRunner.java View source code
@Override
public void addFailure(Test test, AssertionFailedError t) {
    mTestResult.putString(REPORT_KEY_STACK, BaseTestRunner.getFilteredTrace(t));
    mTestResultCode = REPORT_VALUE_RESULT_FAILURE;
    // pretty printing
    mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT, String.format("\nFailure in %s:\n%s", ((TestCase) test).getName(), BaseTestRunner.getFilteredTrace(t)));
}
Example 37
Project: parkandrideAPI-master  File: RequestLogITest.java View source code
private void concurrentlyGenerateLogs(int numberOfRequests, int numberOfUpdates) {
    withDate(DateTime.now().withTime(12, 2, 0, 0), () -> {
        final Stream<CompletableFuture<Integer>> statusCodes = range(0, numberOfRequests).parallel().mapToObj( i -> {
            final Response response = given().header(SOURCE_HEADER, WEB_UI_SOURCE).when().get(UrlSchema.CAPACITY_TYPES).thenReturn();
            return CompletableFuture.completedFuture(response.statusCode());
        });
        final Stream<CompletableFuture<Integer>> updates = range(0, numberOfUpdates).parallel().mapToObj( i -> {
            batchingRequestLogService.updateRequestLogs();
            return CompletableFuture.completedFuture(0);
        });
        try {
            CompletableFuture.allOf(Stream.concat(statusCodes, updates).toArray( i -> new CompletableFuture[i])).get();
        } catch (InterruptedExceptionExecutionException |  e) {
            e.printStackTrace();
            throw new AssertionFailedError(e.getMessage());
        }
    });
}
Example 38
Project: krypton-master  File: SeleneseTestCase.java View source code
/**
	 * Like JUn it's Assert.assertEquals, but knows how to compare string arrays
	 */
public static void assertEquals(Object s1, Object s2) {
    if (s1 instanceof String && s2 instanceof String) {
        assertEquals((String) s1, (String) s2);
    } else if (s1 instanceof String && s2 instanceof String[]) {
        assertEquals((String) s1, (String[]) s2);
    } else if (s1 instanceof String && s2 instanceof Number) {
        assertEquals((String) s1, ((Number) s2).toString());
    } else {
        if (s1 instanceof String[] && s2 instanceof String[]) {
            String[] sa1 = (String[]) s1;
            String[] sa2 = (String[]) s2;
            if (sa1.length != sa2.length) {
                throw new AssertionFailedError("Expected " + sa1 + " but saw " + sa2);
            }
            for (int j = 0; j < sa1.length; j++) {
                Assert.assertEquals(sa1[j], sa2[j]);
            }
        }
    }
}
Example 39
Project: appengine-java-vm-runtime-master  File: SessionManagerTest.java View source code
private void testSerialize(String key, Object value) {
    AppEngineSession session = createSession();
    session.setAttribute(key, value);
    session.save();
    HttpSession httpSession = retrieveSession(session);
    assertNotNull(httpSession);
    Object result = httpSession.getAttribute(key);
    if (!value.getClass().isArray()) {
        assertEquals(value, result);
    } else {
        if (value instanceof Object[]) {
            Object[] valueAsArray = (Object[]) value;
            Object[] resultAsArray = (Object[]) result;
            if (!Arrays.deepEquals(valueAsArray, resultAsArray)) {
                throw new AssertionFailedError("Expected: " + Arrays.deepToString(valueAsArray) + " Received: " + Arrays.deepToString(resultAsArray));
            }
        } else if (value instanceof byte[]) {
            assertArrayEquals((byte[]) value, (byte[]) result);
        } else {
            throw new RuntimeException("Unhandled array type, " + value.getClass());
        }
    }
}
Example 40
Project: hadoop-20-master  File: TestBookKeeperEditLogInputStream.java View source code
private void testReadBufferGreaterThanLedgerSizeInner(int numEdits) throws Exception {
    LedgerHandle ledgerOut = createLedger();
    long ledgerId = ledgerOut.getId();
    BookKeeperEditLogInputStream bkEditsIn = new BookKeeperEditLogInputStream(ledgerProvider, ledgerId, 0, 1, -1, true);
    EditLogFileOutputStream fileEditsOut = new EditLogFileOutputStream(tempEditsFile, null);
    bkEditsIn.init();
    // Set the edit log buffer flush size smaller than the size of
    // of the buffer in BufferedInputStream in BookKeeperJournalInputStream
    FSEditLog.sizeFlushBuffer = bkEditsIn.bin.available() / 3;
    LOG.info("Set flush buffer size to " + FSEditLog.sizeFlushBuffer);
    BookKeeperEditLogOutputStream bkEditsOut = new BookKeeperEditLogOutputStream(ledgerOut);
    FSEditLogTestUtil.createAndPopulateStreams(1, numEdits, bkEditsOut, fileEditsOut);
    // Re-try refreshing up to ten times until we are able to refresh
    // successfully to be beginning of the ledger and read the edit log
    // layout version
    int maxTries = 10;
    for (int i = 0; i < maxTries; i++) {
        try {
            bkEditsIn.refresh(0, -1);
            assertEquals("refresh succeeded", bkEditsIn.logVersion, FSConstants.LAYOUT_VERSION);
        } catch (AssertionFailedError e) {
            if (i == maxTries) {
                throw e;
            }
        }
    }
    EditLogFileInputStream fileEditsIn = new EditLogFileInputStream(tempEditsFile);
    for (int i = 0; i <= numEdits; i++) {
        FSEditLogOp opFromBk = bkEditsIn.readOp();
        FSEditLogOp opFromFile = fileEditsIn.readOp();
        if (LOG.isDebugEnabled()) {
            LOG.debug("txId = " + i + ", " + "opFromBk = " + opFromBk + ", opFromFile = " + opFromFile);
        }
        assertEquals("Operation read from file and BookKeeper must be same after refresh", opFromBk, opFromFile);
    }
    assertNull("BookKeeper edit log must end at txid 1000", bkEditsIn.readOp());
}
Example 41
Project: seasar2-master  File: S2TestCase.java View source code
/**
     * 等しいことを表明します。
     * 
     * @param message
     *            メッセージ
     * @param expected
     *            期待値
     * @param actual
     *            実際の値
     */
public void assertEquals(String message, DataTable expected, DataTable actual) {
    message = message == null ? "" : message;
    message = message + ":TableName=" + expected.getTableName();
    assertEquals(message + ":RowSize", expected.getRowSize(), actual.getRowSize());
    for (int i = 0; i < expected.getRowSize(); ++i) {
        DataRow expectedRow = expected.getRow(i);
        DataRow actualRow = actual.getRow(i);
        List errorMessages = new ArrayList();
        for (int j = 0; j < expected.getColumnSize(); ++j) {
            try {
                String columnName = expected.getColumnName(j);
                Object expectedValue = expectedRow.getValue(columnName);
                ColumnType ct = ColumnTypes.getColumnType(expectedValue);
                Object actualValue = actualRow.getValue(columnName);
                if (!ct.equals(expectedValue, actualValue)) {
                    assertEquals(message + ":Row=" + i + ":columnName=" + columnName, expectedValue, actualValue);
                }
            } catch (AssertionFailedError e) {
                errorMessages.add(e.getMessage());
            }
        }
        if (!errorMessages.isEmpty()) {
            fail(message + errorMessages);
        }
    }
}
Example 42
Project: flink-master  File: MesosFlinkResourceManagerTest.java View source code
@Override
protected void run() {
    try {
        initialize();
        register(Collections.<ResourceID>emptyList());
        // set the target pool size
        when(workerStore.newTaskID()).thenReturn(task1).thenThrow(new AssertionFailedError());
        resourceManager.tell(new SetWorkerPoolSize(1), jobManager);
        // verify that a new worker was persisted, the internal state was updated, the task router was notified,
        // and the launch coordinator was asked to launch a task
        MesosWorkerStore.Worker expected = MesosWorkerStore.Worker.newWorker(task1);
        verify(workerStore).putWorker(expected);
        assertThat(resourceManagerInstance.workersInNew, hasEntry(extractResourceID(task1), expected));
        resourceManagerInstance.taskRouter.expectMsgClass(TaskMonitor.TaskGoalStateUpdated.class);
        resourceManagerInstance.launchCoordinator.expectMsgClass(LaunchCoordinator.Launch.class);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
Example 43
Project: oliot-fc-master  File: ECElementsUtils.java View source code
public static void assertEquals(ECSpec expected, ECSpec actual) {
    if (expected == null || actual == null) {
        if (expected == null && actual == null) {
            return;
        } else {
            throw new AssertionFailedError();
        }
    }
    assertEquals(expected.getAny(), actual.getAny());
    assertEquals(expected.getBoundarySpec(), actual.getBoundarySpec());
    assertEquals(expected.getCreationDate(), actual.getCreationDate());
    assertEquals(expected.getExtension(), actual.getExtension());
    assertEquals(expected.getLogicalReaders(), actual.getLogicalReaders());
    assertEquals(expected.getReportSpecs(), actual.getReportSpecs());
    assertEquals(expected.getSchemaVersion(), actual.getSchemaVersion());
}
Example 44
Project: openjdk-master  File: ForkJoinPoolTest.java View source code
/**
     * After invoking a single task, isQuiescent eventually becomes
     * true, at which time queues are empty, threads are not active,
     * the task has completed successfully, and construction
     * parameters continue to hold
     */
public void testIsQuiescent() throws Exception {
    ForkJoinPool p = new ForkJoinPool(2);
    try (PoolCleaner cleaner = cleaner(p)) {
        assertTrue(p.isQuiescent());
        long startTime = System.nanoTime();
        FibTask f = new FibTask(20);
        p.invoke(f);
        assertSame(ForkJoinPool.defaultForkJoinWorkerThreadFactory, p.getFactory());
        while (!p.isQuiescent()) {
            if (millisElapsedSince(startTime) > LONG_DELAY_MS)
                throw new AssertionFailedError("timed out");
            assertFalse(p.getAsyncMode());
            assertFalse(p.isShutdown());
            assertFalse(p.isTerminating());
            assertFalse(p.isTerminated());
            Thread.yield();
        }
        assertTrue(p.isQuiescent());
        assertFalse(p.getAsyncMode());
        assertEquals(0, p.getQueuedTaskCount());
        assertEquals(0, p.getQueuedSubmissionCount());
        assertFalse(p.hasQueuedSubmissions());
        while (p.getActiveThreadCount() != 0 && millisElapsedSince(startTime) < LONG_DELAY_MS) Thread.yield();
        assertFalse(p.isShutdown());
        assertFalse(p.isTerminating());
        assertFalse(p.isTerminated());
        assertTrue(f.isDone());
        assertEquals(6765, (int) f.get());
        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
    }
}
Example 45
Project: ARTPart-master  File: ThreadTest.java View source code
public void run() {
    SimpleThread st1 = null;
    SimpleThread st2 = null;
    ThreadGroup mytg = null;
    Thread firstOne = null;
    Thread secondOne = null;
    try {
        int arrayLength = 10;
        Thread[] tarray = new Thread[arrayLength];
        st1 = new SimpleThread(-1);
        st2 = new SimpleThread(-1);
        mytg = new ThreadGroup("jp");
        firstOne = new Thread(mytg, st1, "firstOne2");
        secondOne = new Thread(mytg, st2, "secondOne1");
        int count = Thread.enumerate(tarray);
        assertEquals("Incorrect value returned1", 1, count);
        synchronized (st1) {
            firstOne.start();
            try {
                st1.wait();
            } catch (InterruptedException e) {
            }
        }
        count = Thread.enumerate(tarray);
        assertEquals("Incorrect value returned2", 2, count);
        synchronized (st2) {
            secondOne.start();
            try {
                st2.wait();
            } catch (InterruptedException e) {
            }
        }
        count = Thread.enumerate(tarray);
        assertEquals("Incorrect value returned3", 3, count);
    } catch (junit.framework.AssertionFailedError e) {
        failed = true;
        failMessage = e.getMessage();
    } finally {
        synchronized (st1) {
            firstOne.interrupt();
        }
        synchronized (st2) {
            secondOne.interrupt();
        }
        try {
            firstOne.join();
            secondOne.join();
        } catch (InterruptedException e) {
        }
        mytg.destroy();
    }
}
Example 46
Project: lucene-solr-master  File: DistributedFacetPivotSmallTest.java View source code
@Test
@ShardsFixed(num = 4)
public void test() throws Exception {
    del("*:*");
    // NOTE: we use the literal (4 character) string "null" as a company name
    // to help ensure there isn't any bugs where the literal string is treated as if it 
    // were a true NULL value.
    index(id, 19, "place_t", "cardiff dublin", "company_t", "microsoft polecat", "price_ti", "15");
    index(id, 20, "place_t", "dublin", "company_t", "polecat microsoft null", "price_ti", "19", // TODO: add enum field - blocked by SOLR-6682
    "solo_i", 42, "solo_s", "lonely", "solo_dt", "1976-03-06T01:23:45Z");
    index(id, 21, "place_t", "london la dublin", "company_t", "microsoft fujitsu null polecat", "price_ti", "29");
    index(id, 22, "place_t", "krakow london cardiff", "company_t", "polecat null bbc", "price_ti", "39");
    index(id, 23, "place_t", "london", "company_t", "", "price_ti", "29");
    index(id, 24, "place_t", "la", "company_t", "");
    index(id, 25, "company_t", "microsoft polecat null fujitsu null bbc", "price_ti", "59");
    index(id, 26, "place_t", "krakow", "company_t", "null");
    index(id, 27, "place_t", "krakow cardiff dublin london la", "company_t", "null microsoft polecat bbc fujitsu");
    index(id, 28, "place_t", "cork", "company_t", "fujitsu rte");
    commit();
    handle.clear();
    handle.put("QTime", SKIPVAL);
    handle.put("timestamp", SKIPVAL);
    handle.put("maxScore", SKIPVAL);
    final ModifiableSolrParams params = new ModifiableSolrParams();
    setDistributedParams(params);
    params.add("q", "*:*");
    params.add("facet", "true");
    params.add("facet.pivot", "place_t,company_t");
    QueryResponse rsp = queryServer(params);
    List<PivotField> expectedPlacePivots = new UnorderedEqualityArrayList<PivotField>();
    List<PivotField> expectedCardiffPivots = new UnorderedEqualityArrayList<PivotField>();
    expectedCardiffPivots.add(new ComparablePivotField("company_t", "microsoft", 2, null));
    expectedCardiffPivots.add(new ComparablePivotField("company_t", "null", 2, null));
    expectedCardiffPivots.add(new ComparablePivotField("company_t", "bbc", 2, null));
    expectedCardiffPivots.add(new ComparablePivotField("company_t", "polecat", 3, null));
    expectedCardiffPivots.add(new ComparablePivotField("company_t", "fujitsu", 1, null));
    List<PivotField> expectedDublinPivots = new UnorderedEqualityArrayList<PivotField>();
    expectedDublinPivots.add(new ComparablePivotField("company_t", "polecat", 4, null));
    expectedDublinPivots.add(new ComparablePivotField("company_t", "microsoft", 4, null));
    expectedDublinPivots.add(new ComparablePivotField("company_t", "null", 3, null));
    expectedDublinPivots.add(new ComparablePivotField("company_t", "fujitsu", 2, null));
    expectedDublinPivots.add(new ComparablePivotField("company_t", "bbc", 1, null));
    List<PivotField> expectedLondonPivots = new UnorderedEqualityArrayList<PivotField>();
    expectedLondonPivots.add(new ComparablePivotField("company_t", "polecat", 3, null));
    expectedLondonPivots.add(new ComparablePivotField("company_t", "microsoft", 2, null));
    expectedLondonPivots.add(new ComparablePivotField("company_t", "fujitsu", 2, null));
    expectedLondonPivots.add(new ComparablePivotField("company_t", "null", 3, null));
    expectedLondonPivots.add(new ComparablePivotField("company_t", "bbc", 2, null));
    List<PivotField> expectedLAPivots = new UnorderedEqualityArrayList<PivotField>();
    expectedLAPivots.add(new ComparablePivotField("company_t", "microsoft", 2, null));
    expectedLAPivots.add(new ComparablePivotField("company_t", "fujitsu", 2, null));
    expectedLAPivots.add(new ComparablePivotField("company_t", "null", 2, null));
    expectedLAPivots.add(new ComparablePivotField("company_t", "bbc", 1, null));
    expectedLAPivots.add(new ComparablePivotField("company_t", "polecat", 2, null));
    List<PivotField> expectedKrakowPivots = new UnorderedEqualityArrayList<PivotField>();
    expectedKrakowPivots.add(new ComparablePivotField("company_t", "polecat", 2, null));
    expectedKrakowPivots.add(new ComparablePivotField("company_t", "bbc", 2, null));
    expectedKrakowPivots.add(new ComparablePivotField("company_t", "null", 3, null));
    expectedKrakowPivots.add(new ComparablePivotField("company_t", "fujitsu", 1, null));
    expectedKrakowPivots.add(new ComparablePivotField("company_t", "microsoft", 1, null));
    List<PivotField> expectedCorkPivots = new UnorderedEqualityArrayList<PivotField>();
    expectedCorkPivots.add(new ComparablePivotField("company_t", "fujitsu", 1, null));
    expectedCorkPivots.add(new ComparablePivotField("company_t", "rte", 1, null));
    expectedPlacePivots.add(new ComparablePivotField("place_t", "dublin", 4, expectedDublinPivots));
    expectedPlacePivots.add(new ComparablePivotField("place_t", "cardiff", 3, expectedCardiffPivots));
    expectedPlacePivots.add(new ComparablePivotField("place_t", "london", 4, expectedLondonPivots));
    expectedPlacePivots.add(new ComparablePivotField("place_t", "la", 3, expectedLAPivots));
    expectedPlacePivots.add(new ComparablePivotField("place_t", "krakow", 3, expectedKrakowPivots));
    expectedPlacePivots.add(new ComparablePivotField("place_t", "cork", 1, expectedCorkPivots));
    List<PivotField> placePivots = rsp.getFacetPivot().get("place_t,company_t");
    // Useful to check for errors, orders lists and does toString() equality
    // check
    testOrderedPivotsStringEquality(expectedPlacePivots, placePivots);
    assertEquals(expectedPlacePivots, placePivots);
    // Test sorting by count
    params.set(FacetParams.FACET_SORT, FacetParams.FACET_SORT_COUNT);
    rsp = queryServer(params);
    placePivots = rsp.getFacetPivot().get("place_t,company_t");
    testCountSorting(placePivots);
    // Test limit
    params.set(FacetParams.FACET_LIMIT, 2);
    rsp = queryServer(params);
    expectedPlacePivots = new UnorderedEqualityArrayList<PivotField>();
    expectedDublinPivots = new UnorderedEqualityArrayList<PivotField>();
    expectedDublinPivots.add(new ComparablePivotField("company_t", "polecat", 4, null));
    expectedDublinPivots.add(new ComparablePivotField("company_t", "microsoft", 4, null));
    expectedLondonPivots = new UnorderedEqualityArrayList<PivotField>();
    expectedLondonPivots.add(new ComparablePivotField("company_t", "null", 3, null));
    expectedLondonPivots.add(new ComparablePivotField("company_t", "polecat", 3, null));
    expectedPlacePivots.add(new ComparablePivotField("place_t", "dublin", 4, expectedDublinPivots));
    expectedPlacePivots.add(new ComparablePivotField("place_t", "london", 4, expectedLondonPivots));
    placePivots = rsp.getFacetPivot().get("place_t,company_t");
    assertEquals(expectedPlacePivots, placePivots);
    // Test individual facet.limit values
    params.remove(FacetParams.FACET_LIMIT);
    params.set("f.place_t." + FacetParams.FACET_LIMIT, 1);
    params.set("f.company_t." + FacetParams.FACET_LIMIT, 4);
    rsp = queryServer(params);
    expectedPlacePivots = new UnorderedEqualityArrayList<PivotField>();
    expectedDublinPivots = new UnorderedEqualityArrayList<PivotField>();
    expectedDublinPivots.add(new ComparablePivotField("company_t", "microsoft", 4, null));
    expectedDublinPivots.add(new ComparablePivotField("company_t", "polecat", 4, null));
    expectedDublinPivots.add(new ComparablePivotField("company_t", "null", 3, null));
    expectedDublinPivots.add(new ComparablePivotField("company_t", "fujitsu", 2, null));
    expectedLondonPivots = new UnorderedEqualityArrayList<PivotField>();
    expectedLondonPivots.add(new ComparablePivotField("company_t", "null", 3, null));
    expectedLondonPivots.add(new ComparablePivotField("company_t", "polecat", 3, null));
    expectedLondonPivots.add(new ComparablePivotField("company_t", "bbc", 2, null));
    expectedLondonPivots.add(new ComparablePivotField("company_t", "fujitsu", 2, null));
    expectedCardiffPivots = new UnorderedEqualityArrayList<PivotField>();
    expectedCardiffPivots.add(new ComparablePivotField("company_t", "polecat", 3, null));
    expectedKrakowPivots = new UnorderedEqualityArrayList<PivotField>();
    expectedKrakowPivots.add(new ComparablePivotField("company_t", "null", 3, null));
    expectedLAPivots = new UnorderedEqualityArrayList<PivotField>();
    expectedLAPivots.add(new ComparablePivotField("company_t", "fujitsu", 2, null));
    expectedCorkPivots = new UnorderedEqualityArrayList<PivotField>();
    expectedCorkPivots.add(new ComparablePivotField("company_t", "fujitsu", 1, null));
    expectedPlacePivots.add(new ComparablePivotField("place_t", "dublin", 4, expectedDublinPivots));
    placePivots = rsp.getFacetPivot().get("place_t,company_t");
    assertEquals(expectedPlacePivots, placePivots);
    params.remove("f.company_t." + FacetParams.FACET_LIMIT);
    params.remove("f.place_t." + FacetParams.FACET_LIMIT);
    params.set(FacetParams.FACET_LIMIT, 2);
    // Test facet.missing=true with diff sorts
    // NOTE: id=25 has no place as well
    index("id", 777);
    commit();
    SolrParams missingA = params("q", "*:*", "rows", "0", "facet", "true", "facet.pivot", "place_t,company_t", "f.place_t.facet.mincount", "2", // default facet.sort
    FacetParams.FACET_MISSING, "true");
    SolrParams missingB = SolrParams.wrapDefaults(missingA, params(FacetParams.FACET_LIMIT, "4", "facet.sort", "index"));
    for (SolrParams p : new SolrParams[] { missingA, missingB }) {
        // in either case, the last pivot option should be the same
        rsp = query(p);
        placePivots = rsp.getFacetPivot().get("place_t,company_t");
        assertTrue("not enough values for pivot: " + p + " => " + placePivots, 1 < placePivots.size());
        PivotField missing = placePivots.get(placePivots.size() - 1);
        assertNull("not the missing place value: " + p, missing.getValue());
        assertEquals("wrong missing place count: " + p, 2, missing.getCount());
        assertTrue("not enough sub-pivots for missing place: " + p + " => " + missing.getPivot(), 1 < missing.getPivot().size());
        missing = missing.getPivot().get(missing.getPivot().size() - 1);
        assertNull("not the missing company value: " + p, missing.getValue());
        assertEquals("wrong missing company count: " + p, 1, missing.getCount());
        assertNull("company shouldn't have sub-pivots: " + p, missing.getPivot());
    }
    // sort=index + mincount + limit
    for (SolrParams variableParams : new SolrParams[] { // we should get the same results regardless of overrequest
    params("facet.overrequest.count", "0", "facet.overrequest.ratio", "0"), params() }) {
        SolrParams p = SolrParams.wrapDefaults(params("q", "*:*", "rows", "0", "facet", "true", "facet.pivot", "company_t", "facet.sort", "index", "facet.pivot.mincount", "4", "facet.limit", "4"), variableParams);
        try {
            List<PivotField> pivots = query(p).getFacetPivot().get("company_t");
            assertEquals(4, pivots.size());
            assertEquals("fujitsu", pivots.get(0).getValue());
            assertEquals(4, pivots.get(0).getCount());
            assertEquals("microsoft", pivots.get(1).getValue());
            assertEquals(5, pivots.get(1).getCount());
            assertEquals("null", pivots.get(2).getValue());
            assertEquals(6, pivots.get(2).getCount());
            assertEquals("polecat", pivots.get(3).getValue());
            assertEquals(6, pivots.get(3).getCount());
        } catch (AssertionFailedError ae) {
            throw new AssertionError(ae.getMessage() + " <== " + p.toString(), ae);
        }
    }
    // sort=index + mincount + limit + offset
    for (SolrParams variableParams : new SolrParams[] { // we should get the same results regardless of overrequest
    params("facet.overrequest.count", "0", "facet.overrequest.ratio", "0"), params() }) {
        SolrParams p = SolrParams.wrapDefaults(params("q", "*:*", "rows", "0", "facet", "true", "facet.pivot", "company_t", "facet.sort", "index", "facet.pivot.mincount", "4", "facet.offset", "1", "facet.limit", "4"), variableParams);
        try {
            List<PivotField> pivots = query(p).getFacetPivot().get("company_t");
            // asked for 4, but not enough meet the mincount
            assertEquals(3, pivots.size());
            assertEquals("microsoft", pivots.get(0).getValue());
            assertEquals(5, pivots.get(0).getCount());
            assertEquals("null", pivots.get(1).getValue());
            assertEquals(6, pivots.get(1).getCount());
            assertEquals("polecat", pivots.get(2).getValue());
            assertEquals(6, pivots.get(2).getCount());
        } catch (AssertionFailedError ae) {
            throw new AssertionError(ae.getMessage() + " <== " + p.toString(), ae);
        }
    }
    // sort=index + mincount + limit + offset (more permutations)
    for (SolrParams variableParams : new SolrParams[] { // all of these combinations should result in the same first value
    params("facet.pivot.mincount", "4", "facet.offset", "2"), params("facet.pivot.mincount", "5", "facet.offset", "1"), params("facet.pivot.mincount", "6", "facet.offset", "0") }) {
        SolrParams p = SolrParams.wrapDefaults(params("q", "*:*", "rows", "0", "facet", "true", "facet.limit", "1", "facet.sort", "index", "facet.overrequest.ratio", "0", "facet.pivot", "company_t"), variableParams);
        try {
            List<PivotField> pivots = query(p).getFacetPivot().get("company_t");
            assertEquals(1, pivots.size());
            assertEquals(pivots.toString(), "null", pivots.get(0).getValue());
            assertEquals(pivots.toString(), 6, pivots.get(0).getCount());
        } catch (AssertionFailedError ae) {
            throw new AssertionError(ae.getMessage() + " <== " + p.toString(), ae);
        }
    }
    // all price stats
    doTestDeepPivotStats(false);
    // just the mean price stat
    doTestDeepPivotStats(true);
    doTestPivotStatsFromOneShard();
    testFacetPivotRange();
    testFacetPivotQuery();
    testNegativeFacetQuery();
    testNegativeRangeQuery();
    testPivotFacetRangeAndQuery();
}
Example 47
Project: platform_tools_adt_idea-master  File: RenderErrorPanelTest.java View source code
public void testWrongClassFormat() {
    LogOperation operation = new LogOperation() {

        @Override
        public void addErrors(@NotNull RenderLogger logger, @NotNull RenderResult render) {
            // MANUALLY register errors
            logger.addIncorrectFormatClass("com.example.unit.test.R", new InconvertibleClassError(null, "com.example.unit.test.R", 51, 0));
            logger.addIncorrectFormatClass("com.example.unit.test.MyButton", new InconvertibleClassError(null, "com.example.unit.test.MyButton", 52, 0));
        }
    };
    String html = getRenderOutput(myFixture.copyFileToProject(BASE_PATH + "layout2.xml", "res/layout/layout.xml"), operation);
    String current = ClassConverter.getCurrentJdkVersion();
    try {
        assertHtmlEquals("<html><body><A HREF=\"action:close\"></A><font style=\"font-weight:bold; color:#005555;\">Rendering Problems</font><BR/>\n" + "Preview might be incorrect: unsupported class version.<BR/>\n" + "Tip: You need to run the IDE with the highest JDK version that you are compiling custom views with. " + "One or more views have been compiled with JDK 1.8, but you are running the IDE on JDK " + current + ". Running on a higher " + "JDK is necessary such that these classes can be run in the layout renderer. (Or, extract your custom views into a " + "library which you compile with a lower JDK version.)<BR/>\n" + "<BR/>\n" + "If you have just accidentally built your code with a later JDK, try to <A HREF=\"action:build\">build</A> the project.<BR/>\n" + "<BR/>\n" + "Classes with incompatible format:<DL>\n" + "<DD>-&NBSP;com.example.unit.test.MyButton (Compiled with 1.8)\n" + "<DD>-&NBSP;com.example.unit.test.R (Compiled with 1.7)\n" + "</DL><A HREF=\"runnable:0\">Rebuild project with '-target 1.6'</A><BR/>\n" + "</body></html>", html);
    } catch (AssertionFailedError e) {
        System.out.println(getName() + " failed. Test temporarily disabled since it seems to work locally and I cannot figure out " + "why it fails on the build server. Original failure output: " + e.getMessage());
    }
}
Example 48
Project: sosies-generator-master  File: FileWriterWithEncodingTest.java View source code
@Test(timeout = 1000)
public void testDifferentEncoding_add1016() throws Exception {
    fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(), this, "testDifferentEncoding_add1016");
    if (java.nio.charset.Charset.isSupported("UTF-16BE")) {
        FileWriter fw1 = null;
        FileWriterWithEncoding fw2 = null;
        try {
            fw1 = new FileWriter(file1);
            fw2 = new FileWriterWithEncoding(file2, defaultEncoding);
            fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1493, file1, 1492, file1.exists());
            fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1495, file2, 1494, file2.exists());
            fw1.write(textContent);
            fw1.write(textContent);
            fw2.write(textContent);
            fw1.flush();
            fw2.flush();
            try {
                checkFile(file1, file2);
            } catch (AssertionFailedError ex) {
            }
        } finally {
            org.apache.commons.io.IOUtils.closeQuietly(fw1);
            org.apache.commons.io.IOUtils.closeQuietly(fw2);
        }
        fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1497, file1, 1496, file1.exists());
        fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1499, file2, 1498, file2.exists());
    }
    if (java.nio.charset.Charset.isSupported("UTF-16LE")) {
        FileWriter fw1 = null;
        FileWriterWithEncoding fw2 = null;
        try {
            fw1 = new FileWriter(file1);
            fw2 = new FileWriterWithEncoding(file2, defaultEncoding);
            fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1501, file1, 1500, file1.exists());
            fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1503, file2, 1502, file2.exists());
            fw1.write(textContent);
            fw2.write(textContent);
            fw1.flush();
            fw2.flush();
            try {
                checkFile(file1, file2);
            } catch (AssertionFailedError ex) {
            }
        } finally {
            org.apache.commons.io.IOUtils.closeQuietly(fw1);
            org.apache.commons.io.IOUtils.closeQuietly(fw2);
        }
        fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1505, file1, 1504, file1.exists());
        fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1507, file2, 1506, file2.exists());
    }
    fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread());
}
Example 49
Project: cdt-master  File: RenameRegressionTests.java View source code
public void testConstructor_26() throws Exception {
    StringWriter writer = new StringWriter();
    writer.write("class Boo{                   \n");
    writer.write("  Boo(){}//vp1,res1  \n");
    writer.write("};                           \n");
    writer.write("void f() {                   \n");
    writer.write("   Boo a = new Boo();                    \n");
    writer.write("}                            \n");
    String contents = writer.toString();
    IFile file = importFile("t.cpp", contents);
    int offset = contents.indexOf("Boo(){}");
    try {
        getRefactorChanges(file, offset, "ooga");
    } catch (AssertionFailedError e) {
        assertTrue(e.getMessage().startsWith("Input check on ooga failed."));
        return;
    }
    fail("An error should have occurred in the input check.");
}
Example 50
Project: flare-spork-master  File: TestLogicalPlanBuilder.java View source code
@Test
public void testQueryFail72() throws Exception {
    boolean catchEx = false;
    String q = "split (load 'a') into x if $0 > '7', y if $0 < '7';";
    try {
        buildPlan(q + "c = foreach y generate (bag)$1;");
    } catch (AssertionFailedError e) {
        catchEx = true;
    }
    Assert.assertTrue(catchEx);
    catchEx = false;
    try {
        buildPlan(q + "c = foreach y generate (bag{int, float})$1;");
    } catch (AssertionFailedError e) {
        catchEx = true;
    }
    Assert.assertTrue(catchEx);
    catchEx = false;
    try {
        buildPlan(q + "c = foreach y generate (tuple)$1;");
    } catch (AssertionFailedError e) {
        catchEx = true;
    }
    Assert.assertTrue(catchEx);
}