You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LocalDiskRepositoryTestCase.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /*
  2. * Copyright (C) 2009-2010, Google Inc.
  3. * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  4. * Copyright (C) 2007, Shawn O. Pearce <spearce@spearce.org>
  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. package org.eclipse.jgit.junit;
  46. import java.io.File;
  47. import java.io.FileOutputStream;
  48. import java.io.IOException;
  49. import java.io.OutputStreamWriter;
  50. import java.io.Writer;
  51. import java.util.ArrayList;
  52. import java.util.Collections;
  53. import java.util.HashMap;
  54. import java.util.List;
  55. import java.util.Map;
  56. import java.util.concurrent.TimeUnit;
  57. import junit.framework.Assert;
  58. import junit.framework.TestCase;
  59. import org.eclipse.jgit.lib.AnyObjectId;
  60. import org.eclipse.jgit.lib.Constants;
  61. import org.eclipse.jgit.lib.PersonIdent;
  62. import org.eclipse.jgit.lib.Repository;
  63. import org.eclipse.jgit.lib.RepositoryCache;
  64. import org.eclipse.jgit.storage.file.FileBasedConfig;
  65. import org.eclipse.jgit.storage.file.FileRepository;
  66. import org.eclipse.jgit.storage.file.WindowCache;
  67. import org.eclipse.jgit.storage.file.WindowCacheConfig;
  68. import org.eclipse.jgit.util.FS;
  69. import org.eclipse.jgit.util.IO;
  70. import org.eclipse.jgit.util.SystemReader;
  71. /**
  72. * JUnit TestCase with specialized support for temporary local repository.
  73. * <p>
  74. * A temporary directory is created for each test, allowing each test to use a
  75. * fresh environment. The temporary directory is cleaned up after the test ends.
  76. * <p>
  77. * Callers should not use {@link RepositoryCache} from within these tests as it
  78. * may wedge file descriptors open past the end of the test.
  79. * <p>
  80. * A system property {@code jgit.junit.usemmap} defines whether memory mapping
  81. * is used. Memory mapping has an effect on the file system, in that memory
  82. * mapped files in Java cannot be deleted as long as the mapped arrays have not
  83. * been reclaimed by the garbage collector. The programmer cannot control this
  84. * with precision, so temporary files may hang around longer than desired during
  85. * a test, or tests may fail altogether if there is insufficient file
  86. * descriptors or address space for the test process.
  87. */
  88. public abstract class LocalDiskRepositoryTestCase extends TestCase {
  89. private static Thread shutdownHook;
  90. private static int testCount;
  91. private static final boolean useMMAP = "true".equals(System
  92. .getProperty("jgit.junit.usemmap"));
  93. /** A fake (but stable) identity for author fields in the test. */
  94. protected PersonIdent author;
  95. /** A fake (but stable) identity for committer fields in the test. */
  96. protected PersonIdent committer;
  97. private final File trash = new File(new File("target"), "trash");
  98. private final List<Repository> toClose = new ArrayList<Repository>();
  99. private MockSystemReader mockSystemReader;
  100. @Override
  101. protected void setUp() throws Exception {
  102. super.setUp();
  103. if (shutdownHook == null) {
  104. shutdownHook = new Thread() {
  105. @Override
  106. public void run() {
  107. System.gc();
  108. recursiveDelete("SHUTDOWN", trash, false, false);
  109. }
  110. };
  111. Runtime.getRuntime().addShutdownHook(shutdownHook);
  112. }
  113. recursiveDelete(testName(), trash, true, false);
  114. mockSystemReader = new MockSystemReader();
  115. mockSystemReader.userGitConfig = new FileBasedConfig(new File(trash,
  116. "usergitconfig"), FS.DETECTED);
  117. ceilTestDirectories(getCeilings());
  118. SystemReader.setInstance(mockSystemReader);
  119. final long now = mockSystemReader.getCurrentTime();
  120. final int tz = mockSystemReader.getTimezone(now);
  121. author = new PersonIdent("J. Author", "jauthor@example.com");
  122. author = new PersonIdent(author, now, tz);
  123. committer = new PersonIdent("J. Committer", "jcommitter@example.com");
  124. committer = new PersonIdent(committer, now, tz);
  125. final WindowCacheConfig c = new WindowCacheConfig();
  126. c.setPackedGitLimit(128 * WindowCacheConfig.KB);
  127. c.setPackedGitWindowSize(8 * WindowCacheConfig.KB);
  128. c.setPackedGitMMAP(useMMAP);
  129. c.setDeltaBaseCacheLimit(8 * WindowCacheConfig.KB);
  130. WindowCache.reconfigure(c);
  131. }
  132. protected List<File> getCeilings() {
  133. return Collections.singletonList(trash.getParentFile().getAbsoluteFile());
  134. }
  135. private void ceilTestDirectories(List<File> ceilings) {
  136. mockSystemReader.setProperty(Constants.GIT_CEILING_DIRECTORIES_KEY, makePath(ceilings));
  137. }
  138. private String makePath(List<?> objects) {
  139. final StringBuilder stringBuilder = new StringBuilder();
  140. for (Object object : objects) {
  141. if (stringBuilder.length() > 0)
  142. stringBuilder.append(File.pathSeparatorChar);
  143. stringBuilder.append(object.toString());
  144. }
  145. return stringBuilder.toString();
  146. }
  147. @Override
  148. protected void tearDown() throws Exception {
  149. RepositoryCache.clear();
  150. for (Repository r : toClose)
  151. r.close();
  152. toClose.clear();
  153. // Since memory mapping is controlled by the GC we need to
  154. // tell it this is a good time to clean up and unlock
  155. // memory mapped files.
  156. //
  157. if (useMMAP)
  158. System.gc();
  159. recursiveDelete(testName(), trash, false, true);
  160. super.tearDown();
  161. }
  162. /** Increment the {@link #author} and {@link #committer} times. */
  163. protected void tick() {
  164. final long delta = TimeUnit.MILLISECONDS.convert(5 * 60,
  165. TimeUnit.SECONDS);
  166. final long now = author.getWhen().getTime() + delta;
  167. final int tz = mockSystemReader.getTimezone(now);
  168. author = new PersonIdent(author, now, tz);
  169. committer = new PersonIdent(committer, now, tz);
  170. }
  171. /**
  172. * Recursively delete a directory, failing the test if the delete fails.
  173. *
  174. * @param dir
  175. * the recursively directory to delete, if present.
  176. */
  177. protected void recursiveDelete(final File dir) {
  178. recursiveDelete(testName(), dir, false, true);
  179. }
  180. private static boolean recursiveDelete(final String testName,
  181. final File dir, boolean silent, boolean failOnError) {
  182. assert !(silent && failOnError);
  183. if (!dir.exists()) {
  184. return silent;
  185. }
  186. final File[] ls = dir.listFiles();
  187. if (ls != null) {
  188. for (int k = 0; k < ls.length; k++) {
  189. final File e = ls[k];
  190. if (e.isDirectory()) {
  191. silent = recursiveDelete(testName, e, silent, failOnError);
  192. } else {
  193. if (!e.delete()) {
  194. if (!silent) {
  195. reportDeleteFailure(testName, failOnError, e);
  196. }
  197. silent = !failOnError;
  198. }
  199. }
  200. }
  201. }
  202. if (!dir.delete()) {
  203. if (!silent) {
  204. reportDeleteFailure(testName, failOnError, dir);
  205. }
  206. silent = !failOnError;
  207. }
  208. return silent;
  209. }
  210. private static void reportDeleteFailure(final String testName,
  211. final boolean failOnError, final File e) {
  212. final String severity;
  213. if (failOnError)
  214. severity = "ERROR";
  215. else
  216. severity = "WARNING";
  217. final String msg = severity + ": Failed to delete " + e + " in "
  218. + testName;
  219. if (failOnError)
  220. fail(msg);
  221. else
  222. System.err.println(msg);
  223. }
  224. /**
  225. * Creates a new empty bare repository.
  226. *
  227. * @return the newly created repository, opened for access
  228. * @throws IOException
  229. * the repository could not be created in the temporary area
  230. */
  231. protected FileRepository createBareRepository() throws IOException {
  232. return createRepository(true /* bare */);
  233. }
  234. /**
  235. * Creates a new empty repository within a new empty working directory.
  236. *
  237. * @return the newly created repository, opened for access
  238. * @throws IOException
  239. * the repository could not be created in the temporary area
  240. */
  241. protected FileRepository createWorkRepository() throws IOException {
  242. return createRepository(false /* not bare */);
  243. }
  244. /**
  245. * Creates a new empty repository.
  246. *
  247. * @param bare
  248. * true to create a bare repository; false to make a repository
  249. * within its working directory
  250. * @return the newly created repository, opened for access
  251. * @throws IOException
  252. * the repository could not be created in the temporary area
  253. */
  254. private FileRepository createRepository(boolean bare) throws IOException {
  255. String uniqueId = System.currentTimeMillis() + "_" + (testCount++);
  256. String gitdirName = "test" + uniqueId + (bare ? "" : "/") + Constants.DOT_GIT;
  257. File gitdir = new File(trash, gitdirName).getCanonicalFile();
  258. FileRepository db = new FileRepository(gitdir);
  259. assertFalse(gitdir.exists());
  260. db.create();
  261. toClose.add(db);
  262. return db;
  263. }
  264. /**
  265. * Run a hook script in the repository, returning the exit status.
  266. *
  267. * @param db
  268. * repository the script should see in GIT_DIR environment
  269. * @param hook
  270. * path of the hook script to execute, must be executable file
  271. * type on this platform
  272. * @param args
  273. * arguments to pass to the hook script
  274. * @return exit status code of the invoked hook
  275. * @throws IOException
  276. * the hook could not be executed
  277. * @throws InterruptedException
  278. * the caller was interrupted before the hook completed
  279. */
  280. protected int runHook(final Repository db, final File hook,
  281. final String... args) throws IOException, InterruptedException {
  282. final String[] argv = new String[1 + args.length];
  283. argv[0] = hook.getAbsolutePath();
  284. System.arraycopy(args, 0, argv, 1, args.length);
  285. final Map<String, String> env = cloneEnv();
  286. env.put("GIT_DIR", db.getDirectory().getAbsolutePath());
  287. putPersonIdent(env, "AUTHOR", author);
  288. putPersonIdent(env, "COMMITTER", committer);
  289. final File cwd = db.getWorkTree();
  290. final Process p = Runtime.getRuntime().exec(argv, toEnvArray(env), cwd);
  291. p.getOutputStream().close();
  292. p.getErrorStream().close();
  293. p.getInputStream().close();
  294. return p.waitFor();
  295. }
  296. private static void putPersonIdent(final Map<String, String> env,
  297. final String type, final PersonIdent who) {
  298. final String ident = who.toExternalString();
  299. final String date = ident.substring(ident.indexOf("> ") + 2);
  300. env.put("GIT_" + type + "_NAME", who.getName());
  301. env.put("GIT_" + type + "_EMAIL", who.getEmailAddress());
  302. env.put("GIT_" + type + "_DATE", date);
  303. }
  304. /**
  305. * Create a string to a UTF-8 temporary file and return the path.
  306. *
  307. * @param body
  308. * complete content to write to the file. If the file should end
  309. * with a trailing LF, the string should end with an LF.
  310. * @return path of the temporary file created within the trash area.
  311. * @throws IOException
  312. * the file could not be written.
  313. */
  314. protected File write(final String body) throws IOException {
  315. final File f = File.createTempFile("temp", "txt", trash);
  316. try {
  317. write(f, body);
  318. return f;
  319. } catch (Error e) {
  320. f.delete();
  321. throw e;
  322. } catch (RuntimeException e) {
  323. f.delete();
  324. throw e;
  325. } catch (IOException e) {
  326. f.delete();
  327. throw e;
  328. }
  329. }
  330. /**
  331. * Write a string as a UTF-8 file.
  332. *
  333. * @param f
  334. * file to write the string to. Caller is responsible for making
  335. * sure it is in the trash directory or will otherwise be cleaned
  336. * up at the end of the test. If the parent directory does not
  337. * exist, the missing parent directories are automatically
  338. * created.
  339. * @param body
  340. * content to write to the file.
  341. * @throws IOException
  342. * the file could not be written.
  343. */
  344. protected void write(final File f, final String body) throws IOException {
  345. f.getParentFile().mkdirs();
  346. Writer w = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
  347. try {
  348. w.write(body);
  349. } finally {
  350. w.close();
  351. }
  352. }
  353. /**
  354. * Fully read a UTF-8 file and return as a string.
  355. *
  356. * @param f
  357. * file to read the content of.
  358. * @return UTF-8 decoded content of the file, empty string if the file
  359. * exists but has no content.
  360. * @throws IOException
  361. * the file does not exist, or could not be read.
  362. */
  363. protected String read(final File f) throws IOException {
  364. final byte[] body = IO.readFully(f);
  365. return new String(body, 0, body.length, "UTF-8");
  366. }
  367. protected static void assertEquals(AnyObjectId exp, AnyObjectId act) {
  368. Assert.assertEquals(exp, act);
  369. }
  370. private static String[] toEnvArray(final Map<String, String> env) {
  371. final String[] envp = new String[env.size()];
  372. int i = 0;
  373. for (Map.Entry<String, String> e : env.entrySet()) {
  374. envp[i++] = e.getKey() + "=" + e.getValue();
  375. }
  376. return envp;
  377. }
  378. private static HashMap<String, String> cloneEnv() {
  379. return new HashMap<String, String>(System.getenv());
  380. }
  381. private String testName() {
  382. return getClass().getName() + "." + getName();
  383. }
  384. }