Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

LocalDiskRepositoryTestCase.java 13KB

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