package com.atlassian.bitbucket.scm.cache.git;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

import static org.junit.Assert.*;

public class UploadPackCacheKeyBuilderTest {

    @Test
    public void testCacheKeyClone() throws IOException {
        PackRequest expectedRequest = createCloneRequest();
        String expectedKey = expectedRequest.buildCacheKey();

        InputStream is = getClass().getResourceAsStream("/git/clone.request");
        String actualKey = GitUtils.getCacheKeyForUploadPackRequest(is);

        assertNotNull(actualKey);
        assertEquals(expectedKey, actualKey);
    }

    @Test
    public void testCacheKeyCloneDifferentOrder() throws IOException {
        String key1 = GitUtils.getCacheKeyForUploadPackRequest(getClass().getResourceAsStream("/git/clone.request"));
        String key2 = GitUtils.getCacheKeyForUploadPackRequest(getClass().getResourceAsStream("/git/clone-reordered.request"));

        assertEquals(key1, key2);
    }

    @Test
    public void testCacheKeyEmptyIsNull() {
        assertNull(new PackRequest().buildCacheKey());
    }

    @Test
    public void testCacheKeyFetch() throws IOException {
        String key = GitUtils.getCacheKeyForUploadPackRequest(getClass().getResourceAsStream("/git/fetch.request"));

        assertNull(key);
    }

    @Test
    public void testCacheKeyShallowClone() throws IOException {
        // shallow clones over HTTP trigger two upload-pack requests, one without a 'done' packet, one with a 'done' packet
        String key1 = GitUtils.getCacheKeyForUploadPackRequest(getClass().getResourceAsStream("/git/shallow-clone-1.request"));
        String key2 = GitUtils.getCacheKeyForUploadPackRequest(getClass().getResourceAsStream("/git/shallow-clone-2.request"));

        assertNotNull(key1);
        assertNotNull(key2);
        assertFalse(key1.equals(key2));
    }

    private PackRequest createCloneRequest() throws IOException {
        PackRequest request = new PackRequest();
        try (InputStream input = getClass().getResourceAsStream("/git/clone.request")) {
            byte[] packet;
            while ((packet = GitUtils.readPacket(input)) != null) {
                request.packet(packet);
            }
        }

        return request;
    }

}
