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

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