package com.atlassian.bitbucket.internal.scm.git.lfs.mirror;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;

@RunWith(MockitoJUnitRunner.class)
public class DigestValidatingInputStreamTest {

    private static final String REQUIRED_CHECKSUM = "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae";

    @Rule
    public TemporaryFolder temporaryFolder = new TemporaryFolder();
    private File file;

    @Mock
    private OutputStream outputStream;

    @Before
    public void setUp() throws Exception {
        file = temporaryFolder.newFile();
    }

    @Test
    public void badChecksum() throws IOException {
        DigestValidatingInputStream underTest =
                new DigestValidatingInputStream(new ByteArrayInputStream("foobar".getBytes()), REQUIRED_CHECKSUM,
                        file);

        assertThat(file.exists(), is(true));
        underTest.read(new byte[8]);
        underTest.read();
        assertThat(file.exists(), is(false));
    }

    @Test
    public void goodChecksum() throws IOException {
        DigestValidatingInputStream underTest =
                new DigestValidatingInputStream(new ByteArrayInputStream("foo".getBytes()), REQUIRED_CHECKSUM,
                        file);

        assertThat(file.exists(), is(true));
        underTest.read(new byte[8]);
        underTest.read();
        assertThat(file.exists(), is(true));
    }
}