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

import com.google.common.base.Charsets;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import static org.junit.Assert.assertEquals;

@RunWith(MockitoJUnitRunner.class)
public class DelegatingHttpServletResponseTest {

    @Mock
    private HttpServletResponse delegateResponse;

    private ByteArrayOutputStream outputStream;
    private DelegatingHttpServletResponse response;

    @Before
    public void setup() {
        outputStream = new ByteArrayOutputStream();
        response = new DelegatingHttpServletResponse(delegateResponse, outputStream);
    }

    @Test
    public void testSetStatus() {
        response.setStatus(204);
        assertEquals(204, response.getStatus());
    }

    @Test
    public void testSendError() throws IOException {
        response.sendError(503, "Error");
        assertEquals(503, response.getStatus());
    }

    @Test
    public void testSendErrorNoMsg() throws IOException {
        response.sendError(503);
        assertEquals(503, response.getStatus());
    }

    @Test
    public void testSendRedirect() throws IOException {
        response.sendRedirect("http://go/home");
        assertEquals(HttpServletResponse.SC_TEMPORARY_REDIRECT, response.getStatus());
    }

    @Test
    public void testWrite() throws IOException {
        int b = '!';
        byte[] bytes = "This is a test message".getBytes(Charsets.UTF_8);

        ServletOutputStream os = response.getOutputStream();
        os.write(b);
        os.write(bytes);
        os.write(bytes, 4, 3);
        os.flush();
        os.close();
        String result = outputStream.toString("UTF-8");

        assertEquals("!This is a test message is", result);
    }
}
