package com.avg.zaap.crashlibrary.publish.packer;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.io.File;
import java.io.IOException;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import static org.powermock.api.mockito.PowerMockito.when;

/**
 * Small tests for inner class {@link com.avg.zaap.crashlibrary.publish.packer.BinPacker.FileWalker}
 * <p>
 * Created by marek.osvald on 18.4.2016.
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest({BinPacker.FileWalker.class})
public class FileWalkerTests {

    private File mRootFile;
    private File mInnerFile;
    private BinPacker.FileWalker.IFileWalkerAction mAction;

    @Before
    public void setUp() throws Exception {
        mRootFile = mock(File.class);
        mInnerFile = mock(File.class);
        mAction = mock(BinPacker.FileWalker.IFileWalkerAction.class);
    }

    @Test
    public void walk_file_correctBehaviour() throws IOException, IBinPacker.BinPackerException {
        // prepare
        when(mRootFile.isFile()).thenReturn(true);
        when(mRootFile.isDirectory()).thenReturn(false);

        // test
        BinPacker.FileWalker.walk(mRootFile, mAction);

        // verify
        verify(mAction, times(1)).actFile(mRootFile);
        verify(mAction, never()).actFolder(mRootFile);
    }

    @Test
    public void walk_directory_correctBehaviour() throws IOException, IBinPacker.BinPackerException {
        // prepare
        when(mRootFile.isFile()).thenReturn(false);
        when(mRootFile.isDirectory()).thenReturn(true);
        when(mRootFile.listFiles()).thenReturn(new File[0]);

        // test
        BinPacker.FileWalker.walk(mRootFile, mAction);

        // verify
        verify(mAction, times(1)).actFolder(mRootFile);
        verify(mAction, never()).actFile(mRootFile);
    }

    @Test
    public void walk_directoryRecursive_correctBehaviour() throws IOException, IBinPacker.BinPackerException {
        // prepare
        when(mRootFile.isFile()).thenReturn(false);
        when(mRootFile.isDirectory()).thenReturn(true);
        when(mInnerFile.isFile()).thenReturn(true);
        when(mInnerFile.isDirectory()).thenReturn(false);
        when(mRootFile.listFiles()).thenReturn(new File[]{mInnerFile});

        // test
        BinPacker.FileWalker.walk(mRootFile, mAction);

        // verify
        verify(mAction, times(1)).actFolder(mRootFile);
        verify(mAction, never()).actFile(mRootFile);
        // second call
        verify(mAction, times(1)).actFile(mInnerFile);
        verify(mAction, never()).actFolder(mInnerFile);
    }
}