summaryrefslogtreecommitdiffstats
path: root/src/test/java/com/beust/jcommander/internal/DefaultConsoleTest.java
blob: e1014391e962487cc26bb1f0fbd1e481dbda43d1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.beust.jcommander.internal;

import java.io.IOException;
import java.io.InputStream;

import org.testng.Assert;
import org.testng.annotations.Test;

@Test
public class DefaultConsoleTest {
  public void readPasswordCanBeCalledMultipleTimes() {
    final InputStream inBackup = System.in;
    try {
      final StringInputStream in = new StringInputStream();
      System.setIn(in);
      final Console console = new DefaultConsole();

      in.setData("password1\n");
      char[] password = console.readPassword(false);
      Assert.assertEquals(password, "password1".toCharArray());
      Assert.assertFalse(in.isClosedCalled(), "System.in stream shouldn't be closed");

      in.setData("password2\n");
      password = console.readPassword(false);
      Assert.assertEquals(password, "password2".toCharArray());
      Assert.assertFalse(in.isClosedCalled(), "System.in stream shouldn't be closed");
    } finally {
      System.setIn(inBackup);
    }
  }

  private static class StringInputStream extends InputStream {
    private byte[] data = new byte[0];
    private int offset = 0;
    private boolean closedCalled;

    StringInputStream() {
      super();
    }

    void setData(final String strData) {
      data = strData.getBytes();
      offset = 0;
    }

    boolean isClosedCalled() {
      return closedCalled;
    }

    @Override
    public int read() throws IOException {
      if (offset >= data.length) {
        return -1;
      }
      return 0xFFFF & data[offset++];
    }

    @Override
    public void close() throws IOException {
      closedCalled = true;
      super.close();
    }
  }
}