@Test
 public void testRemoveCase3() {
   AvlTree<Integer> tree = new AvlTree<Integer>();
   tree.insert(50)
       .insert(25)
       .insert(80)
       .insert(10)
       .insert(40)
       .insert(60)
       .insert(100)
       .insert(30)
       .insert(55)
       .insert(90)
       .insert(150)
       .insert(85)
       .insert(95)
       .remove(60);
   String treeOut = "50 25 90 10 40 80 100 30 55 85 95 150 ";
   ByteArrayOutputStream outContent = new ByteArrayOutputStream();
   ByteArrayOutputStream errContent = new ByteArrayOutputStream();
   System.setOut(new PrintStream(outContent));
   System.setErr(new PrintStream(errContent));
   tree.printTreeLevel();
   assertEquals(treeOut, outContent.toString());
   System.setOut(null);
   System.setErr(null);
 }
  private String execute(final String name, final String code, final String input)
      throws Throwable {
    bc.compile(new StringReader(code), name, name, cw);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    InputStream is = System.in;
    PrintStream os = System.out;
    System.setIn(new ByteArrayInputStream(input.getBytes()));
    System.setOut(new PrintStream(bos));

    try {
      TestClassLoader cl = new TestClassLoader(getClass().getClassLoader(), name, cw.toByteArray());
      Class<?> c = cl.loadClass(name);
      Method m = c.getDeclaredMethod("main", new Class<?>[] {String[].class});
      m.invoke(null, new Object[] {new String[0]});

    } catch (InvocationTargetException ex) {
      throw ex.getCause();
    } finally {
      System.setIn(is);
      System.setOut(os);
    }

    String output = new String(bos.toByteArray(), "ASCII");

    System.out.println(code + " WITH INPUT '" + input + "' GIVES " + output);

    return output;
  }
  private static void testSysOut(String fs, String exp, Object... args) {
    FileOutputStream fos = null;
    FileInputStream fis = null;
    try {
      PrintStream saveOut = System.out;
      fos = new FileOutputStream("testSysOut");
      System.setOut(new PrintStream(fos));
      System.out.format(Locale.US, fs, args);
      fos.close();

      fis = new FileInputStream("testSysOut");
      byte[] ba = new byte[exp.length()];
      int len = fis.read(ba);
      String got = new String(ba);
      if (len != ba.length) fail(fs, exp, got);
      ck(fs, exp, got);

      System.setOut(saveOut);
    } catch (FileNotFoundException ex) {
      fail(fs, ex.getClass());
    } catch (IOException ex) {
      fail(fs, ex.getClass());
    } finally {
      try {
        if (fos != null) fos.close();
        if (fis != null) fis.close();
      } catch (IOException ex) {
        fail(fs, ex.getClass());
      }
    }
  }
  @Test
  public void attemptToMergeReservedProperty() throws Exception {
    HashMap<String, String> customProperties = new HashMap<String, String>();
    customProperties.put("user.dir", "/home/foo");

    Properties propertiesFile = new Properties();
    propertiesFile.load(new FileInputStream(new File(this.testFile.toURI())));

    ByteArrayOutputStream logCapture = new ByteArrayOutputStream();
    System.setOut(new PrintStream(logCapture));

    Properties modifiedProperties =
        new PropertyFileMerger().mergeProperties(customProperties, propertiesFile);

    String loggedMessage = UtilityFunctions.stripCarriageReturns(logCapture.toString());
    System.setOut(this.originalOut);

    assertThat(modifiedProperties.containsKey("user.dir"), is(equalTo(false)));
    assertThat(modifiedProperties.size(), is(equalTo(2)));
    assertThat(
        loggedMessage,
        is(
            equalTo(
                "[warn] Unable to set 'user.dir', it is a reserved property in the jmeter-maven-plugin")));
  }
Exemple #5
1
  public void test13666() {
    Options options = new Options();
    Option dir = OptionBuilder.withDescription("dir").hasArg().create('d');
    options.addOption(dir);

    final PrintStream oldSystemOut = System.out;
    try {
      final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
      final PrintStream print = new PrintStream(bytes);

      // capture this platform's eol symbol
      print.println();
      final String eol = bytes.toString();
      bytes.reset();

      System.setOut(new PrintStream(bytes));
      try {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("dir", options);
      } catch (Exception exp) {
        fail("Unexpected Exception: " + exp.getMessage());
      }
      assertEquals("usage: dir" + eol + " -d <arg>   dir" + eol, bytes.toString());
    } finally {
      System.setOut(oldSystemOut);
    }
  }
 @Test
 public void testRemoveCase1() {
   AvlTree<Integer> tree = new AvlTree<Integer>();
   tree.insert(12)
       .insert(6)
       .insert(30)
       .insert(4)
       .insert(8)
       .insert(25)
       .insert(55)
       .insert(2)
       .insert(5)
       .insert(7)
       .insert(11)
       .insert(57)
       .insert(1)
       .remove(8)
       .remove(11);
   String treeOut = "12 4 30 2 6 25 55 1 5 7 57 ";
   ByteArrayOutputStream outContent = new ByteArrayOutputStream();
   ByteArrayOutputStream errContent = new ByteArrayOutputStream();
   System.setOut(new PrintStream(outContent));
   System.setErr(new PrintStream(errContent));
   tree.printTreeLevel();
   assertEquals(treeOut, outContent.toString());
   System.setOut(null);
   System.setErr(null);
 }
  /**
   * One round of test for max_retries and timeout.
   *
   * @param expected the expected kdc# timeout kdc# timeout...
   */
  private static void test0(ByteArrayOutputStream bo, String expected) throws Exception {
    PrintStream oldout = System.out;
    boolean failed = false;
    System.setOut(new PrintStream(bo));
    try {
      Context.fromUserPass(OneKDC.USER, OneKDC.PASS, false);
    } catch (Exception e) {
      failed = true;
    } finally {
      System.setOut(oldout);
    }

    String[] lines = new String(bo.toByteArray()).split("\n");
    StringBuilder sb = new StringBuilder();
    for (String line : lines) {
      Matcher m = re.matcher(line);
      if (m.find()) {
        System.out.println(line);
        sb.append(m.group(1)).append(toSymbolicSec(Integer.parseInt(m.group(2))));
      }
    }
    if (failed) sb.append('-');

    String output = sb.toString();
    System.out.println("Expected: " + expected + ", actual " + output);
    if (!output.matches(expected)) {
      throw new Exception("Does not match");
    }
  }
Exemple #8
0
  public static void main(String[] args) {

    PrintStream out = System.out;

    try {
      File file = new File("game.txt");
      PrintStream printStream = new PrintStream(new FileOutputStream(file));
      System.setOut(printStream);
    } catch (Exception e) {
      System.out.println("Cannot open game.txt for writing");
      return;
    }

    for (int i = 0; i < 100; i++) {
      PlayFakeGame();
    }

    System.setOut(out);

    System.out.println("Wrote output of 100 games to game.txt");
    File expectedFile = new File("expected.txt");
    if (expectedFile.exists()) {
      String expected = readFile("expected.txt");
      String actual = readFile("game.txt");

      System.out.println();
      System.out.println(
          "Diff with expected.txt: " + (actual.equals(expected) ? "OK!" : "Failure!!!"));
    } else {
      System.out.println("expected.txt missing. Rename game.txt to expected.txt and try again");
    }
  }
Exemple #9
0
 static String runHive(String... args) throws Exception {
   ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
   ByteArrayOutputStream errBytes = new ByteArrayOutputStream();
   PrintStream outSaved = System.out;
   PrintStream errSaved = System.err;
   System.setOut(new PrintStream(outBytes, true));
   System.setErr(new PrintStream(errBytes, true));
   try {
     CliDriver.run(args);
   } finally {
     System.setOut(outSaved);
     System.setErr(errSaved);
   }
   ByteArrayInputStream outBytesIn = new ByteArrayInputStream(outBytes.toByteArray());
   ByteArrayInputStream errBytesIn = new ByteArrayInputStream(errBytes.toByteArray());
   BufferedReader is = new BufferedReader(new InputStreamReader(outBytesIn));
   BufferedReader es = new BufferedReader(new InputStreamReader(errBytesIn));
   StringBuilder output = new StringBuilder();
   String line;
   while ((line = is.readLine()) != null) {
     if (output.length() > 0) {
       output.append("\n");
     }
     output.append(line);
   }
   if (output.length() == 0) {
     output = new StringBuilder();
     while ((line = es.readLine()) != null) {
       output.append("\n");
       output.append(line);
     }
   }
   return output.toString();
 }
  /**
   * Test of printHelp, of class CliParser.
   *
   * @throws Exception thrown when an excpetion occurs.
   */
  @Test
  public void testParse_printHelp() throws Exception {
    System.out.println("printHelp");

    PrintStream out = System.out;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    System.setOut(new PrintStream(baos));

    CliParser instance = new CliParser();
    String[] args = {"-h"};
    instance.parse(args);
    instance.printHelp();
    args[0] = "-ah";
    instance.parse(args);
    instance.printHelp();
    try {
      baos.flush();
      String text = (new String(baos.toByteArray()));
      String[] lines = text.split(System.getProperty("line.separator"));
      assertTrue(lines[0].startsWith("usage: "));
      assertTrue((lines.length > 2));
    } catch (IOException ex) {
      System.setOut(out);
      fail("CliParser.printVersionInfo did not write anything to system.out.");
    } finally {
      System.setOut(out);
    }
  }
Exemple #11
0
  public static void main(String[] args) throws IOException {
    PrintStream console = System.out;
    FileInputStream in =
        new FileInputStream(
            new File(
                System.getProperty("user.dir")
                    + File.separator
                    + "src"
                    + File.separator
                    + "chap18"
                    + File.separator
                    + "Redirecting.java"));
    PrintStream out = new PrintStream(new FileOutputStream(new File("test.txt")));
    System.setIn(in);
    System.setOut(out);
    System.setErr(out);

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String s;
    while ((s = reader.readLine()) != null) {
      System.out.println(s);
    }
    out.close();
    System.setOut(console);
  }
  @Test
  public void testPrint() {

    String treeOut = "11 12 30 32 33 35 36 47 50 55 57 ";
    AvlTree<Integer> tree = new AvlTree<Integer>();
    tree.insert(50)
        .insert(30)
        .insert(55)
        .insert(33)
        .insert(12)
        .insert(11)
        .insert(57)
        .insert(35)
        .insert(36)
        .insert(47)
        .insert(32);

    ByteArrayOutputStream outContent = new ByteArrayOutputStream();
    ByteArrayOutputStream errContent = new ByteArrayOutputStream();
    System.setOut(new PrintStream(outContent));
    System.setErr(new PrintStream(errContent));
    tree.printTree();
    assertEquals(treeOut, outContent.toString());
    System.setOut(null);
    System.setErr(null);
  }
Exemple #13
0
  // Then JUnit calls this test on it
  @Test
  public void testStatement() {
    // Build up a little program
    EagleFileReader pgm = new EagleFileReader();
    pgm.add("IDENTIFICATION DIVISION.");
    if (_data != null) {
      pgm.add("DATA DIVISION.");
      pgm.add("WORKING-STORAGE SECTION.");
      pgm.add(_data);
    }
    pgm.add("PROCEDURE DIVISION.");
    pgm.add(_proc);
    COBOL_Program_Complete lang = new COBOL_Program_Free_Format();
    ParserManager parser = new ParserManager();
    parser.parseLines(pgm, lang, lang);

    // Now, run the program
    PrintStream saveOut = System.out;
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    PrintStream prt = new PrintStream(stream);
    System.setOut(prt); // Redirect into my byte stream

    _interpreter.execute(lang);

    System.setOut(saveOut); // Restore original stdout
    prt.close();
    String actualOutput = stream.toString();
    assert _expected == actualOutput : "Values didn't match";
    System.out.print("==== " + _testName + " ====\n");
    if (_data != null) System.out.print(_data + "\n");
    System.out.print(_proc + "\n");
    System.out.println("Printed " + _expected + "As expected.\n");
  }
  /**
   * Tests that the we can effectively create file blocks generating text on the standard output
   * stream.
   */
  public void testFileBlockOutputStream() {
    final FileBlock mtlFileBlock = getDummyFileBlock();
    mtlFileBlock.setFileUrl(createOCLExpression("'stdout'")); // $NON-NLS-1$

    final PrintStream oldOut = System.out;
    final StringBuffer generatedText = new StringBuffer();

    // redirect standard output to our buffer
    System.setOut(
        new PrintStream(System.out) {
          @Override
          public void write(int b) {
            generatedText.append((char) b);
          }
        });
    evaluationVisitor.visitExpression(getParentTemplate(mtlFileBlock));
    System.setOut(oldOut);

    assertEquals(
        "Generation hasn't been redirected to the standard output.",
        OUTPUT,
        generatedText //$NON-NLS-1$
            .toString());
    assertTrue("No preview should have been generated.", getPreview().isEmpty()); // $NON-NLS-1$
  }
  /**
   * Helper method that runs the UnixStreamPipeline with the given history and logic pipe.
   *
   * @param history
   * @param pipe
   * @return
   * @throws IOException
   * @throws InvalidDataException
   */
  private String run(String history, Pipe pipe) throws IOException, InvalidDataException {

    // create IN/OUT streams to be used by UnixStreamPipeline
    InputStream inStream = new ByteArrayInputStream(history.getBytes());
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();

    // save default streams for STDIN and STDOUT
    final InputStream DEFAULT_STDIN = System.in;
    final PrintStream DEFAULT_STDOUT = System.out;

    // override STDIN/STDOUT defaults for java
    System.setIn(inStream);
    System.setOut(new PrintStream(outStream, true));

    // run UnixStreamPipeline
    mPipeline.execute(pipe);

    // flush stream and grab the modified history
    outStream.flush();
    String historyModified = outStream.toString().trim();
    outStream.close();

    // reset streams back to defaults
    System.setIn(DEFAULT_STDIN);
    System.setOut(DEFAULT_STDOUT);

    return historyModified;
  }
  @Test
  public void shouldCaptureConsoleErrorOutput_WhenYAMLValid_WithFileFailedToLoadAndBodySet()
      throws Exception {

    final String stubbedResponseFile = "../../very.big.soap.response.xml";

    final String expectedBody = "{\"message\", \"Hello, this is HTTP response body\"}";
    final String yaml =
        YAML_BUILDER
            .newStubbedRequest()
            .withMethodGet()
            .withUrl("/some/uri")
            .newStubbedResponse()
            .withFoldedBody(expectedBody)
            .withFile(stubbedResponseFile)
            .withStatus("201")
            .build();

    final ByteArrayOutputStream consoleCaptor = new ByteArrayOutputStream();
    final boolean NO_AUTO_FLUSH = false;
    System.setOut(new PrintStream(consoleCaptor, NO_AUTO_FLUSH, StringUtils.UTF_8));

    unmarshall(yaml);

    System.setOut(System.out);

    final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim();

    assertThat(actualConsoleOutput)
        .contains("Could not load file from path: ../../very.big.soap.response.xml");
    assertThat(actualConsoleOutput).contains(YamlParser.FAILED_TO_LOAD_FILE_ERR);
  }
Exemple #17
0
 static String execCmd(FsShell shell, String... args) throws Exception {
   ByteArrayOutputStream baout = new ByteArrayOutputStream();
   PrintStream out = new PrintStream(baout, true);
   PrintStream old = System.out;
   System.setOut(out);
   shell.run(args);
   out.close();
   System.setOut(old);
   return baout.toString();
 }
 /**
  * Temporarily captures the output to the standard output stream, then restores the standard
  * output stream once complete.
  *
  * <p>Note: the implementation details of this function are advanced. If you don't understand it
  * just now, don't worry.
  *
  * @param args arguments to pass to main function of class to be tested
  * @return output result of calling main function of class to be tested
  */
 private String captureOutputOfMain(String args[]) {
   OutputStream outputStream = new ByteArrayOutputStream();
   PrintStream originalOut = System.out;
   System.setOut(new PrintStream(outputStream));
   try {
     DateFashion.main(args);
   } finally {
     System.setOut(originalOut);
   }
   return outputStream.toString().trim();
 }
 public void testUsage() {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   PrintStream captured = new PrintStream(baos);
   PrintStream stdout = System.out;
   System.setOut(new PrintStream(captured));
   try {
     MysqldResource.main(new String[] {"--help"});
   } finally {
     System.setOut(stdout);
   }
   assertTrue(baos.toString().indexOf("Usage") >= 0);
 }
Exemple #20
0
 public static void main(String[] args) {
   PrintStream consoleStream = System.out;
   ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
   PrintStream stream = new PrintStream(outputStream);
   System.setOut(stream);
   testString.printSomething();
   String result = outputStream.toString();
   System.setOut(consoleStream);
   String stringBuilder = new String(result);
   String string = stringBuilder.replaceAll("te", "??");
   System.out.println(string);
 }
 @Test
 public void testPrintLevelEmpty() {
   String treeOut = "";
   AvlTree<Integer> tree = new AvlTree<Integer>();
   ByteArrayOutputStream outContent = new ByteArrayOutputStream();
   ByteArrayOutputStream errContent = new ByteArrayOutputStream();
   System.setOut(new PrintStream(outContent));
   System.setErr(new PrintStream(errContent));
   tree.printTreeLevel();
   assertEquals(treeOut, outContent.toString());
   System.setOut(null);
   System.setErr(null);
 }
 @Override
 protected String run(final String... args) throws IOException {
   try {
     final ArrayOutput ao = new ArrayOutput();
     System.setOut(new PrintStream(ao));
     System.setErr(NULL);
     new BaseX(args);
     return ao.toString();
   } finally {
     System.setOut(OUT);
     System.setErr(ERR);
   }
 }
  public void testSimpleOutput() throws Exception {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PrintStream collector = new PrintStream(byteArrayOutputStream);
    PrintStream orgOur = System.out;
    System.setOut(collector);

    RunStatistics result = runClasses(Dummy3.class);
    assertReporter(result, 2, 0, 0, "msgs");

    String foo = new String(byteArrayOutputStream.toByteArray());
    assertNotNull(foo);

    System.setOut(orgOur);
  }
 @Test
 public void testInsertCase4() {
   AvlTree<Integer> tree = new AvlTree<Integer>();
   tree.insert(12).insert(5).insert(15).insert(17).insert(13).insert(19);
   String treeOut = "15 12 17 5 13 19 ";
   ByteArrayOutputStream outContent = new ByteArrayOutputStream();
   ByteArrayOutputStream errContent = new ByteArrayOutputStream();
   System.setOut(new PrintStream(outContent));
   System.setErr(new PrintStream(errContent));
   tree.printTreeLevel();
   assertEquals(treeOut, outContent.toString());
   System.setOut(null);
   System.setErr(null);
 }
  public static int test(int n) throws Exception {
    PrintStream oldOut = System.out;
    int sum = 0;
    for (int i = 0; i < 10; i++) {
      ByteArrayOutputStream ba = new ByteArrayOutputStream(n * 10);
      PrintStream newOut = new PrintStream(ba);
      System.setOut(newOut);
      doPrint(n);
      sum += ba.size();
    }

    System.setOut(oldOut);
    return sum;
  }
 static String runFsck(
     Configuration conf, int expectedErrCode, boolean checkErrorCode, String... path)
     throws Exception {
   PrintStream oldOut = System.out;
   ByteArrayOutputStream bStream = new ByteArrayOutputStream();
   PrintStream newOut = new PrintStream(bStream, true);
   System.setOut(newOut);
   ((Log4JLogger) PermissionChecker.LOG).getLogger().setLevel(Level.ALL);
   int errCode = ToolRunner.run(new DFSck(conf), path);
   if (checkErrorCode) assertEquals(expectedErrCode, errCode);
   ((Log4JLogger) PermissionChecker.LOG).getLogger().setLevel(Level.INFO);
   System.setOut(oldOut);
   return bStream.toString();
 }
 @Test
 public void testRemoveCase4() {
   AvlTree<Integer> tree = new AvlTree<Integer>();
   tree.insert(12).insert(5).insert(20).insert(4).insert(18).insert(25).insert(40).remove(5);
   String treeOut = "20 12 25 4 18 40 ";
   ByteArrayOutputStream outContent = new ByteArrayOutputStream();
   ByteArrayOutputStream errContent = new ByteArrayOutputStream();
   System.setOut(new PrintStream(outContent));
   System.setErr(new PrintStream(errContent));
   tree.printTreeLevel();
   assertEquals(treeOut, outContent.toString());
   System.setOut(null);
   System.setErr(null);
 }
Exemple #28
0
  static String invokeExec(String cmd, String... args) {
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    PrintStream prev = System.out;

    try {
      PrintStream p = new PrintStream(b);
      System.setOut(p);
      exec(cmd, args).execute();
      p.close();
    } finally {
      System.setOut(prev);
    }

    return b.toString();
  }
  /** tests the demuxing of output streams in a multithreaded situation */
  public void testDemux() {
    Project p = getProject();
    p.addTaskDefinition("demuxtest", DemuxOutputTask.class);
    PrintStream out = System.out;
    PrintStream err = System.err;
    System.setOut(new PrintStream(new DemuxOutputStream(p, false)));
    System.setErr(new PrintStream(new DemuxOutputStream(p, true)));

    try {
      p.executeTarget("testDemux");
    } finally {
      System.setOut(out);
      System.setErr(err);
    }
  }
  @Test
  public void testPrintLevel() {
    String treeOut = "50 30 55 12 33 52 ";
    AvlTree<Integer> tree = new AvlTree<Integer>();
    tree.insert(50).insert(55).insert(30).insert(33).insert(12).insert(52);

    ByteArrayOutputStream outContent = new ByteArrayOutputStream();
    ByteArrayOutputStream errContent = new ByteArrayOutputStream();
    System.setOut(new PrintStream(outContent));
    System.setErr(new PrintStream(errContent));
    tree.printTreeLevel();
    assertEquals(treeOut, outContent.toString());
    System.setOut(null);
    System.setErr(null);
  }