// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.omaha;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
import org.chromium.base.FakeTimeTestRule;
import org.chromium.base.test.BaseRobolectricTestRunner;
import org.chromium.base.test.util.Batch;
import org.chromium.base.test.util.Feature;
/** Tests the ExponentialBackoffScheduler. */
@RunWith(BaseRobolectricTestRunner.class)
@Batch(Batch.UNIT_TESTS)
@Config(manifest = Config.NONE)
public class ExponentialBackoffSchedulerTest {
private static final String PREFERENCE_NAME = "scheduler";
private static final long BACKOFF_MS = 15000;
private static final long MAX_MS = 1000000;
@Rule public FakeTimeTestRule mFakeTimeRule = new FakeTimeTestRule();
/** Checks that the correct number of failures are set/reset. */
@Test
@Feature({"Omaha", "Sync"})
public void testExponentialBackoffSchedulerFailureSetting() {
ExponentialBackoffScheduler writer =
new ExponentialBackoffScheduler(PREFERENCE_NAME, BACKOFF_MS, MAX_MS);
ExponentialBackoffScheduler reader =
new ExponentialBackoffScheduler(PREFERENCE_NAME, BACKOFF_MS, MAX_MS);
Assert.assertEquals(
"Expected no failures for freshly created class", 0, reader.getNumFailedAttempts());
writer.increaseFailedAttempts();
writer.increaseFailedAttempts();
Assert.assertEquals(
"Expected 2 failures after 2 increments.", 2, reader.getNumFailedAttempts());
writer.resetFailedAttempts();
Assert.assertEquals("Expected 0 failures after reset.", 0, reader.getNumFailedAttempts());
}
/** Check that the delay generated by the scheduler is within the correct range. */
@Test
@Feature({"Omaha", "Sync"})
public void testExponentialBackoffSchedulerDelayCalculation() {
ExponentialBackoffScheduler scheduler =
new ExponentialBackoffScheduler(PREFERENCE_NAME, BACKOFF_MS, MAX_MS);
// With no failures, expect the base backoff delay.
long delay = scheduler.calculateNextTimestamp() - scheduler.getCurrentTime();
Assert.assertEquals(
"Expected delay of " + BACKOFF_MS + " milliseconds.", BACKOFF_MS, delay);
// With two failures, expect a delay within [BACKOFF_MS, BACKOFF_MS * 2^2].
scheduler.increaseFailedAttempts();
scheduler.increaseFailedAttempts();
delay = scheduler.calculateNextTimestamp() - scheduler.getCurrentTime();
final long minDelay = BACKOFF_MS;
final long maxDelay = BACKOFF_MS * (1 << scheduler.getNumFailedAttempts());
Assert.assertTrue("Expected delay greater than the minimum.", delay >= minDelay);
Assert.assertTrue("Expected delay within maximum of " + maxDelay, delay <= maxDelay);
}
}