1   package org.apache.velocity.test;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.    
20   */
21  
22  import java.io.File;
23  import java.io.IOException;
24  
25  import junit.framework.TestCase;
26  
27  import org.apache.oro.text.perl.Perl5Util;
28  import org.apache.velocity.runtime.RuntimeSingleton;
29  import org.apache.velocity.util.StringUtils;
30  
31  /**
32   * Base test case that provides a few utility methods for
33   * the rest of the tests.
34   *
35   * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
36   * @version $Id: BaseTestCase.java 490718 2006-12-28 13:35:49Z wglass $
37   */
38  public abstract class BaseTestCase
39          extends TestCase
40          implements TemplateTestBase
41  {
42      /**
43       *  used for nomalization of output and compare data
44       */
45      private Perl5Util perl = new Perl5Util();
46  
47      /**
48       * Default constructor.
49       */
50      public BaseTestCase(String name)
51      {
52          super(name);
53      }
54  
55      /**
56       * Concatenates the file name parts together appropriately.
57       *
58       * @return The full path to the file.
59       */
60      protected static String getFileName (final String dir, final String base, final String ext)
61      {
62          return getFileName(dir, base, ext, false);
63      }
64  
65      protected static String getFileName (final String dir, final String base, final String ext, final boolean mustExist)
66      {
67          StringBuffer buf = new StringBuffer();
68  
69          try
70          {
71              File baseFile = new File(base);
72  
73              if (dir != null)
74              {
75                  if (!baseFile.isAbsolute())
76                  {
77                      baseFile = new File(dir, base);
78                  }
79  
80                  buf.append(baseFile.getCanonicalPath());
81              }
82              else
83              {
84                  buf.append(baseFile.getPath());
85              }
86  
87              if (org.apache.commons.lang.StringUtils.isNotEmpty(ext))
88              {
89                  buf.append('.').append(ext);
90              }
91  
92              if (mustExist)
93              {
94                  File testFile = new File(buf.toString());
95  
96                  if (!testFile.exists())
97                  {
98                      fail("getFileName() result " + testFile.getPath() + " does not exist!");
99                  }
100 
101                 if (!testFile.isFile())
102                 {
103                     fail("getFileName() result " + testFile.getPath() + " is not a file!");
104                 }
105             }
106         }
107         catch (IOException e)
108         {
109             fail("IO Exception while running getFileName(" + dir + ", " + base + ", "+ ext + ", " + mustExist + "): " + e.getMessage());
110         }
111 
112         return buf.toString();
113     }
114 
115     /**
116      * Assures that the results directory exists.  If the results directory
117      * cannot be created, fails the test.
118      */
119     protected static void assureResultsDirectoryExists (String resultsDirectory)
120     {
121         File dir = new File(resultsDirectory);
122         if (!dir.exists())
123         {
124             RuntimeSingleton.getLog().info("Template results directory does not exist");
125             if (dir.mkdirs())
126             {
127                 RuntimeSingleton.getLog().info("Created template results directory");
128             }
129             else
130             {
131                 String errMsg = "Unable to create template results directory";
132                 RuntimeSingleton.getLog().warn(errMsg);
133                 fail(errMsg);
134             }
135         }
136     }
137 
138 
139     /**
140      * Normalizes lines to account for platform differences.  Macs use
141      * a single \r, DOS derived operating systems use \r\n, and Unix
142      * uses \n.  Replace each with a single \n.
143      *
144      * @author <a href="mailto:rubys@us.ibm.com">Sam Ruby</a>
145      * @return source with all line terminations changed to Unix style
146      */
147     protected String normalizeNewlines (String source)
148     {
149         return perl.substitute("s/\r[\r]?[\n]/\n/g", source);
150     }
151 
152     /**
153      * Returns whether the processed template matches the
154      * content of the provided comparison file.
155      *
156      * @return Whether the output matches the contents
157      *         of the comparison file.
158      *
159      * @exception Exception Test failure condition.
160      */
161     protected boolean isMatch (String resultsDir,
162                                String compareDir,
163                                String baseFileName,
164                                String resultExt,
165                                String compareExt)
166         throws Exception
167     {
168         String result = StringUtils.fileContentsToString
169                 (getFileName(resultsDir, baseFileName, resultExt, true));
170 
171         return isMatch(result,compareDir,baseFileName,compareExt);
172     }
173 
174     
175     /**
176      * Returns whether the processed template matches the
177      * content of the provided comparison file.
178      *
179      * @return Whether the output matches the contents
180      *         of the comparison file.
181      *
182      * @exception Exception Test failure condition.
183      */
184     protected boolean isMatch (
185                                String result,
186                                String compareDir,
187                                String baseFileName,
188                                String compareExt)
189         throws Exception
190     {
191         String compare = StringUtils.fileContentsToString
192                 (getFileName(compareDir, baseFileName, compareExt, true));
193 
194         /*
195          *  normalize each wrt newline
196          */
197 
198         return normalizeNewlines(result).equals(
199                            normalizeNewlines( compare ) );
200     }
201 
202         /**
203      * Turns a base file name into a test case name.
204      *
205      * @param s The base file name.
206      * @return  The test case name.
207      */
208     protected  static final String getTestCaseName (String s)
209     {
210         StringBuffer name = new StringBuffer();
211         name.append(Character.toTitleCase(s.charAt(0)));
212         name.append(s.substring(1, s.length()).toLowerCase());
213         return name.toString();
214     }
215 }