package com.atlassian.bitbucket.mesh.util;

import org.junit.Test;

import java.time.Duration;

import static com.atlassian.bitbucket.mesh.util.Gate.CLEANUP_THRESHOLD;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;

public class GateTest {

    @Test
    public void testCleanup() throws Exception {
        int expiryMs = 50;
        Runnable runnable = mock(Runnable.class);

        Gate<String> gate = spy(new Gate<>(Duration.ofMillis(expiryMs)));
        for (int i = 0; i < CLEANUP_THRESHOLD; i++) {
            gate.maybeRun("bob" + i, runnable);
        }
        assertEquals(CLEANUP_THRESHOLD, gate.getMapSize());

        Thread.sleep(expiryMs * 2); //Wait for entries to expire

        gate.maybeRun("bob", runnable); //Should trigger a cleanup
        assertEquals(1, gate.getMapSize());
    }

    @Test
    public void testGated() {
        Runnable bob1 = mock(Runnable.class, "bob1");
        Runnable bob2 = mock(Runnable.class, "bob2");
        Runnable sonny = mock(Runnable.class, "sonny");

        Gate<String> gate = new Gate<>(Duration.ofMinutes(1L));
        gate.maybeRun("bob", bob1);
        gate.maybeRun("bob", bob2);
        gate.maybeRun("sonny", sonny);

        verify(bob1).run();
        verify(bob2, never()).run();
        verify(sonny).run();
    }
}