package tv.ustream.yolo.handler;

import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.File;
import java.io.FileWriter;

/**
 * @author bandesz
 */
public class FileHandlerTest implements ILineHandler
{

    @Rule
    public TemporaryFolder tmpFolder = new TemporaryFolder();

    private FileHandler handler;

    private File testFile;

    private String handledLines;

    @Before
    public void setUp() throws Exception
    {
        handledLines = "";
        testFile = tmpFolder.newFile();
        FileWriter out = new FileWriter(testFile);
        out.write("l1\nl2\nl3\n");
        out.close();
    }

    @After
    public void tearDown()
    {
        handler.stop();
    }

    @Test
    public void shouldTailFile() throws Exception
    {
        handler = new FileHandler(this, testFile.getAbsolutePath(), 100, false, false);
        handler.start();

        Thread.sleep(100);

        FileWriter out = new FileWriter(testFile, true);
        out.write("l4\nl5\n");
        out.close();

        Thread.sleep(200);

        Assert.assertEquals("l4\nl5\n", handledLines);
    }

    @Test
    public void shouldTailFileFromTheBeginning() throws Exception
    {
        handler = new FileHandler(this, testFile.getAbsolutePath(), 100, true, false);
        handler.start();

        Thread.sleep(100);

        FileWriter out = new FileWriter(testFile, true);
        out.write("l4\nl5\n");
        out.close();

        Thread.sleep(200);

        Assert.assertEquals("l1\nl2\nl3\nl4\nl5\n", handledLines);
    }

    @Test
    public void shouldHandleRotate() throws Exception
    {
        handler = new FileHandler(this, testFile.getAbsolutePath(), 100, true, false);
        handler.start();

        Thread.sleep(100);

        FileWriter out = new FileWriter(testFile, true);
        out.write("l4\nl5\n");
        out.close();

        Thread.sleep(100);

        testFile.delete();

        Thread.sleep(100);

        out = new FileWriter(testFile, true);
        out.write("l6\nl7\n");
        out.close();

        Thread.sleep(1000);

        Assert.assertEquals("l1\nl2\nl3\nl4\nl5\nl6\nl7\n", handledLines);
    }

    @Override
    public void handle(String line)
    {
        handledLines += line + "\n";
    }

}

@@ -1849,33 +1849,33 @@
    Thread.sleep(
-1
+2
 00);%0A%0A        Fi
@@ -1876,104 +1876,22 @@
     
-FileWriter out = new FileWriter(testFile, true);%0A        out.write(%22l4%5Cnl5%5Cn%22);%0A        out.clos
+testFile.delet
 e();
@@ -1905,33 +1905,33 @@
    Thread.sleep(
-1
+2
 00);%0A%0A        te
@@ -1932,63 +1932,18 @@
     
-testFile.delete();%0A%0A        Thread.sleep(100);%0A%0A       
+FileWriter
  out
@@ -1997,21 +1997,21 @@
 write(%22l
-6%5Cnl7
+4%5Cnl5
 %5Cn%22);%0A  
@@ -2111,16 +2111,8 @@
 nl5%5C
-nl6%5Cnl7%5C
 n%22, 

Change FileHandler rotate testing (timing problems)