/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.sdm.infrastructure;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

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

import org.junit.Before;
import org.junit.Test;

/**
 * Tests of {@link CompositeInputStream}.
 */
public class CompositeInputStreamTest {
    private InputStream part1;

    private InputStream part2;

    private InputStream part3;

    private CompositeInputStream stream;

    @Before
    public void setUp() throws IOException {
        part1 = mock(InputStream.class);
        when(part1.read()).thenReturn(1, -1);
        part2 = mock(InputStream.class);
        when(part2.read()).thenReturn(2, -1);
        part3 = mock(InputStream.class);
        when(part3.read()).thenReturn(3, -1);
        stream = new CompositeInputStream(part1, part2, part3);
    }

    @Test
    public void testRead() throws IOException {
        assertEquals(1, stream.read());
        assertEquals(2, stream.read());
        assertEquals(3, stream.read());
        assertEquals(-1, stream.read());
    }

    @Test(expected = IOException.class)
    public void testReadIOException() throws IOException {
        when(part2.read()).thenThrow(new IOException("test"));
        stream.read();
        stream.read();
    }

    @Test
    public void testClose() throws IOException {
        stream.close();
        verify(part1).close();
        verify(part2).close();
        verify(part3).close();
    }

    @Test(expected = IOException.class)
    public void testCloseIOException() throws IOException {
        doThrow(new IOException("test")).when(part2).close();
        try {
            stream.close();
        } catch (IOException e) {
            verify(part1).close();
            verify(part3).close();
            throw e;
        }
    }
}
