001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.recovery;
015
016import static org.junit.Assert.*;
017
018import org.junit.Test;
019
020public class RecoveryCoordinatorTest {
021
022    long now = System.currentTimeMillis();
023    RecoveryCoordinator rc = new RecoveryCoordinator(now);
024
025    @Test
026    public void recoveryNotNeededAfterInit() {
027        RecoveryCoordinator rc = new RecoveryCoordinator();
028        assertTrue(rc.isTooSoon());
029    }
030
031    @Test
032    public void recoveryNotNeededIfAsleepForLessThanBackOffTime() throws InterruptedException {
033        rc.setCurrentTime(now + RecoveryCoordinator.BACKOFF_COEFFICIENT_MIN / 2);
034        assertTrue(rc.isTooSoon());
035    }
036
037    @Test
038    public void recoveryNeededIfAsleepForMoreThanBackOffTime() throws InterruptedException {
039        rc.setCurrentTime(now + RecoveryCoordinator.BACKOFF_COEFFICIENT_MIN + 20);
040        assertFalse(rc.isTooSoon());
041    }
042
043    @Test
044    public void recoveryNotNeededIfCurrentTimeSetToBackOffTime() throws InterruptedException {
045        rc.setCurrentTime(now + RecoveryCoordinator.BACKOFF_COEFFICIENT_MIN);
046        assertTrue(rc.isTooSoon());
047    }
048
049    @Test
050    public void recoveryNeededIfCurrentTimeSetToExceedBackOffTime() {
051        rc.setCurrentTime(now + RecoveryCoordinator.BACKOFF_COEFFICIENT_MIN + 1);
052        assertFalse(rc.isTooSoon());
053    }
054
055    @Test
056    public void recoveryConditionDetectedEvenAfterReallyLongTimesBetweenRecovery() {
057        // Since backoff time quadruples whenever recovery is needed,
058        // we double the offset on each for-loop iteration, causing
059        // every other iteration to trigger recovery.
060
061        long offset = RecoveryCoordinator.BACKOFF_COEFFICIENT_MIN;
062
063        for (int i = 0; i < 16; i++) {
064            rc.setCurrentTime(now + offset);
065
066            if (i % 2 == 0) {
067                assertTrue("recovery should've been needed at " + offset, rc.isTooSoon());
068            } else {
069                assertFalse("recovery should NOT have been needed at " + offset, rc.isTooSoon());
070            }
071            offset *= 2;
072        }
073    }
074}