/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.provisionr.core.activities; import org.apache.provisionr.api.pool.Machine; import org.apache.provisionr.test.ProcessVariablesCollector; import java.io.IOException; import java.net.ServerSocket; import org.activiti.engine.delegate.DelegateExecution; import org.activiti.engine.delegate.JavaDelegate; import static org.fest.assertions.api.Assertions.assertThat; import org.junit.Test; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class IsMachinePortOpenTest { private static final String RESULT = "result"; @Test public void testWithRandomOpenPort() throws Exception { DelegateExecution execution = mock(DelegateExecution.class); when(execution.getVariable(eq(IsMachinePortOpen.MACHINE))) .thenReturn(Machine.builder().localhost().createMachine()); ProcessVariablesCollector collector = new ProcessVariablesCollector(); collector.install(execution); ServerSocket socket = null; try { socket = new ServerSocket(0); JavaDelegate delegate = new IsMachinePortOpen(RESULT, socket.getLocalPort()); delegate.execute(execution); assertThat((Boolean) collector.getVariable(RESULT)).isTrue(); } finally { if (socket != null) { socket.close(); } } } @Test public void testWithRandomClosedPort() throws Exception { DelegateExecution execution = mock(DelegateExecution.class); when(execution.getVariable(eq(IsMachinePortOpen.MACHINE))) .thenReturn(Machine.builder().localhost().createMachine()); ProcessVariablesCollector collector = new ProcessVariablesCollector(); collector.install(execution); JavaDelegate delegate = new IsMachinePortOpen(RESULT, findRandomNotUsedPort()); delegate.execute(execution); assertThat((Boolean) collector.getVariable(RESULT)).isFalse(); } private int findRandomNotUsedPort() throws IOException { ServerSocket socket = null; try { socket = new ServerSocket(0); return socket.getLocalPort(); } finally { if (socket != null) { socket.close(); } } } }