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 15KB

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