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 static java.nio.charset.StandardCharsets.UTF_8;
49  
50  import java.io.File;
51  import java.io.FileNotFoundException;
52  import java.io.FileOutputStream;
53  import java.io.IOException;
54  import java.io.InputStream;
55  import java.io.OutputStreamWriter;
56  import java.io.Writer;
57  import java.lang.reflect.Method;
58  import java.net.URISyntaxException;
59  import java.net.URL;
60  import java.nio.file.Path;
61  
62  import org.eclipse.jgit.lib.Repository;
63  import org.eclipse.jgit.util.FileUtils;
64  import org.eclipse.jgit.util.IO;
65  import org.eclipse.jgit.util.RawParseUtils;
66  import org.junit.Assert;
67  import org.junit.Test;
68  
69  /**
70   * Abstract test util class
71   */
72  public abstract class JGitTestUtil {
73  	/** Constant <code>CLASSPATH_TO_RESOURCES="org/eclipse/jgit/test/resources/"</code> */
74  	public static final String CLASSPATH_TO_RESOURCES = "org/eclipse/jgit/test/resources/";
75  
76  	private JGitTestUtil() {
77  		throw new UnsupportedOperationException();
78  	}
79  
80  	/**
81  	 * Get name of current test by inspecting stack trace
82  	 *
83  	 * @return the name
84  	 */
85  	public static String getName() {
86  		GatherStackTrace stack;
87  		try {
88  			throw new GatherStackTrace();
89  		} catch (GatherStackTrace wanted) {
90  			stack = wanted;
91  		}
92  
93  		try {
94  			for (StackTraceElement stackTrace : stack.getStackTrace()) {
95  				String className = stackTrace.getClassName();
96  				String methodName = stackTrace.getMethodName();
97  				Method method;
98  				try {
99  					method = Class.forName(className) //
100 							.getMethod(methodName, (Class[]) null);
101 				} catch (NoSuchMethodException e) {
102 					// could be private, i.e. not a test method
103 					// could have arguments, not handled
104 					continue;
105 				}
106 
107 				Test annotation = method.getAnnotation(Test.class);
108 				if (annotation != null)
109 					return methodName;
110 			}
111 		} catch (ClassNotFoundException shouldNeverOccur) {
112 			// Fall through and crash.
113 		}
114 
115 		throw new AssertionError("Cannot determine name of current test");
116 	}
117 
118 	@SuppressWarnings("serial")
119 	private static class GatherStackTrace extends Exception {
120 		// Thrown above to collect the stack frame.
121 	}
122 
123 	/**
124 	 * Assert byte arrays are equal
125 	 *
126 	 * @param exp
127 	 *            expected value
128 	 * @param act
129 	 *            actual value
130 	 */
131 	public static void assertEquals(byte[] exp, byte[] act) {
132 		Assert.assertEquals(s(exp), s(act));
133 	}
134 
135 	private static String s(byte[] raw) {
136 		return RawParseUtils.decode(raw);
137 	}
138 
139 	/**
140 	 * Get test resource file.
141 	 *
142 	 * @param fileName
143 	 * @return the test resource file
144 	 */
145 	public static File getTestResourceFile(String fileName) {
146 		if (fileName == null || fileName.length() <= 0) {
147 			return null;
148 		}
149 		final URL url = cl().getResource(CLASSPATH_TO_RESOURCES + fileName);
150 		if (url == null) {
151 			// If URL is null then try to load it as it was being
152 			// loaded previously
153 			return new File("tst", fileName);
154 		}
155 		if ("jar".equals(url.getProtocol())) {
156 			try {
157 				File tmp = File.createTempFile("tmp_", "_" + fileName);
158 				copyTestResource(fileName, tmp);
159 				return tmp;
160 			} catch (IOException err) {
161 				throw new RuntimeException("Cannot create temporary file", err);
162 			}
163 		}
164 		try {
165 			return new File(url.toURI());
166 		} catch (IllegalArgumentException e) {
167 			throw new IllegalArgumentException(e.getMessage() + " " + url);
168 		} catch (URISyntaxException e) {
169 			return new File(url.getPath());
170 		}
171 	}
172 
173 	/**
174 	 * Copy test resource.
175 	 *
176 	 * @param name
177 	 * @param dest
178 	 * @throws IOException
179 	 */
180 	public static void copyTestResource(String name, File dest)
181 			throws IOException {
182 		URL url = cl().getResource(CLASSPATH_TO_RESOURCES + name);
183 		if (url == null)
184 			throw new FileNotFoundException(name);
185 		try (InputStream in = url.openStream();
186 				FileOutputStream out = new FileOutputStream(dest)) {
187 			byte[] buf = new byte[4096];
188 			for (int n; (n = in.read(buf)) > 0;)
189 				out.write(buf, 0, n);
190 		}
191 	}
192 
193 	private static ClassLoader cl() {
194 		return JGitTestUtil.class.getClassLoader();
195 	}
196 
197 	/**
198 	 * Write a trash file.
199 	 *
200 	 * @param db
201 	 * @param name
202 	 * @param data
203 	 * @return the trash file
204 	 * @throws IOException
205 	 */
206 	public static File writeTrashFile(final Repository db,
207 			final String name, final String data) throws IOException {
208 		File path = new File(db.getWorkTree(), name);
209 		write(path, data);
210 		return path;
211 	}
212 
213 	/**
214 	 * Write a trash file.
215 	 *
216 	 * @param db
217 	 * @param subdir
218 	 * @param name
219 	 * @param data
220 	 * @return the trash file
221 	 * @throws IOException
222 	 */
223 	public static File writeTrashFile(final Repository db,
224 			final String subdir,
225 			final String name, final String data) throws IOException {
226 		File path = new File(db.getWorkTree() + "/" + subdir, name);
227 		write(path, data);
228 		return path;
229 	}
230 
231 	/**
232 	 * Write a string as a UTF-8 file.
233 	 *
234 	 * @param f
235 	 *            file to write the string to. Caller is responsible for making
236 	 *            sure it is in the trash directory or will otherwise be cleaned
237 	 *            up at the end of the test. If the parent directory does not
238 	 *            exist, the missing parent directories are automatically
239 	 *            created.
240 	 * @param body
241 	 *            content to write to the file.
242 	 * @throws IOException
243 	 *             the file could not be written.
244 	 */
245 	public static void write(File f, String body)
246 			throws IOException {
247 		FileUtils.mkdirs(f.getParentFile(), true);
248 		try (Writer w = new OutputStreamWriter(new FileOutputStream(f),
249 				UTF_8)) {
250 			w.write(body);
251 		}
252 	}
253 
254 	/**
255 	 * Fully read a UTF-8 file and return as a string.
256 	 *
257 	 * @param file
258 	 *            file to read the content of.
259 	 * @return UTF-8 decoded content of the file, empty string if the file
260 	 *         exists but has no content.
261 	 * @throws IOException
262 	 *             the file does not exist, or could not be read.
263 	 */
264 	public static String read(File file) throws IOException {
265 		final byte[] body = IO.readFully(file);
266 		return new String(body, 0, body.length, UTF_8);
267 	}
268 
269 	/**
270 	 * Read a file's content
271 	 *
272 	 * @param db
273 	 * @param name
274 	 * @return the content of the file
275 	 * @throws IOException
276 	 */
277 	public static String read(Repository db, String name)
278 			throws IOException {
279 		File file = new File(db.getWorkTree(), name);
280 		return read(file);
281 	}
282 
283 	/**
284 	 * Check if file exists
285 	 *
286 	 * @param db
287 	 * @param name
288 	 *            name of the file
289 	 * @return {@code true} if the file exists
290 	 */
291 	public static boolean check(Repository db, String name) {
292 		File file = new File(db.getWorkTree(), name);
293 		return file.exists();
294 	}
295 
296 	/**
297 	 * Delete a trash file.
298 	 *
299 	 * @param db
300 	 * @param name
301 	 * @throws IOException
302 	 */
303 	public static void deleteTrashFile(final Repository db,
304 			final String name) throws IOException {
305 		File path = new File(db.getWorkTree(), name);
306 		FileUtils.delete(path);
307 	}
308 
309 	/**
310 	 * Write a symbolic link
311 	 *
312 	 * @param db
313 	 *            the repository
314 	 * @param link
315 	 *            the path of the symbolic link to create
316 	 * @param target
317 	 *            the target of the symbolic link
318 	 * @return the path to the symbolic link
319 	 * @throws Exception
320 	 * @since 4.2
321 	 */
322 	public static Path writeLink(Repository db, String link,
323 			String target) throws Exception {
324 		return FileUtils.createSymLink(new File(db.getWorkTree(), link),
325 				target);
326 	}
327 
328 	/**
329 	 * Concatenate byte arrays.
330 	 *
331 	 * @param b
332 	 *            byte arrays to combine together.
333 	 * @return a single byte array that contains all bytes copied from input
334 	 *         byte arrays.
335 	 * @since 4.9
336 	 */
337 	public static byte[] concat(byte[]... b) {
338 		int n = 0;
339 		for (byte[] a : b) {
340 			n += a.length;
341 		}
342 
343 		byte[] data = new byte[n];
344 		n = 0;
345 		for (byte[] a : b) {
346 			System.arraycopy(a, 0, data, n, a.length);
347 			n += a.length;
348 		}
349 		return data;
350 	}
351 }