下面列出了怎么用org.mockito.internal.util.io.IOUtil的API类实例代码及写法,或者点击链接到github查看源代码。
@Before
public void startServer() throws IOException, TlsException {
tempConfigFilePath = "./target/TestHttpNotificationService-config.xml";
Files.deleteIfExists(Paths.get(tempConfigFilePath));
mockWebServer = new MockWebServer();
TlsConfiguration tlsConfiguration = new TlsConfiguration("./src/test/resources/keystore.jks", "passwordpassword", null, "JKS",
"./src/test/resources/truststore.jks", "passwordpassword", "JKS", CertificateUtils.getHighestCurrentSupportedTlsProtocolVersion());
final SSLContext sslContext = SslContextFactory.createSslContext(tlsConfiguration, SslContextFactory.ClientAuth.REQUIRED);
mockWebServer.useHttps(sslContext.getSocketFactory(), false);
String configFileOutput = CONFIGURATION_FILE_TEXT.replace("${test.server}", String.valueOf(mockWebServer.url("/")));
IOUtil.writeText(configFileOutput, new File(tempConfigFilePath));
}
@Test
public void testStartNotificationSucceedsNoKeystorePasswd() throws ParserConfigurationException, SAXException, IOException {
Logger notificationServiceLogger = (Logger) LoggerFactory.getLogger(NotificationServiceManager.class);
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
notificationServiceLogger.addAppender(listAppender);
String configFileOutput = CONFIGURATION_FILE_TEXT_NO_KEYSTORE_PASSWORD.replace("${test.server}", String.valueOf(mockWebServer.url("/")));
IOUtil.writeText(configFileOutput, new File(tempConfigFilePath));
NotificationServiceManager notificationServiceManager = new NotificationServiceManager();
notificationServiceManager.setMaxNotificationAttempts(1);
notificationServiceManager.loadNotificationServices(new File(tempConfigFilePath));
List<ILoggingEvent> logsList = listAppender.list;
boolean notificationServiceFailed = false;
for (ILoggingEvent logMessage : logsList) {
if (logMessage.getFormattedMessage().contains("is not valid for the following reasons")) {
notificationServiceFailed = true;
}
}
assertFalse(notificationServiceFailed);
}
@Test
public void testStartNotificationSucceedsNoKeyPasswd() throws ParserConfigurationException, SAXException, IOException {
Logger notificationServiceLogger = (Logger) LoggerFactory.getLogger(NotificationServiceManager.class);
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
notificationServiceLogger.addAppender(listAppender);
String configFileOutput = CONFIGURATION_FILE_TEXT_NO_KEY_PASSWORD.replace("${test.server}", String.valueOf(mockWebServer.url("/")));
IOUtil.writeText(configFileOutput, new File(tempConfigFilePath));
NotificationServiceManager notificationServiceManager = new NotificationServiceManager();
notificationServiceManager.setMaxNotificationAttempts(1);
notificationServiceManager.loadNotificationServices(new File(tempConfigFilePath));
List<ILoggingEvent> logsList = listAppender.list;
boolean notificationServiceFailed = false;
for (ILoggingEvent logMessage : logsList) {
if (logMessage.getFormattedMessage().contains("is not valid for the following reasons")) {
notificationServiceFailed = true;
}
}
assertFalse(notificationServiceFailed);
}
@Test
public void testStartNotificationFailsBlankKeystorePasswdCorrectKeypasswd() throws ParserConfigurationException, SAXException, IOException {
Logger notificationServiceLogger = (Logger) LoggerFactory.getLogger(NotificationServiceManager.class);
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
notificationServiceLogger.addAppender(listAppender);
String configFileOutput = CONFIGURATION_FILE_TEXT_BLANK_KEYSTORE_PASSWORD.replace("${test.server}", String.valueOf(mockWebServer.url("/")));
IOUtil.writeText(configFileOutput, new File(tempConfigFilePath));
NotificationServiceManager notificationServiceManager = new NotificationServiceManager();
notificationServiceManager.setMaxNotificationAttempts(1);
notificationServiceManager.loadNotificationServices(new File(tempConfigFilePath));
List<ILoggingEvent> logsList = listAppender.list;
boolean notificationServiceFailed = false;
for (ILoggingEvent logMessage : logsList) {
if (logMessage.getFormattedMessage().contains("'Keystore Password' validated against '' is invalid because Keystore Password cannot be empty")) {
notificationServiceFailed = true;
}
}
assertTrue(notificationServiceFailed);
}
@Test
public void testStartNotificationFailsCorrectKeystorePasswdBlankKeypasswd() throws ParserConfigurationException, SAXException, IOException {
Logger notificationServiceLogger = (Logger) LoggerFactory.getLogger(NotificationServiceManager.class);
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
notificationServiceLogger.addAppender(listAppender);
String configFileOutput = CONFIGURATION_FILE_TEXT_BLANK_KEY_PASSWORD.replace("${test.server}", String.valueOf(mockWebServer.url("/")));
IOUtil.writeText(configFileOutput, new File(tempConfigFilePath));
NotificationServiceManager notificationServiceManager = new NotificationServiceManager();
notificationServiceManager.setMaxNotificationAttempts(1);
notificationServiceManager.loadNotificationServices(new File(tempConfigFilePath));
List<ILoggingEvent> logsList = listAppender.list;
boolean notificationServiceFailed = false;
for (ILoggingEvent logMessage : logsList) {
if (logMessage.getFormattedMessage().contains("'Key Password' validated against '' is invalid because Key Password cannot be empty")) {
notificationServiceFailed = true;
}
}
assertTrue(notificationServiceFailed);
}
@Test
public void portDetect() throws UnknownHostException, IOException {
int port = NetUtil.findRandomAvailablePort(20000, 20100);
assertThat(port).isBetween(20000, 20100);
System.out.println("random port:" + port);
assertThat(NetUtil.isPortAvailable(port)).isTrue();
int port2 = NetUtil.findAvailablePortFrom(port);
assertThat(port2).isEqualTo(port);
int port3 = NetUtil.findRandomAvailablePort();
assertThat(port3).isBetween(NetUtil.PORT_RANGE_MIN, NetUtil.PORT_RANGE_MAX);
System.out.println("random port:" + port3);
// 尝试占住一个端口
ServerSocket serverSocket = null;
try {
serverSocket = ServerSocketFactory.getDefault().createServerSocket(port, 1,
InetAddress.getByName("localhost"));
assertThat(NetUtil.isPortAvailable(port)).isFalse();
int port4 = NetUtil.findAvailablePortFrom(port);
assertThat(port4).isEqualTo(port + 1);
try {
int port5 = NetUtil.findRandomAvailablePort(port, port);
fail("should fail before");
} catch (Throwable t) {
assertThat(t).isInstanceOf(IllegalStateException.class);
}
} finally {
IOUtil.close(serverSocket);
}
}
@Test
public void portDetect() throws UnknownHostException, IOException {
int port = NetUtil.findRandomAvailablePort(20000, 20100);
assertThat(port).isBetween(20000, 20100);
System.out.println("random port:" + port);
assertThat(NetUtil.isPortAvailable(port)).isTrue();
int port2 = NetUtil.findAvailablePortFrom(port);
assertThat(port2).isEqualTo(port);
int port3 = NetUtil.findRandomAvailablePort();
assertThat(port3).isBetween(NetUtil.PORT_RANGE_MIN, NetUtil.PORT_RANGE_MAX);
System.out.println("random port:" + port3);
// 尝试占住一个端口
ServerSocket serverSocket = null;
try {
serverSocket = ServerSocketFactory.getDefault().createServerSocket(port, 1,
InetAddress.getByName("localhost"));
assertThat(NetUtil.isPortAvailable(port)).isFalse();
int port4 = NetUtil.findAvailablePortFrom(port);
assertThat(port4).isEqualTo(port + 1);
try {
int port5 = NetUtil.findRandomAvailablePort(port, port);
fail("should fail before");
} catch (Throwable t) {
assertThat(t).isInstanceOf(IllegalStateException.class);
}
} finally {
IOUtil.close(serverSocket);
}
}
public void run() {
try {
try {
if (!cmd.hasOption(SILENT_OPTION)) {
System.out.printf("%sLoading schema from %s:%s%s", ANSI_RED, host, port, ANSI_RESET);
System.out.flush();
}
String cfids = cmd.getOptionValue(CFID_OPTION, "");
cluster = CassandraUtils.loadTablesFromRemote(host, port, cfids);
} finally {
System.out.print(ANSI_RESET);
}
for (String target : cmd.getArgs()) {
File targetFile = new File(target);
if (!targetFile.exists()) {
if (!cmd.hasOption(SILENT_OPTION)) {
System.out.print("\r" + ANSI_RESET + Strings.repeat(" ", 60) + "\r");
}
System.err.println("Non-existant target provided: " + target);
} else {
if (!cmd.hasOption(SILENT_OPTION)) {
System.out.print("\r" + ANSI_RESET + Strings.repeat(" ", 60) + "\r");
System.out.println("\u001B[1;34m" + targetFile.getAbsolutePath());
System.out.println(ANSI_CYAN + Strings.repeat("=", targetFile.getAbsolutePath().length()));
System.out.print(ANSI_RESET);
}
MutationReplayer replayer = null;
if (cmd.hasOption(REPLAY_OPTION)) {
replayer = new MutationReplayer(cluster);
}
walkMutations(targetFile, System.out, replayer);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtil.closeQuietly(cluster);
}
}
@Before
public void createCredentials() throws IOException {
File tempDir = tempFolder.newFolder();
File clientJson = new File(tempDir, "client.json");
IOUtil.writeText("{\"client_id\":\"abcdefg \",\"client_secret\":\"geheim\"}", clientJson);
File userJson = new File(tempDir, "user.json");
IOUtil.writeText("{\"application_username\":\"klaus \",\"application_password\":\"geheim\"}", userJson);
System.setProperty(CREDENTIALS_DIR, tempDir.getAbsolutePath());
}
@Override
public void traverse() {
String annotations = makeVariantAnnotations().stream()
.map(a -> a.getClass().getSimpleName())
.collect(Collectors.joining("\n"));
IOUtil.writeText(annotations, new File(output));
}
@Override
public void traverse() {
String readFilters = getCommandLineParser()
.getPluginDescriptor(GATKReadFilterPluginDescriptor.class)
.getResolvedInstances()
.stream()
.map(a -> a.getClass().getSimpleName())
.collect(Collectors.joining("\n"));
IOUtil.writeText(readFilters, new File(output));
}
@BeforeClass
public static void startServer() throws IOException {
tempConfigFilePath = "./target/TestHttpNotificationService-config.xml";
Files.deleteIfExists(Paths.get(tempConfigFilePath));
mockWebServer = new MockWebServer();
String configFileOutput = CONFIGURATION_FILE_TEXT.replace("${test.server}", String.valueOf(mockWebServer.url("/")));
IOUtil.writeText(configFileOutput, new File(tempConfigFilePath));
}
@Override
public BElement deserialize(InputStream in) {
return BElement.ofAny(IOUtil.readLines(in).iterator().next());
}
@Override
public BElement deserialize(InputStream in) {
return BObject.of("name", IOUtil.readLines(in).iterator().next());
}
@Override
public BElement deserialize(InputStream in) {
return BElement.ofAny(IOUtil.readLines(in).iterator().next());
}
@Override
public BElement deserialize(InputStream in) {
return BReference.of(new SimplePojo(IOUtil.readLines(in).iterator().next()));
}
@Test
public void runAccessTokenRefresher() throws IOException, InterruptedException {
File tempDir = tempFolder.newFolder();
File clientJson = new File(tempDir, "client.json");
IOUtil.writeText("{\"client_id\":\"abcdefg \",\"client_secret\":\"geheim\"}", clientJson);
File userJson = new File(tempDir, "user.json");
IOUtil.writeText("{\"application_username\":\"klaus \",\"application_password\":\"geheim\"}", userJson);
System.setProperty(CREDENTIALS_DIR, tempDir.getAbsolutePath());
ClientCredentialsProvider ccp = new JsonFileBackedClientCredentialsProvider(clientJson);
UserCredentialsProvider ucp = new JsonFileBackedUserCredentialsProvider(userJson);
HttpProviderFactory hpf = Mockito.mock(HttpProviderFactory.class);
AccessTokensBuilder accessTokenBuilder = Tokens.createAccessTokensWithUri(uri)
.usingClientCredentialsProvider(ccp)
.usingUserCredentialsProvider(ucp)
.usingHttpProviderFactory(hpf)
.manageToken("TR_TEST")
.done()
.manageToken("TR_TEST_1")
.done()
.manageToken("TR_TEST_2")
.done();
HttpProvider httpProvider = Mockito.mock(HttpProvider.class);
Mockito.when(hpf.create(Mockito.any(ClientCredentials.class), Mockito.any(UserCredentials.class),
Mockito.any(URI.class), Mockito.any(HttpConfig.class))).thenReturn(httpProvider);
Mockito.when(httpProvider.createToken(Mockito.any(AccessTokenConfiguration.class)))
.thenReturn(new AccessToken("123456789", "BEARER", 2, new Date(System.currentTimeMillis() + 15000)))
.thenThrow(new RuntimeException("DO NOT FAIL ALL CONFIGURATIONS"))
.thenReturn(new AccessToken("123456789", "BEARER", 2, new Date(System.currentTimeMillis() + 15000)))
.thenReturn(new AccessToken("123456789", "BEARER", 2, new Date(System.currentTimeMillis() + 15000)))
.thenThrow(new RuntimeException("DO NOT FAIL ALL CONFIGURATIONS"))
.thenReturn(new AccessToken("123456789", "BEARER", 2, new Date(System.currentTimeMillis() + 15000)));
accessTokens = accessTokenBuilder.start();
Assertions.assertThat(accessTokens).isNotNull();
TimeUnit.SECONDS.sleep(30);
Mockito.verify(httpProvider, Mockito.atLeastOnce()).createToken(Mockito.any(AccessTokenConfiguration.class));
}