CLIRepositoryTestCase.java

  1. /*
  2.  * Copyright (C) 2012, IBM Corporation and others. and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */
  10. package org.eclipse.jgit.lib;

  11. import static org.junit.Assert.assertEquals;

  12. import java.io.File;
  13. import java.io.IOException;
  14. import java.nio.file.Path;
  15. import java.util.ArrayList;
  16. import java.util.Arrays;
  17. import java.util.List;

  18. import org.eclipse.jgit.junit.JGitTestUtil;
  19. import org.eclipse.jgit.junit.LocalDiskRepositoryTestCase;
  20. import org.eclipse.jgit.pgm.CLIGitCommand;
  21. import org.eclipse.jgit.pgm.CLIGitCommand.Result;
  22. import org.eclipse.jgit.pgm.TextBuiltin.TerminatedByHelpException;
  23. import org.junit.Before;

  24. public class CLIRepositoryTestCase extends LocalDiskRepositoryTestCase {
  25.     /** Test repository, initialized for this test case. */
  26.     protected Repository db;

  27.     @Override
  28.     @Before
  29.     public void setUp() throws Exception {
  30.         super.setUp();
  31.         db = createWorkRepository();
  32.     }

  33.     /**
  34.      * Executes specified git commands (with arguments)
  35.      *
  36.      * @param cmds
  37.      *            each string argument must be a valid git command line, e.g.
  38.      *            "git branch -h"
  39.      * @return command output
  40.      * @throws Exception
  41.      */
  42.     protected String[] executeUnchecked(String... cmds) throws Exception {
  43.         List<String> result = new ArrayList<>(cmds.length);
  44.         for (String cmd : cmds) {
  45.             result.addAll(CLIGitCommand.executeUnchecked(cmd, db));
  46.         }
  47.         return result.toArray(new String[0]);
  48.     }

  49.     /**
  50.      * Executes specified git commands (with arguments), throws exception and
  51.      * stops execution on first command which output contains a 'fatal:' error
  52.      *
  53.      * @param cmds
  54.      *            each string argument must be a valid git command line, e.g.
  55.      *            "git branch -h"
  56.      * @return command output
  57.      * @throws Exception
  58.      */
  59.     protected String[] execute(String... cmds) throws Exception {
  60.         List<String> result = new ArrayList<>(cmds.length);
  61.         for (String cmd : cmds) {
  62.             Result r = CLIGitCommand.executeRaw(cmd, db);
  63.             if (r.ex instanceof TerminatedByHelpException) {
  64.                 result.addAll(r.errLines());
  65.             } else if (r.ex != null) {
  66.                 throw r.ex;
  67.             }
  68.             result.addAll(r.outLines());
  69.         }
  70.         return result.toArray(new String[0]);
  71.     }

  72.     /**
  73.      * @param link
  74.      *            the path of the symbolic link to create
  75.      * @param target
  76.      *            the target of the symbolic link
  77.      * @return the path to the symbolic link
  78.      * @throws Exception
  79.      */
  80.     protected Path writeLink(String link, String target) throws Exception {
  81.         return JGitTestUtil.writeLink(db, link, target);
  82.     }

  83.     protected File writeTrashFile(String name, String data)
  84.             throws IOException {
  85.         return JGitTestUtil.writeTrashFile(db, name, data);
  86.     }

  87.     @Override
  88.     protected String read(File file) throws IOException {
  89.         return JGitTestUtil.read(file);
  90.     }

  91.     protected void deleteTrashFile(String name) throws IOException {
  92.         JGitTestUtil.deleteTrashFile(db, name);
  93.     }

  94.     /**
  95.      * Execute the given commands and print the output to stdout. Use this
  96.      * function instead of the normal {@link #execute(String...)} when preparing
  97.      * a test case: the command is executed and then its output is printed on
  98.      * stdout, thus making it easier to prepare the correct command and expected
  99.      * output for the test case.
  100.      *
  101.      * @param cmds
  102.      *            The commands to execute
  103.      * @return the result of the command, see {@link #execute(String...)}
  104.      * @throws Exception
  105.      */
  106.     protected String[] executeAndPrint(String... cmds) throws Exception {
  107.         String[] lines = execute(cmds);
  108.         for (String line : lines) {
  109.             System.out.println(line);
  110.         }
  111.         return lines;
  112.     }

  113.     /**
  114.      * Execute the given commands and print test code comparing expected and
  115.      * actual output. Use this function instead of the normal
  116.      * {@link #execute(String...)} when preparing a test case: the command is
  117.      * executed and test code is generated using the command output as a
  118.      * template of what is expected. The code generated is printed on stdout and
  119.      * can be pasted in the test case function.
  120.      *
  121.      * @param cmds
  122.      *            The commands to execute
  123.      * @return the result of the command, see {@link #execute(String...)}
  124.      * @throws Exception
  125.      */
  126.     protected String[] executeAndPrintTestCode(String... cmds) throws Exception {
  127.         String[] lines = execute(cmds);
  128.         String cmdString = cmdString(cmds);
  129.         if (lines.length == 0)
  130.             System.out.println("\t\tassertTrue(execute(" + cmdString
  131.                     + ").length == 0);");
  132.         else {
  133.             System.out
  134.                     .println("\t\tassertArrayOfLinesEquals(new String[] { //");
  135.             System.out.print("\t\t\t\t\t\t\"" + escapeJava(lines[0]));
  136.             for (int i=1; i<lines.length; i++) {
  137.                 System.out.println("\", //");
  138.                 System.out.print("\t\t\t\t\t\t\"" + escapeJava(lines[i]));
  139.             }
  140.             System.out.println("\" //");
  141.             System.out.println("\t\t\t\t}, execute(" + cmdString + ")); //");
  142.         }
  143.         return lines;
  144.     }

  145.     protected String cmdString(String... cmds) {
  146.         switch (cmds.length) {
  147.         case 0:
  148.             return "";
  149.         case 1:
  150.             return "\"" + escapeJava(cmds[0]) + "\"";
  151.         default:
  152.             StringBuilder sb = new StringBuilder(cmdString(cmds[0]));
  153.             for (int i=1; i<cmds.length; i++) {
  154.                 sb.append(", ");
  155.                 sb.append(cmdString(cmds[i]));
  156.             }
  157.             return sb.toString();
  158.         }
  159.     }

  160.     protected String escapeJava(String line) {
  161.         // very crude implementation but ok for generating test code
  162.         return line.replaceAll("\"", "\\\\\"") //
  163.                 .replaceAll("\\\\", "\\\\\\")
  164.                 .replaceAll("\t", "\\\\t");
  165.     }

  166.     protected String shellQuote(String s) {
  167.         return "'" + s.replace("'", "'\\''") + "'";
  168.     }

  169.     protected String shellQuote(File f) {
  170.         return "'" + f.getPath().replace("'", "'\\''") + "'";
  171.     }

  172.     protected void assertStringArrayEquals(String expected, String[] actual) {
  173.         // if there is more than one line, ignore last one if empty
  174.         assertEquals(1,
  175.                 actual.length > 1 && actual[actual.length - 1].isEmpty()
  176.                         ? actual.length - 1 : actual.length);
  177.         assertEquals(expected, actual[0]);
  178.     }

  179.     protected void assertArrayOfLinesEquals(String[] expected, String[] actual) {
  180.         assertEquals(toString(expected), toString(actual));
  181.     }

  182.     public static String toString(String... lines) {
  183.         return toString(Arrays.asList(lines));
  184.     }

  185.     public static String toString(List<String> lines) {
  186.         StringBuilder b = new StringBuilder();
  187.         for (String s : lines) {
  188.             // trim indentation, to simplify tests
  189.             s = s.trim();
  190.             if (s != null && !s.isEmpty()) {
  191.                 b.append(s);
  192.                 b.append('\n');
  193.             }
  194.         }
  195.         // delete last line break to allow simpler tests with one line compare
  196.         if (b.length() > 0 && b.charAt(b.length() - 1) == '\n') {
  197.             b.deleteCharAt(b.length() - 1);
  198.         }
  199.         return b.toString();
  200.     }

  201.     public static boolean contains(List<String> lines, String str) {
  202.         for (String s : lines) {
  203.             if (s.contains(str)) {
  204.                 return true;
  205.             }
  206.         }
  207.         return false;
  208.     }
  209. }