package com.atlassian.stash.internal.user;

import com.atlassian.bitbucket.permission.Permission;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.*;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class CompositePermissionGraphTest {

    @Mock
    private PermissionGraph graph1;
    @Mock
    private PermissionGraph graph2;

    @Test
    public void testMaybeComposeNull() {
        assertEquals(graph1, CompositePermissionGraph.maybeCompose(graph1, null));
        assertEquals(graph1, CompositePermissionGraph.maybeCompose(null, graph1));

        PermissionGraph graph = CompositePermissionGraph.maybeCompose(null, null);
        assertNotNull(graph);

        // the returned graph should always return false - even for illegal inputs
        assertFalse(graph.isGranted(null, null));
    }

    @Test
    public void testMaybeCompose() {
        PermissionGraph composed = CompositePermissionGraph.maybeCompose(graph1, graph2);
        when(graph1.isGranted(eq(Permission.ADMIN), isNull())).thenReturn(true);
        when(graph2.isGranted(eq(Permission.LICENSED_USER), isNull())).thenReturn(true);

        assertTrue(composed.isGranted(Permission.ADMIN, null));
        assertTrue(composed.isGranted(Permission.LICENSED_USER, null));
        assertFalse(composed.isGranted(Permission.SYS_ADMIN, null));
    }

    @Test
    public void testIsGrantedByGraph1() {
        Object resource = new Object();
        when(graph1.isGranted(Permission.REPO_READ, resource)).thenReturn(true);

        CompositePermissionGraph graph = new CompositePermissionGraph(graph1, graph2);
        assertTrue(graph.isGranted(Permission.REPO_READ, resource));
        assertFalse(graph.isGranted(Permission.REPO_ADMIN, resource));
    }

    @Test
    public void testIsGrantedByGraph2() {
        Object resource = new Object();
        when(graph2.isGranted(Permission.REPO_READ, resource)).thenReturn(true);

        CompositePermissionGraph graph = new CompositePermissionGraph(graph1, graph2);
        assertTrue(graph.isGranted(Permission.REPO_READ, resource));
        assertFalse(graph.isGranted(Permission.REPO_ADMIN, resource));
    }
}
