View Javadoc
1   /*
2    * Copyright (C) 2008-2009, Google Inc.
3    * Copyright (C) 2008, Imran M Yousuf <imyousuf@smartitengineering.com>
4    * Copyright (C) 2008, Jonas Fonseca <fonseca@diku.dk>
5    * and other copyright owners as documented in the project's IP log.
6    *
7    * This program and the accompanying materials are made available
8    * under the terms of the Eclipse Distribution License v1.0 which
9    * accompanies this distribution, is reproduced below, and is
10   * available at http://www.eclipse.org/org/documents/edl-v10.php
11   *
12   * All rights reserved.
13   *
14   * Redistribution and use in source and binary forms, with or
15   * without modification, are permitted provided that the following
16   * conditions are met:
17   *
18   * - Redistributions of source code must retain the above copyright
19   *   notice, this list of conditions and the following disclaimer.
20   *
21   * - Redistributions in binary form must reproduce the above
22   *   copyright notice, this list of conditions and the following
23   *   disclaimer in the documentation and/or other materials provided
24   *   with the distribution.
25   *
26   * - Neither the name of the Eclipse Foundation, Inc. nor the
27   *   names of its contributors may be used to endorse or promote
28   *   products derived from this software without specific prior
29   *   written permission.
30   *
31   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
32   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
33   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
36   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
37   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
39   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
40   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
41   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
42   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
43   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44   */
45  
46  package org.eclipse.jgit.junit;
47  
48  import java.io.File;
49  import java.io.FileNotFoundException;
50  import java.io.FileOutputStream;
51  import java.io.IOException;
52  import java.io.InputStream;
53  import java.io.OutputStreamWriter;
54  import java.io.Writer;
55  import java.lang.reflect.Method;
56  import java.net.URISyntaxException;
57  import java.net.URL;
58  
59  import org.eclipse.jgit.lib.Repository;
60  import org.eclipse.jgit.util.FileUtils;
61  import org.eclipse.jgit.util.IO;
62  import org.eclipse.jgit.util.RawParseUtils;
63  import org.junit.Assert;
64  import org.junit.Test;
65  
66  public abstract class JGitTestUtil {
67  	public static final String CLASSPATH_TO_RESOURCES = "org/eclipse/jgit/test/resources/";
68  
69  	private JGitTestUtil() {
70  		throw new UnsupportedOperationException();
71  	}
72  
73  	public static String getName() {
74  		GatherStackTrace stack;
75  		try {
76  			throw new GatherStackTrace();
77  		} catch (GatherStackTrace wanted) {
78  			stack = wanted;
79  		}
80  
81  		try {
82  			for (StackTraceElement stackTrace : stack.getStackTrace()) {
83  				String className = stackTrace.getClassName();
84  				String methodName = stackTrace.getMethodName();
85  				Method method;
86  				try {
87  					method = Class.forName(className) //
88  							.getMethod(methodName, (Class[]) null);
89  				} catch (NoSuchMethodException e) {
90  					// could be private, i.e. not a test method
91  					// could have arguments, not handled
92  					continue;
93  				}
94  
95  				Test annotation = method.getAnnotation(Test.class);
96  				if (annotation != null)
97  					return methodName;
98  			}
99  		} catch (ClassNotFoundException shouldNeverOccur) {
100 			// Fall through and crash.
101 		}
102 
103 		throw new AssertionError("Cannot determine name of current test");
104 	}
105 
106 	@SuppressWarnings("serial")
107 	private static class GatherStackTrace extends Exception {
108 		// Thrown above to collect the stack frame.
109 	}
110 
111 	public static void assertEquals(byte[] exp, byte[] act) {
112 		Assert.assertEquals(s(exp), s(act));
113 	}
114 
115 	private static String s(byte[] raw) {
116 		return RawParseUtils.decode(raw);
117 	}
118 
119 	public static File getTestResourceFile(final String fileName) {
120 		if (fileName == null || fileName.length() <= 0) {
121 			return null;
122 		}
123 		final URL url = cl().getResource(CLASSPATH_TO_RESOURCES + fileName);
124 		if (url == null) {
125 			// If URL is null then try to load it as it was being
126 			// loaded previously
127 			return new File("tst", fileName);
128 		}
129 		if ("jar".equals(url.getProtocol())) {
130 			try {
131 				File tmp = File.createTempFile("tmp_", "_" + fileName);
132 				copyTestResource(fileName, tmp);
133 				return tmp;
134 			} catch (IOException err) {
135 				throw new RuntimeException("Cannot create temporary file", err);
136 			}
137 		}
138 		try {
139 			return new File(url.toURI());
140 		} catch (IllegalArgumentException e) {
141 			throw new IllegalArgumentException(e.getMessage() + " " + url);
142 		} catch (URISyntaxException e) {
143 			return new File(url.getPath());
144 		}
145 	}
146 
147 	public static void copyTestResource(String name, File dest)
148 			throws IOException {
149 		URL url = cl().getResource(CLASSPATH_TO_RESOURCES + name);
150 		if (url == null)
151 			throw new FileNotFoundException(name);
152 		InputStream in = url.openStream();
153 		try {
154 			FileOutputStream out = new FileOutputStream(dest);
155 			try {
156 				byte[] buf = new byte[4096];
157 				for (int n; (n = in.read(buf)) > 0;)
158 					out.write(buf, 0, n);
159 			} finally {
160 				out.close();
161 			}
162 		} finally {
163 			in.close();
164 		}
165 	}
166 
167 	private static ClassLoader cl() {
168 		return JGitTestUtil.class.getClassLoader();
169 	}
170 
171 	public static File writeTrashFile(final Repository db,
172 			final String name, final String data) throws IOException {
173 		File path = new File(db.getWorkTree(), name);
174 		write(path, data);
175 		return path;
176 	}
177 
178 	public static File writeTrashFile(final Repository db,
179 			final String subdir,
180 			final String name, final String data) throws IOException {
181 		File path = new File(db.getWorkTree() + "/" + subdir, name);
182 		write(path, data);
183 		return path;
184 	}
185 
186 	/**
187 	 * Write a string as a UTF-8 file.
188 	 *
189 	 * @param f
190 	 *            file to write the string to. Caller is responsible for making
191 	 *            sure it is in the trash directory or will otherwise be cleaned
192 	 *            up at the end of the test. If the parent directory does not
193 	 *            exist, the missing parent directories are automatically
194 	 *            created.
195 	 * @param body
196 	 *            content to write to the file.
197 	 * @throws IOException
198 	 *             the file could not be written.
199 	 */
200 	public static void write(final File f, final String body)
201 			throws IOException {
202 		FileUtils.mkdirs(f.getParentFile(), true);
203 		Writer w = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
204 		try {
205 			w.write(body);
206 		} finally {
207 			w.close();
208 		}
209 	}
210 
211 	/**
212 	 * Fully read a UTF-8 file and return as a string.
213 	 *
214 	 * @param file
215 	 *            file to read the content of.
216 	 * @return UTF-8 decoded content of the file, empty string if the file
217 	 *         exists but has no content.
218 	 * @throws IOException
219 	 *             the file does not exist, or could not be read.
220 	 */
221 	public static String read(final File file) throws IOException {
222 		final byte[] body = IO.readFully(file);
223 		return new String(body, 0, body.length, "UTF-8");
224 	}
225 
226 	public static String read(final Repository db, final String name)
227 			throws IOException {
228 		File file = new File(db.getWorkTree(), name);
229 		return read(file);
230 	}
231 
232 	public static boolean check(final Repository db, final String name) {
233 		File file = new File(db.getWorkTree(), name);
234 		return file.exists();
235 	}
236 
237 	public static void deleteTrashFile(final Repository db,
238 			final String name) throws IOException {
239 		File path = new File(db.getWorkTree(), name);
240 		FileUtils.delete(path);
241 	}
242 
243 }