1package com.beust.jcommander.internal;
2
3import java.io.IOException;
4import java.io.InputStream;
5
6import org.testng.Assert;
7import org.testng.annotations.Test;
8
9@Test
10public class DefaultConsoleTest {
11  public void readPasswordCanBeCalledMultipleTimes() {
12    final InputStream inBackup = System.in;
13    try {
14      final StringInputStream in = new StringInputStream();
15      System.setIn(in);
16      final Console console = new DefaultConsole();
17
18      in.setData("password1\n");
19      char[] password = console.readPassword(false);
20      Assert.assertEquals(password, "password1".toCharArray());
21      Assert.assertFalse(in.isClosedCalled(), "System.in stream shouldn't be closed");
22
23      in.setData("password2\n");
24      password = console.readPassword(false);
25      Assert.assertEquals(password, "password2".toCharArray());
26      Assert.assertFalse(in.isClosedCalled(), "System.in stream shouldn't be closed");
27    } finally {
28      System.setIn(inBackup);
29    }
30  }
31
32  private static class StringInputStream extends InputStream {
33    private byte[] data = new byte[0];
34    private int offset = 0;
35    private boolean closedCalled;
36
37    StringInputStream() {
38      super();
39    }
40
41    void setData(final String strData) {
42      data = strData.getBytes();
43      offset = 0;
44    }
45
46    boolean isClosedCalled() {
47      return closedCalled;
48    }
49
50    @Override
51    public int read() throws IOException {
52      if (offset >= data.length) {
53        return -1;
54      }
55      return 0xFFFF & data[offset++];
56    }
57
58    @Override
59    public void close() throws IOException {
60      closedCalled = true;
61      super.close();
62    }
63  }
64}
65