use of com.path.android.jobqueue.test.jobs.DummyJob in project android-priority-jobqueue by path.
the class InjectorTest method testInjectorCrash.
@Test
public void testInjectorCrash() throws Exception {
final String EXCEPTION_MESSAGE = "could not inject for whatever reason :)";
DependencyInjector dummyDependencyInjector = new DependencyInjector() {
@Override
public void inject(BaseJob baseJob) {
throw new RuntimeException(EXCEPTION_MESSAGE);
}
};
final ObjectReference objectReference = new ObjectReference();
final CountDownLatch exceptionLatch = new CountDownLatch(1);
CustomLogger customLogger = new CustomLogger() {
@Override
public boolean isDebugEnabled() {
return false;
}
@Override
public void d(String s, Object... objects) {
}
@Override
public void e(Throwable throwable, String s, Object... objects) {
objectReference.setObject(throwable);
exceptionLatch.countDown();
}
@Override
public void e(String s, Object... objects) {
//
}
};
JobManager jobManager = createJobManager(new Configuration.Builder(Robolectric.application).injector(dummyDependencyInjector).customLogger(customLogger));
Throwable addException = null;
try {
jobManager.addJob(new DummyJob(new Params(0)));
} catch (Throwable t) {
addException = t;
}
MatcherAssert.assertThat("addJob should throw exception if dependency injector throws exception", addException, notNullValue());
jobManager.addJobInBackground(new DummyJob(new Params(0)));
exceptionLatch.await(2, TimeUnit.SECONDS);
MatcherAssert.assertThat("there should be a received exception", objectReference.getObject(), notNullValue());
MatcherAssert.assertThat("logged exception should be a runtime exception", objectReference.getObject(), instanceOf(RuntimeException.class));
MatcherAssert.assertThat("logged exception should have expected message", ((Throwable) objectReference.getObject()).getMessage(), is(EXCEPTION_MESSAGE));
}
use of com.path.android.jobqueue.test.jobs.DummyJob in project android-priority-jobqueue by path.
the class JobStatusTest method testJobStatus.
@Test
public void testJobStatus() throws InterruptedException {
DummyNetworkUtilWithConnectivityEventSupport networkUtil = new DummyNetworkUtilWithConnectivityEventSupport();
networkUtil.setHasNetwork(false, true);
JobManager jobManager = createJobManager(new Configuration.Builder(Robolectric.application).networkUtil(networkUtil));
jobManager.stop();
List<Integer> networkRequiringJobIndices = new ArrayList<Integer>();
Job[] jobs = new Job[] { new DummyJob(new Params(0)), new DummyJob(new Params(0).persist()), new DummyJob(new Params(0).persist().requireNetwork()) };
long[] ids = new long[jobs.length];
for (int i = 0; i < jobs.length; i++) {
ids[i] = jobManager.addJob(jobs[i]);
if (jobs[i].requiresNetwork()) {
networkRequiringJobIndices.add(i);
}
JobStatus expectedStatus = (networkUtil.isConnected() || jobs[i].requiresNetwork() == false) ? JobStatus.WAITING_READY : JobStatus.WAITING_NOT_READY;
assertThat("job should have correct status after being added", jobManager.getJobStatus(ids[i], jobs[i].isPersistent()), is(expectedStatus));
}
// create an unknown id, ensure status for that
boolean exists;
long unknownId;
do {
unknownId = (long) (Math.random() * 10000 - 5000);
exists = false;
for (long id : ids) {
if (id == unknownId) {
exists = true;
continue;
}
}
} while (exists);
for (boolean persistent : new boolean[] { true, false }) {
assertThat("job with unknown id should return as expected", jobManager.getJobStatus(unknownId, persistent), is(JobStatus.UNKNOWN));
}
CountDownLatch startLatch = new CountDownLatch(1), endLatch = new CountDownLatch(1);
DummyTwoLatchJob twoLatchJob = new DummyTwoLatchJob(new Params(0), startLatch, endLatch);
jobManager.start();
long jobId = jobManager.addJob(twoLatchJob);
twoLatchJob.waitTillOnRun();
assertThat("job should be in running state", jobManager.getJobStatus(jobId, false), is(JobStatus.RUNNING));
// let it run
startLatch.countDown();
// wait till it finishes
endLatch.await();
// give some time to job manager to clear the job
Thread.sleep(500);
assertThat("finished job should go to unknown state", jobManager.getJobStatus(jobId, false), is(JobStatus.UNKNOWN));
// network requiring job should not be ready
for (Integer i : networkRequiringJobIndices) {
assertThat("network requiring job should still be not-ready", jobManager.getJobStatus(ids[i], jobs[i].isPersistent()), is(JobStatus.WAITING_NOT_READY));
}
jobManager.stop();
networkUtil.setHasNetwork(true, true);
for (Integer i : networkRequiringJobIndices) {
assertThat("network requiring job should still be ready after network is there", jobManager.getJobStatus(ids[i], jobs[i].isPersistent()), is(JobStatus.WAITING_READY));
}
jobManager.start();
int limit = 10;
while (jobManager.count() > 0 && limit-- > 0) {
Thread.sleep(1000);
}
assertThat("jobs should finish", jobManager.count(), is(0));
for (int i = 0; i < jobs.length; i++) {
// after all jobs finish, state should be unknown
assertThat("all jobs finished, states should be unknown", jobManager.getJobStatus(ids[i], jobs[i].isPersistent()), is(JobStatus.UNKNOWN));
}
final long SHORT_SLEEP = 1000;
Job[] delayedJobs = new Job[] { new DummyJob(new Params(0).delayInMs(SHORT_SLEEP)), new DummyJob(new Params(0).delayInMs(SHORT_SLEEP).persist()), new DummyJob(new Params(0).delayInMs(SHORT_SLEEP * 10)), new DummyJob(new Params(0).delayInMs(SHORT_SLEEP * 10).persist()) };
long[] delayedIds = new long[delayedJobs.length];
for (int i = 0; i < delayedJobs.length; i++) {
delayedIds[i] = jobManager.addJob(delayedJobs[i]);
}
for (int i = 0; i < delayedJobs.length; i++) {
assertThat("delayed job(" + i + ") should receive not ready status", jobManager.getJobStatus(delayedIds[i], delayedJobs[i].isPersistent()), is(JobStatus.WAITING_NOT_READY));
}
jobManager.stop();
// sleep
Thread.sleep(SHORT_SLEEP * 2);
for (int i = 0; i < delayedJobs.length; i++) {
if (delayedJobs[i].getDelayInMs() == SHORT_SLEEP) {
assertThat("when enough time passes, delayed jobs should move to ready state", jobManager.getJobStatus(delayedIds[i], delayedJobs[i].isPersistent()), is(JobStatus.WAITING_READY));
} else {
assertThat("delayed job should receive not ready status until their time comes", jobManager.getJobStatus(delayedIds[i], delayedJobs[i].isPersistent()), is(JobStatus.WAITING_NOT_READY));
}
}
}
use of com.path.android.jobqueue.test.jobs.DummyJob in project android-priority-jobqueue by path.
the class LoadFactorTest method testLoadFactor.
@Test
public void testLoadFactor() throws Exception {
// test adding zillions of jobs from the same group and ensure no more than 1 thread is created
int maxConsumerCount = 5;
int minConsumerCount = 2;
int loadFactor = 5;
com.path.android.jobqueue.JobManager jobManager = createJobManager(new Configuration.Builder(Robolectric.application).maxConsumerCount(maxConsumerCount).minConsumerCount(minConsumerCount).customLogger(new CustomLogger() {
public boolean isDebugEnabled() {
return true;
}
public void d(String text, Object... args) {
System.out.println(String.format(text, args));
}
public void e(Throwable t, String text, Object... args) {
t.printStackTrace();
System.out.println(String.format(text, args));
}
public void e(String text, Object... args) {
System.out.println(String.format(text, args));
}
}).loadFactor(loadFactor));
JobConsumerExecutor consumerExecutor = getConsumerExecutor(jobManager);
org.fest.reflect.field.Invoker<AtomicInteger> activeConsumerCnt = getActiveConsumerCount(consumerExecutor);
Object runLock = new Object();
Semaphore semaphore = new Semaphore(maxConsumerCount);
int totalJobCount = loadFactor * maxConsumerCount * 5;
List<DummyJob> runningJobs = new ArrayList<DummyJob>(totalJobCount);
for (int i = 0; i < totalJobCount; i++) {
DummyJob job = new NeverEndingDummyJob(new Params((int) (Math.random() * 3)), runLock, semaphore);
runningJobs.add(job);
jobManager.addJob(job);
int expectedConsumerCount = Math.min(maxConsumerCount, (int) Math.ceil((float) (i + 1) / loadFactor));
if (i >= minConsumerCount) {
expectedConsumerCount = Math.max(minConsumerCount, expectedConsumerCount);
}
// wait till enough jobs start
long now = System.nanoTime();
long waitTill = now + TimeUnit.SECONDS.toNanos(10);
while (System.nanoTime() < waitTill) {
if (semaphore.availablePermits() == maxConsumerCount - expectedConsumerCount) {
// enough # of jobs started
break;
}
}
if (i < loadFactor) {
// make sure there is only min job running
MatcherAssert.assertThat("while below load factor, active consumer count should be = min", activeConsumerCnt.get().get(), equalTo(Math.min(i + 1, minConsumerCount)));
}
if (i > loadFactor) {
// make sure there is only 1 job running
MatcherAssert.assertThat("while above load factor. there should be more job consumers. i=" + i, activeConsumerCnt.get().get(), equalTo(expectedConsumerCount));
}
}
// finish all jobs
long now = System.nanoTime();
long waitTill = now + TimeUnit.SECONDS.toNanos(10);
while (System.nanoTime() < waitTill) {
synchronized (runLock) {
runLock.notifyAll();
}
long totalRunningCount = 0;
for (DummyJob job : runningJobs) {
totalRunningCount += job.getOnRunCnt();
}
if (totalJobCount == totalRunningCount) {
// cool!
break;
}
}
MatcherAssert.assertThat("no jobs should remain", jobManager.count(), equalTo(0));
}
use of com.path.android.jobqueue.test.jobs.DummyJob in project android-priority-jobqueue by path.
the class NetworkJobWithConnectivityListenerTest method testNetworkJobWithConnectivityListener.
@Test
public void testNetworkJobWithConnectivityListener() throws Exception {
DummyNetworkUtilWithConnectivityEventSupport dummyNetworkUtil = new DummyNetworkUtilWithConnectivityEventSupport();
JobManager jobManager = createJobManager(new Configuration.Builder(Robolectric.application).networkUtil(dummyNetworkUtil));
dummyNetworkUtil.setHasNetwork(false, true);
DummyJob dummyJob = new DummyJob(new Params(0).requireNetwork());
long dummyJobId = jobManager.addJob(dummyJob);
// sleep a while so that consumers die. they should die since we are using a network util
Thread.sleep(2000);
// with event support
MatcherAssert.assertThat("count should be 1 as no jobs should be consumed w/o network", jobManager.count(), equalTo(1));
dummyNetworkUtil.setHasNetwork(true, false);
// wait a little bit more to consumer will run
Thread.sleep(1000);
MatcherAssert.assertThat("even though network is recovered, job manager should not consume any job because it " + "does not know (we did not inform)", jobManager.count(), equalTo(1));
dummyNetworkUtil.setHasNetwork(true, true);
// wait a little bit more to consumer will run
Thread.sleep(1000);
MatcherAssert.assertThat("job manager should consume network job after it is informed that network is recovered", jobManager.count(), equalTo(0));
}
use of com.path.android.jobqueue.test.jobs.DummyJob in project android-priority-jobqueue by path.
the class ConsumerCountTest method testMaxConsumerCount.
@Test
public void testMaxConsumerCount() throws Exception {
int maxConsumerCount = 2;
JobManager jobManager = createJobManager(new Configuration.Builder(Robolectric.application).maxConsumerCount(maxConsumerCount).loadFactor(maxConsumerCount));
Object runLock = new Object();
Semaphore semaphore = new Semaphore(maxConsumerCount);
int totalJobCount = maxConsumerCount * 3;
List<DummyJob> runningJobs = new ArrayList<DummyJob>(totalJobCount);
for (int i = 0; i < totalJobCount; i++) {
DummyJob job = new NeverEndingDummyJob(new Params((int) (Math.random() * 3)), runLock, semaphore);
runningJobs.add(job);
jobManager.addJob(job);
}
// wait till enough jobs start
long now = System.nanoTime();
long waitTill = now + TimeUnit.SECONDS.toNanos(10);
while (System.nanoTime() < waitTill) {
if (semaphore.availablePermits() == 0) {
// enough # of jobs started
break;
}
}
// wait some more to ensure no more jobs are started
Thread.sleep(TimeUnit.SECONDS.toMillis(3));
int totalRunningCount = 0;
for (DummyJob job : runningJobs) {
totalRunningCount += job.getOnRunCnt();
}
MatcherAssert.assertThat("only maxConsumerCount jobs should start", totalRunningCount, equalTo(maxConsumerCount));
// try to finish all jobs
// wait till enough jobs start
now = System.nanoTime();
waitTill = now + TimeUnit.SECONDS.toNanos(10);
while (System.nanoTime() < waitTill) {
synchronized (runLock) {
runLock.notifyAll();
}
totalRunningCount = 0;
for (DummyJob job : runningJobs) {
totalRunningCount += job.getOnRunCnt();
}
if (totalJobCount == totalRunningCount) {
// cool!
break;
}
}
MatcherAssert.assertThat("no jobs should remain", jobManager.count(), equalTo(0));
}
Aggregations