1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16  */
17  package org.apache.rat.anttasks;
18  
19  import java.io.File;
20  import java.io.FileReader;
21  import java.io.IOException;
22  import java.util.regex.Pattern;
23  
24  import junit.framework.Assert;
25  
26  import org.apache.tools.ant.BuildFileTest;
27  import org.apache.tools.ant.util.FileUtils;
28  
29  public abstract class AbstractRatAntTaskTest extends BuildFileTest {
30  	private static final File tempDir = new File("target/anttasks");
31  
32  	protected abstract File getAntFile();
33  
34  	protected File getTempDir() {
35  		return tempDir;
36  	}
37  
38  	public void setUp() {
39  		configureProject(getAntFile().getPath());
40  	}
41  
42  	protected void assertLogDoesntMatch(String pPattern) {
43  		final String log = super.getLog();
44  		Assert.assertFalse("Log matches the pattern: " + pPattern + ", got " + log,
45  				isMatching(pPattern, log));
46  	}
47  
48  	protected void assertLogMatches(String pPattern) {
49  		final String log = super.getLog();
50  		Assert.assertTrue("Log doesn' match string: " + pPattern + ", got " + log,
51  				isMatching(pPattern, log));
52  	}
53  
54  	private boolean isMatching(final String pPattern, final String pValue) {
55  		return Pattern.compile(pPattern).matcher(pValue).find();
56  	}
57  
58  	private String load(File pFile) throws IOException {
59  		FileReader fr = new FileReader(pFile);
60  		try {
61  			final StringBuffer sb = new StringBuffer();
62  			char[] buffer = new char[1024];
63  			for (;;) {
64  				int res = fr.read(buffer);
65  				if (res == -1) {
66  					fr.close();
67  					fr = null;
68  					return sb.toString();
69  				}
70  				if (res > 0) {
71  					sb.append(buffer, 0, res);
72  				}
73  			}
74  		} finally {
75  			FileUtils.close(fr);
76  		}
77  	}
78  
79  	protected void assertFileMatches(File pFile, String pPattern)
80  			throws IOException {
81  		final String content = load(pFile);
82  		Assert.assertTrue("File " + pFile
83  				+ " doesn't match the pattern " + pPattern
84  				+ ", got " + content,
85  				isMatching(pPattern, content));
86  	}
87  }