use of com.birbit.android.jobqueue.test.jobs.DummyJob in project android-priority-jobqueue by yigit.
the class JobStatusTest method testJobStatus.
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Test
public void testJobStatus() throws InterruptedException {
DummyNetworkUtilWithConnectivityEventSupport networkUtil = new DummyNetworkUtilWithConnectivityEventSupport();
networkUtil.setNetworkStatus(NetworkUtil.DISCONNECTED, true);
final JobManager jobManager = createJobManager(new Configuration.Builder(RuntimeEnvironment.application).networkUtil(networkUtil).timer(mockTimer));
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().addTags(REQ_NETWORK_TAG)) };
String[] ids = new String[jobs.length];
networkRequiringJobIndices.add(2);
for (int i = 0; i < jobs.length; i++) {
jobManager.addJob(jobs[i]);
ids[i] = jobs[i].getId();
JobStatus expectedStatus = (!networkUtil.isDisconnected() || !networkRequiringJobIndices.contains(i)) ? JobStatus.WAITING_READY : JobStatus.WAITING_NOT_READY;
assertThat("job should have correct status after being added", jobManager.getJobStatus(ids[i]), is(expectedStatus));
}
//create an unknown id, ensure status for that
boolean exists;
String unknownId;
do {
unknownId = UUID.randomUUID().toString();
exists = false;
for (String id : ids) {
if (unknownId.equals(id)) {
exists = true;
}
}
} while (exists);
for (boolean persistent : new boolean[] { true, false }) {
assertThat("job with unknown id should return as expected", jobManager.getJobStatus(unknownId), is(JobStatus.UNKNOWN));
}
final CountDownLatch startLatch = new CountDownLatch(1), endLatch = new CountDownLatch(1);
final DummyTwoLatchJob twoLatchJob = new DummyTwoLatchJob(new Params(0), startLatch, endLatch);
jobManager.start();
jobManager.addJob(twoLatchJob);
final String jobId = twoLatchJob.getId();
twoLatchJob.waitTillOnRun();
final CountDownLatch twoLatchJobDone = new CountDownLatch(1);
jobManager.addCallback(new JobManagerCallbackAdapter() {
@Override
public void onAfterJobRun(@NonNull Job job, int resultCode) {
if (job == twoLatchJob && resultCode == RESULT_SUCCEED) {
jobManager.removeCallback(this);
twoLatchJobDone.countDown();
}
}
});
assertThat("job should be in running state", jobManager.getJobStatus(jobId), is(JobStatus.RUNNING));
//let it run
startLatch.countDown();
try {
//wait till it finishes
endLatch.await();
} catch (InterruptedException ignored) {
}
twoLatchJobDone.await(1, TimeUnit.MINUTES);
assertThat("finished job should go to unknown state. id: " + jobId, jobManager.getJobStatus(jobId), 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]), is(JobStatus.WAITING_NOT_READY));
}
jobManager.stop();
networkUtil.setNetworkStatus(NetworkUtil.METERED, true);
for (Integer i : networkRequiringJobIndices) {
assertThat("network requiring job should still be ready after network is there", jobManager.getJobStatus(ids[i]), is(JobStatus.WAITING_READY));
}
final CountDownLatch networkRequiredLatch = new CountDownLatch(networkRequiringJobIndices.size());
jobManager.addCallback(new JobManagerCallbackAdapter() {
@Override
public void onDone(@NonNull Job job) {
if (job.getTags().contains(REQ_NETWORK_TAG)) {
networkRequiredLatch.countDown();
}
}
});
jobManager.start();
networkRequiredLatch.await(1, TimeUnit.MINUTES);
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]), is(JobStatus.UNKNOWN));
}
final long SHORT_SLEEP = 2000;
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()) };
String[] delayedIds = new String[delayedJobs.length];
long start = mockTimer.nanoTime();
for (int i = 0; i < delayedJobs.length; i++) {
jobManager.addJob(delayedJobs[i]);
delayedIds[i] = delayedJobs[i].getId();
}
for (int i = 0; i < delayedJobs.length; i++) {
assertThat("delayed job(" + i + ") should receive not ready status. startMs:" + start, jobManager.getJobStatus(delayedIds[i]), is(JobStatus.WAITING_NOT_READY));
}
jobManager.stop();
//sleep
mockTimer.incrementMs(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]), is(JobStatus.WAITING_READY));
} else {
assertThat("delayed job should receive not ready status until their time comes", jobManager.getJobStatus(delayedIds[i]), is(JobStatus.WAITING_NOT_READY));
}
}
}
use of com.birbit.android.jobqueue.test.jobs.DummyJob in project android-priority-jobqueue by yigit.
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;
enableDebug();
JobManager jobManager = createJobManager(new Configuration.Builder(RuntimeEnvironment.application).maxConsumerCount(maxConsumerCount).minConsumerCount(minConsumerCount).loadFactor(loadFactor).timer(mockTimer));
final CountDownLatch runLock = new CountDownLatch(1);
Semaphore semaphore = new Semaphore(maxConsumerCount);
int totalJobCount = loadFactor * maxConsumerCount * 5;
List<DummyJob> runningJobs = new ArrayList<DummyJob>(totalJobCount);
int prevConsumerCount = 0;
final Semaphore onRunCount = new Semaphore(totalJobCount);
onRunCount.acquire(totalJobCount);
for (int i = 0; i < totalJobCount; i++) {
DummyJob job = new NeverEndingDummyJob(new Params((int) (Math.random() * 3)), runLock, semaphore) {
@Override
public void onRun() throws Throwable {
onRunCount.release();
super.onRun();
}
};
runningJobs.add(job);
jobManager.addJob(job);
final int wantedConsumers = (int) Math.ceil((i + 1f) / loadFactor);
final int expectedConsumerCount = Math.max(Math.min(i + 1, minConsumerCount), Math.min(maxConsumerCount, wantedConsumers));
if (prevConsumerCount != expectedConsumerCount) {
assertThat("waiting for another job to start", onRunCount.tryAcquire(1, 10, TimeUnit.SECONDS), is(true));
}
assertThat("Consumer count should match expected value at " + (i + 1) + " jobs", jobManager.getActiveConsumerCount(), equalTo(expectedConsumerCount));
prevConsumerCount = expectedConsumerCount;
}
//finish all jobs
waitUntilJobsAreDone(jobManager, runningJobs, new Runnable() {
@Override
public void run() {
runLock.countDown();
}
});
assertThat("no jobs should remain", jobManager.count(), equalTo(0));
}
use of com.birbit.android.jobqueue.test.jobs.DummyJob in project android-priority-jobqueue by yigit.
the class AssertThreadsTest method assertFailure.
private void assertFailure(final Runnable runnable) throws InterruptedException {
final Throwable[] throwable = new Throwable[1];
jobManager = createJobManager();
final DummyJob dummyJob = new DummyJob(new Params(0)) {
@Override
public void onAdded() {
super.onAdded();
try {
runnable.run();
} catch (Throwable t) {
throwable[0] = t;
}
}
};
waitUntilAJobIsDone(jobManager, new WaitUntilCallback() {
@Override
public void run() {
jobManager.addJob(dummyJob);
}
@Override
public void assertJob(Job job) {
}
});
assertThat(throwable[0] instanceof WrongThreadException, is(true));
}
use of com.birbit.android.jobqueue.test.jobs.DummyJob in project android-priority-jobqueue by yigit.
the class CancelBeforeRunningTest method testCancelBeforeRunning.
@Test
public void testCancelBeforeRunning() {
JobManager jobManager = createJobManager();
jobManager.stop();
DummyJob nonPersistentJob = new DummyJob(new Params(0).addTags("dummyTag"));
DummyJob persistentJob = new DummyJob(new Params(0).addTags("dummyTag").persist());
jobManager.addJob(nonPersistentJob);
jobManager.addJob(persistentJob);
CancelResult result = jobManager.cancelJobs(TagConstraint.ANY, "dummyTag");
assertThat("both jobs should be cancelled", result.getCancelledJobs().size(), is(2));
assertThat("both jobs should be cancelled", result.getFailedToCancel().size(), is(0));
for (Job j : result.getCancelledJobs()) {
DummyJob job = (DummyJob) j;
if (!job.isPersistent()) {
assertThat("job is still added", job.getOnAddedCnt(), is(1));
}
assertThat("job is cancelled", job.getOnCancelCnt(), is(1));
assertThat("job is NOT run", job.getOnRunCnt(), is(0));
}
}
use of com.birbit.android.jobqueue.test.jobs.DummyJob in project android-priority-jobqueue by yigit.
the class CancelWhileRunningTest method testCancelBeforeRunning.
@Test
public void testCancelBeforeRunning() throws InterruptedException {
JobManager jobManager = createJobManager(new Configuration.Builder(RuntimeEnvironment.application).minConsumerCount(5).timer(mockTimer));
JobWithEndLatch nonPersistent1 = new JobWithEndLatch(new Params(0).addTags("dummyTag"), true);
JobWithEndLatch nonPersistent2 = new JobWithEndLatch(new Params(0).addTags("dummyTag"), false);
DummyJob persistentJob1 = new PersistentJobWithEndLatch(new Params(0).addTags("dummyTag"), false);
DummyJob persistentJob2 = new PersistentJobWithEndLatch(new Params(0).addTags("dummyTag"), true);
jobManager.addJob(nonPersistent1);
jobManager.addJob(nonPersistent2);
jobManager.addJob(persistentJob1);
jobManager.addJob(persistentJob2);
onStartLatch.await();
nonPersistent1.onStartLatch.await();
nonPersistent2.onStartLatch.await();
final CancelResult[] resultHolder = new CancelResult[2];
final CountDownLatch cancelLatch = new CountDownLatch(1);
jobManager.cancelJobsInBackground(new CancelResult.AsyncCancelCallback() {
@Override
public void onCancelled(CancelResult cancelResult) {
resultHolder[0] = cancelResult;
cancelLatch.countDown();
}
}, TagConstraint.ANY, "dummyTag");
jobManager.cancelJobsInBackground(new CancelResult.AsyncCancelCallback() {
@Override
public void onCancelled(CancelResult cancelResult) {
resultHolder[1] = cancelResult;
}
}, TagConstraint.ANY, "dummyTag");
assertThat("result should not arrive until existing jobs finish", cancelLatch.await(4, TimeUnit.SECONDS), is(false));
onEndLatch.countDown();
nonPersistent1.onEndLatch.countDown();
nonPersistent2.onEndLatch.countDown();
assertThat("when jobs in question are finished, cancel callback should be triggered", cancelLatch.await(10, TimeUnit.SECONDS), is(true));
final CancelResult result = resultHolder[0];
JqLog.d("cancelled jobs %s", result.getCancelledJobs());
JqLog.d("failed to cancel %s", result.getFailedToCancel());
assertThat("two jobs should be cancelled", result.getCancelledJobs().size(), is(2));
assertThat("two jobs should fail to cancel", result.getFailedToCancel().size(), is(2));
for (Job j : result.getCancelledJobs()) {
FailingJob job = (FailingJob) j;
if (!job.isPersistent()) {
assertThat("job is still added", job.getOnAddedCnt(), is(1));
}
if (job.fail) {
assertThat("job is cancelled", job.getOnCancelCnt(), is(1));
} else {
assertThat("job could not be cancelled", job.getOnCancelCnt(), is(0));
}
}
for (Job j : result.getFailedToCancel()) {
FailingJob job = (FailingJob) j;
if (!job.isPersistent()) {
assertThat("job is still added", job.getOnAddedCnt(), is(1));
}
if (job.fail) {
assertThat("job is cancelled", job.getOnCancelCnt(), is(1));
} else {
assertThat("job could not be cancelled", job.getOnCancelCnt(), is(0));
}
}
assertThat("second cancel should not cancel anything", resultHolder[1].getCancelledJobs().size(), is(0));
assertThat("second cancel should not cancel anything", resultHolder[1].getFailedToCancel().size(), is(0));
}
Aggregations