001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase;
019
020import static org.junit.jupiter.api.Assertions.assertNotEquals;
021import static org.mockito.ArgumentMatchers.anyInt;
022import static org.mockito.Mockito.mock;
023import static org.mockito.Mockito.verify;
024import static org.mockito.Mockito.when;
025
026import java.util.Random;
027import org.apache.hadoop.hbase.testclassification.MiscTests;
028import org.apache.hadoop.hbase.testclassification.SmallTests;
029import org.junit.jupiter.api.Tag;
030import org.junit.jupiter.api.Test;
031import org.mockito.Mockito;
032import org.mockito.invocation.InvocationOnMock;
033import org.mockito.stubbing.Answer;
034
035@Tag(MiscTests.TAG)
036@Tag(SmallTests.TAG)
037public class TestPortAllocator {
038
039  @Test
040  public void testResolvePortConflict() throws Exception {
041    // raises port conflict between 1st call and 2nd call of randomPort() by mocking Random object
042    Random random = mock(Random.class);
043    when(random.nextInt(anyInt())).thenAnswer(new Answer<Integer>() {
044      int[] numbers = { 1, 1, 2 };
045      int count = 0;
046
047      @Override
048      public Integer answer(InvocationOnMock invocation) {
049        int ret = numbers[count];
050        count++;
051        return ret;
052      }
053    });
054
055    HBaseTestingUtil.PortAllocator.AvailablePortChecker portChecker =
056      mock(HBaseTestingUtil.PortAllocator.AvailablePortChecker.class);
057    when(portChecker.available(anyInt())).thenReturn(true);
058
059    HBaseTestingUtil.PortAllocator portAllocator =
060      new HBaseTestingUtil.PortAllocator(random, portChecker);
061
062    int port1 = portAllocator.randomFreePort();
063    int port2 = portAllocator.randomFreePort();
064    assertNotEquals(port1, port2);
065    verify(random, Mockito.times(3)).nextInt(anyInt());
066  }
067}