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