1   /**
2    * Logback: the generic, reliable, fast and flexible logging framework.
3    * 
4    * Copyright (C) 2000-2008, QOS.ch
5    * 
6    * This library is free software, you can redistribute it and/or modify it under
7    * the terms of the GNU Lesser General Public License as published by the Free
8    * Software Foundation.
9    */
10  
11  package ch.qos.logback.core.rolling;
12  
13  import static org.junit.Assert.assertTrue;
14  
15  import java.io.File;
16  import java.text.SimpleDateFormat;
17  import java.util.Calendar;
18  
19  import org.junit.Before;
20  import org.junit.Test;
21  
22  import ch.qos.logback.core.Context;
23  import ch.qos.logback.core.ContextBase;
24  import ch.qos.logback.core.Layout;
25  import ch.qos.logback.core.layout.EchoLayout;
26  import ch.qos.logback.core.util.Compare;
27  import ch.qos.logback.core.util.Constants;
28  
29  /**
30   * 
31   * This test case aims to unit test/reproduce problems encountered while
32   * renaming the log file under windows.
33   * 
34   * @author Ceki
35   * 
36   */
37  public class RenamingTest {
38  
39    Layout<Object> layout;
40    Context context = new ContextBase();
41  
42    @Before
43    public void setUp() throws Exception {
44      layout = new EchoLayout<Object>();
45  
46      File target = new File(Constants.OUTPUT_DIR_PREFIX + "test.log");
47      target.mkdirs();
48      target.delete();
49    }
50  
51    @Test
52    public void testRename() throws Exception {
53  
54      RollingFileAppender<Object> rfa = new RollingFileAppender<Object>();
55      rfa.setLayout(layout);
56      rfa.setContext(context);
57      rfa.setFile(Constants.OUTPUT_DIR_PREFIX + "test.log");
58  
59      // rollover by the second
60      String datePattern = "yyyy-MM-dd_HH_mm_ss";
61      SimpleDateFormat sdf = new SimpleDateFormat(datePattern);
62      String[] filenames = new String[2];
63  
64      TimeBasedRollingPolicy tbrp = new TimeBasedRollingPolicy();
65      tbrp.setFileNamePattern(Constants.OUTPUT_DIR_PREFIX + "test-%d{"
66          + datePattern + "}");
67      // tbrp.setActiveFileName("src/test/output/test.log");
68      tbrp.setContext(context);
69      tbrp.setParent(rfa);
70      tbrp.start();
71  
72      rfa.setRollingPolicy(tbrp);
73      rfa.start();
74  
75      // StatusPrinter.print(context.getStatusManager());
76      Calendar cal = Calendar.getInstance();
77  
78      rfa.doAppend("Hello 0");
79      DelayerUtil.delayUntilNextSecond(50);
80      rfa.doAppend("Hello 1");
81  
82      filenames[0] = Constants.OUTPUT_DIR_PREFIX + "test-"
83          + sdf.format(cal.getTime());
84      filenames[1] = Constants.OUTPUT_DIR_PREFIX + "test.log";
85  
86      for (int i = 0; i < filenames.length; i++) {
87        // System.out.println("before i=" + i);
88        assertTrue(Compare.compare(filenames[i], Constants.TEST_DIR_PREFIX
89            + "witness/rolling/renaming." + i));
90        // System.out.println("post i=" + i);
91      }
92    }
93  }