Search in sources :

Example 61 with AssertionFailedError

use of junit.framework.AssertionFailedError in project AntennaPod by AntennaPod.

the class PlaybackServiceMediaPlayerTest method resumeTestSkeleton.

private void resumeTestSkeleton(final PlayerStatus initialState, long timeoutSeconds) throws InterruptedException {
    final Context c = getInstrumentation().getTargetContext();
    final int latchCount = (initialState == PlayerStatus.PAUSED || initialState == PlayerStatus.PLAYING) ? 2 : (initialState == PlayerStatus.PREPARED) ? 1 : 0;
    final CountDownLatch countDownLatch = new CountDownLatch(latchCount);
    PlaybackServiceMediaPlayer.PSMPCallback callback = new DefaultPSMPCallback() {

        @Override
        public void statusChanged(LocalPSMP.PSMPInfo newInfo) {
            checkPSMPInfo(newInfo);
            if (newInfo.playerStatus == PlayerStatus.ERROR) {
                if (assertionError == null)
                    assertionError = new UnexpectedStateChange(newInfo.playerStatus);
            } else if (newInfo.playerStatus == PlayerStatus.PLAYING) {
                if (countDownLatch.getCount() == 0) {
                    if (assertionError == null)
                        assertionError = new UnexpectedStateChange(newInfo.playerStatus);
                } else {
                    countDownLatch.countDown();
                }
            }
        }

        @Override
        public boolean onMediaPlayerError(Object inObj, int what, int extra) {
            if (assertionError == null) {
                assertionError = new AssertionFailedError("Unexpected call of onMediaPlayerError");
            }
            return false;
        }
    };
    PlaybackServiceMediaPlayer psmp = new LocalPSMP(c, callback);
    if (initialState == PlayerStatus.PREPARED || initialState == PlayerStatus.PLAYING || initialState == PlayerStatus.PAUSED) {
        boolean startWhenPrepared = (initialState != PlayerStatus.PREPARED);
        psmp.playMediaObject(writeTestPlayable(PLAYABLE_FILE_URL, PLAYABLE_LOCAL_URL), false, startWhenPrepared, true);
    }
    if (initialState == PlayerStatus.PAUSED) {
        psmp.pause(false, false);
    }
    psmp.resume();
    boolean res = countDownLatch.await(timeoutSeconds, TimeUnit.SECONDS);
    if (assertionError != null)
        throw assertionError;
    assertTrue(res || (initialState != PlayerStatus.PAUSED && initialState != PlayerStatus.PREPARED));
    psmp.shutdown();
}
Also used : Context(android.content.Context) LocalPSMP(de.danoeh.antennapod.core.service.playback.LocalPSMP) PlaybackServiceMediaPlayer(de.danoeh.antennapod.core.service.playback.PlaybackServiceMediaPlayer) CountDownLatch(java.util.concurrent.CountDownLatch) AssertionFailedError(junit.framework.AssertionFailedError)

Example 62 with AssertionFailedError

use of junit.framework.AssertionFailedError in project ACS by ACS-Community.

the class HelperTest method testConcurrentChannelRetrieval.

/**
	 * One step up from {@link #testConcurrentChannelCreation()}, here we test concurrent calls to 
	 * {@link Helper#getNotificationChannel(String, String, String)} which are supposed to handle the 
	 * <code>NameAlreadyUsed</code> exception by making those later threads wait until the channel has 
	 * been created for the first thread, then sharing the channel object.
	 */
public void testConcurrentChannelRetrieval() throws Throwable {
    // one channel to be retrieved concurrently
    final String channelName = "testChannelForConcurrentRetrieval";
    final HelperWithChannelCreationSynch helper = new HelperWithChannelCreationSynch(channelName, getContainerServices(), nctx);
    assertChannel(false, channelName);
    class ChannelRetriever implements Callable<EventChannel> {

        private final CountDownLatch synchStart;

        ChannelRetriever(CountDownLatch synchStart) {
            this.synchStart = synchStart;
        }

        public EventChannel call() throws Exception {
            String factoryName = helper.getNotificationFactoryNameForChannel();
            return helper.getNotificationChannel(factoryName, synchStart);
        }
    }
    // we need at least two threads, but more threads may improve collision chances
    final int numCreators = 3;
    assertTrue(numCreators >= 2);
    ExecutorService pool = Executors.newFixedThreadPool(numCreators, getContainerServices().getThreadFactory());
    CountDownLatch synchCreationStart = new CountDownLatch(numCreators);
    List<Future<EventChannel>> results = new ArrayList<Future<EventChannel>>();
    // check the results
    EventChannel uniqueChannel = null;
    try {
        // Run the threads that request the same channel
        for (int i = 0; i < numCreators; i++) {
            results.add(pool.submit(new ChannelRetriever(synchCreationStart)));
        }
        // wait for all threads to finish. Waiting here instead of waiting on the future.get() calls
        // has the advantage that we can exit this method with a fail() without leaving an ongoing channel creation behind.
        pool.shutdown();
        assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS));
        for (Future<EventChannel> future : results) {
            try {
                EventChannel threadResult = future.get();
                // we only get here if threadResult != null, otherwise ex
                if (uniqueChannel != null) {
                    assertTrue(uniqueChannel._is_equivalent(threadResult));
                }
                uniqueChannel = threadResult;
            } catch (ExecutionException ex) {
                throw ex.getCause();
            } catch (AssertionFailedError ex) {
                throw ex;
            } catch (Throwable thr) {
                fail("Unexpected exception " + thr.toString());
            }
        }
        m_logger.info("All concurrent calls to getNotificationChannel got the same channel object.");
    } finally {
        if (uniqueChannel != null) {
            helper.destroyNotificationChannel(NC_KIND.value, uniqueChannel);
        }
    }
}
Also used : ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) Callable(java.util.concurrent.Callable) EventChannel(gov.sandia.NotifyMonitoringExt.EventChannel) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) ExecutionException(java.util.concurrent.ExecutionException) AssertionFailedError(junit.framework.AssertionFailedError)

Example 63 with AssertionFailedError

use of junit.framework.AssertionFailedError in project ACS by ACS-Community.

the class SubsysResourceMonitorTest method testResourceUnavailable.

/**
     * Simulates hanging monitor calls, and tests the notification of the error handler,
     * the creation and reuse of threads, the continuation and eventual termination of monitoring calls.  
     */
public void testResourceUnavailable() throws Exception {
    try {
        TestResource resource = new TestResource(logger);
        TestResourceChecker checker = new TestResourceChecker(resource, logger);
        TestErrorHandler handler = new TestErrorHandler(logger);
        subsysResourceMonitor.monitorResource(checker, handler);
        SubsysResourceMonitor.ResourceCheckRunner runner = subsysResourceMonitor.getResourceCheckRunner(checker);
        assertNotNull(runner);
        // to speed up the test a bit, compared to the default of 10
        runner.setCallTimeoutSeconds(3);
        // (1) we simulate an unavailable resource, as in a CORBA call that eventually times out
        int timeoutSeconds = runner.getCallTimeoutSeconds();
        // must be greater than timeoutSeconds to allow testing the behavior for unavailable resources
        int testDelaySeconds = 6 * timeoutSeconds + 1;
        assertTrue("for testing, the artifical resource check hanging time should not be an integer multiple of (timeoutSeconds + checkDelaySeconds), to avoid hitting the boundary where an exisitng thread can be reused vs. creating a new thread", testDelaySeconds % (timeoutSeconds + checkDelaySeconds) > 0);
        resource.setTestDelaySeconds(testDelaySeconds);
        int numMonitorCalls = 10;
        CountDownLatch timeoutSync = new CountDownLatch(numMonitorCalls);
        handler.setUnreachabilitySync(timeoutSync);
        int maxTotalTimeSeconds = (timeoutSeconds + checkDelaySeconds) * numMonitorCalls + 1;
        logger.info("Test thread will wait for " + numMonitorCalls + " unavailability notifications (at most " + maxTotalTimeSeconds + " seconds)");
        assertTrue("timeout occured while waiting for deliberately slow resource check calls", timeoutSync.await(maxTotalTimeSeconds, TimeUnit.SECONDS));
        logger.info("Test thread continues...");
        assertEquals(1, subsysResourceMonitor.getNumberOfMonitorTasks());
        assertEquals(numMonitorCalls, handler.getUnreachableCount());
        assertEquals(0, handler.getBadStateCount());
        List<Thread> threadsCreated = threadFactory._getAllThreadsCreated();
        // we expect one thread for the monitor scheduler, and some more threads for the asynchronous calls to the resource. 
        // Their number depends on how many checker threads had to be started before an initially hanging thread could be reused. 
        int numCheckerThreads = 1 + testDelaySeconds / (timeoutSeconds + checkDelaySeconds);
        assertEquals("The monitoring should have created " + (numCheckerThreads + 1) + " threads.", numCheckerThreads + 1, threadsCreated.size());
        // (2) we simulate a resource that's gone beyond repair, and whose error handler will request no further monitoring
        handler.setIsPermanentlyUnreachable(true);
        // wait to make sure that the permanent failure has been discovered
        Thread.sleep((checkDelaySeconds + timeoutSeconds + 1) * 1000);
        assertEquals("Monitoring should have been cancelled due to the permanent failure.", 0, subsysResourceMonitor.getNumberOfMonitorTasks());
        logger.info("done");
    } catch (AssertionFailedError e) {
        // we want to log this in order to compare timestamps with the other asynchronous activities
        logger.log(Level.SEVERE, "assertion failure", e);
        throw e;
    }
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) AssertionFailedError(junit.framework.AssertionFailedError)

Example 64 with AssertionFailedError

use of junit.framework.AssertionFailedError in project azure-iot-sdk-java by Azure.

the class HttpsTransportTest method sendMessagesResendsFailedBatch.

// Tests_SRS_HTTPSTRANSPORT_11_012: [If a previous send request had failed while in progress, the function shall resend the request.]
@Test
public void sendMessagesResendsFailedBatch(@Mocked final Message mockMsg, @Mocked final HttpsSingleMessage mockHttpsMsg, @Mocked final IotHubEventCallback mockCallback, @Mocked final HttpsBatchMessage mockBatch, @Mocked final ResponseMessage mockResponseMessage) throws URISyntaxException, IOException, SizeLimitExceededException {
    final Map<String, Object> context = new HashMap<>();
    new NonStrictExpectations() {

        {
            HttpsSingleMessage.parseHttpsMessage(mockMsg);
            result = mockHttpsMsg;
            new HttpsBatchMessage();
            result = mockBatch;
            mockConn.sendEvent((HttpsMessage) any);
            result = new IOException();
            result = mockResponseMessage;
        }
    };
    HttpsTransport transport = new HttpsTransport(mockConfig);
    transport.open();
    transport.addMessage(mockMsg, mockCallback, context);
    transport.addMessage(mockMsg, mockCallback, context);
    transport.addMessage(mockMsg, mockCallback, context);
    try {
        transport.sendMessages();
        throw new AssertionFailedError();
    } catch (IOException e) {
    }
    transport.addMessage(mockMsg, mockCallback, context);
    transport.sendMessages();
    final HttpsSingleMessage expectedSingleMsg = mockHttpsMsg;
    final HttpsMessage expectedMsg = mockBatch;
    new VerificationsInOrder() {

        {
            mockBatch.addMessage(expectedSingleMsg);
            times = 3;
            mockConn.sendEvent(expectedMsg);
            times = 2;
        }
    };
}
Also used : HashMap(java.util.HashMap) IOException(java.io.IOException) AssertionFailedError(junit.framework.AssertionFailedError) Test(org.junit.Test)

Example 65 with AssertionFailedError

use of junit.framework.AssertionFailedError in project aries by apache.

the class BundleMock method findEntries.

public Enumeration<URL> findEntries(String baseDir, String matchRule, boolean recurse) {
    System.err.println("findEntries: " + baseDir + ", " + matchRule + ", " + recurse);
    File base;
    try {
        base = new File(new File(new URL(location.replaceAll(" ", "%20")).toURI()), baseDir);
        System.err.println("Base dir: " + base);
    } catch (Exception e) {
        Error err = new AssertionFailedError("Unable to findEntries from " + location);
        err.initCause(e);
        throw err;
    }
    if (matchRule.equals("*.xml"))
        matchRule = ".*\\.xml";
    else
        matchRule = matchRule.replaceAll("\\*", ".*");
    System.err.println("matchrule: " + matchRule);
    final Pattern p = Pattern.compile(matchRule);
    File[] files = base.listFiles(new FileFilter() {

        public boolean accept(File pathname) {
            return pathname.isFile() && p.matcher(pathname.getName()).matches();
        }
    });
    Vector<URL> v = new Vector<URL>();
    if (files != null) {
        for (File f : files) {
            try {
                v.add(f.toURL());
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } else {
        System.err.println("no matching files");
    }
    if (v.isEmpty()) {
        return null;
    } else {
        System.err.println(v);
        return v.elements();
    }
}
Also used : Pattern(java.util.regex.Pattern) MalformedURLException(java.net.MalformedURLException) AssertionFailedError(junit.framework.AssertionFailedError) AssertionFailedError(junit.framework.AssertionFailedError) FileFilter(java.io.FileFilter) File(java.io.File) Vector(java.util.Vector) URL(java.net.URL) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException)

Aggregations

AssertionFailedError (junit.framework.AssertionFailedError)787 TestFailureException (org.apache.openejb.test.TestFailureException)503 JMSException (javax.jms.JMSException)336 EJBException (javax.ejb.EJBException)334 RemoteException (java.rmi.RemoteException)268 InitialContext (javax.naming.InitialContext)168 RemoveException (javax.ejb.RemoveException)80 CreateException (javax.ejb.CreateException)77 NamingException (javax.naming.NamingException)65 BasicStatefulObject (org.apache.openejb.test.stateful.BasicStatefulObject)42 Test (org.junit.Test)42 BasicBmpObject (org.apache.openejb.test.entity.bmp.BasicBmpObject)41 BasicStatelessObject (org.apache.openejb.test.stateless.BasicStatelessObject)38 CountDownLatch (java.util.concurrent.CountDownLatch)28 EntityManager (javax.persistence.EntityManager)21 HSSFWorkbook (org.apache.poi.hssf.usermodel.HSSFWorkbook)21 EntityManagerFactory (javax.persistence.EntityManagerFactory)17 IOException (java.io.IOException)16 DataSource (javax.sql.DataSource)16 ConnectionFactory (javax.jms.ConnectionFactory)15