static IntervalFunction ofRandomized(long interval) { return ofRandomized(interval, DEFAULT_RANDOMIZATION_FACTOR); }
static IntervalFunction ofRandomized() { return ofRandomized(DEFAULT_INITIAL_INTERVAL, DEFAULT_RANDOMIZATION_FACTOR); }
static IntervalFunction ofRandomized(Duration interval) { return ofRandomized(interval.toMillis(), DEFAULT_RANDOMIZATION_FACTOR); }
static IntervalFunction ofRandomized(Duration interval, double randomizationFactor) { return ofRandomized(interval.toMillis(), randomizationFactor); }
@Test public void shouldRejectOutOfBoundsRandomizationFactor() { // Given final Duration duration = Duration.ofMillis(100); final float negativeFactor = -0.0001f; final float greaterThanOneFactor = 1.0001f; // When final List<Try> tries = List.of( Try.of(() -> IntervalFunction.ofRandomized(duration, negativeFactor)), Try.of(() -> IntervalFunction.ofRandomized(duration, greaterThanOneFactor)) ); // Then Assertions.assertThat(tries.forAll(Try::isFailure)).isTrue(); Assertions.assertThat(tries.map(Try::getCause).forAll(t -> t instanceof IllegalArgumentException)).isTrue(); }
@Test public void generatesRandomizedIntervals() { final IntervalFunction f = IntervalFunction.ofRandomized(100, 0.5); for (int i = 1; i < 50; i++) { //When final long delay = f.apply(i); // Then Assertions.assertThat(delay).isGreaterThanOrEqualTo(50).isLessThanOrEqualTo(150); } }
@Test public void shouldPassPositiveRandomizationFactor() { // Given final Duration duration = Duration.ofMillis(100); final float multiplier = 1.5f; final List<Float> correctFactors = List.of(0.0f, 0.25f, 0.5f, 0.75f, 0.1f); // When correctFactors.forEach(v -> IntervalFunction.ofRandomized(duration, v)); correctFactors.forEach(v -> IntervalFunction.ofExponentialRandomBackoff(duration, multiplier, v)); }
@Test public void shouldRejectAttemptLessThenOne() { // Given final List<IntervalFunction> fns = List.of( IntervalFunction.ofDefaults(), IntervalFunction.ofRandomized(), IntervalFunction.ofExponentialBackoff(), IntervalFunction.ofExponentialRandomBackoff() ); // When final List<Try> tries = fns.map(fn -> Try.of(() -> fn.apply(0))); // Then Assertions.assertThat(tries.forAll(Try::isFailure)).isTrue(); Assertions.assertThat(tries.map(Try::getCause).forAll(t -> t instanceof IllegalArgumentException)).isTrue(); }
@Test public void shouldPassAttemptGreaterThenZero() { // Given final List<IntervalFunction> fns = List.of( IntervalFunction.ofDefaults(), IntervalFunction.ofRandomized(), IntervalFunction.ofExponentialBackoff(), IntervalFunction.ofExponentialRandomBackoff() ); // When final List<Try> tries1 = fns.map(fn -> Try.of(() -> fn.apply(1))); final List<Try> tries2 = fns.map(fn -> Try.of(() -> fn.apply(2))); // Then Assertions.assertThat(tries1.forAll(Try::isFailure)).isFalse(); Assertions.assertThat(tries2.forAll(Try::isFailure)).isFalse(); }