### Question:
PortAllocator { public Map<String, Integer> allocate(final Map<String, PortMapping> ports, final Set<Integer> used) { return allocate0(ports, Sets.newHashSet(used)); } PortAllocator(final int start, final int end); Map<String, Integer> allocate(final Map<String, PortMapping> ports,
                                       final Set<Integer> used);  }### Answer:
@Test public void testAllocate() throws Exception { final PortAllocator sut = new PortAllocator(20000, 20010); final Map<String, PortMapping> mapping = ImmutableMap.of("p1", PortMapping.of(17), "p2", PortMapping.of(18, 18)); final Set<Integer> used = ImmutableSet.of(10, 11); final Map<String, Integer> allocation = sut.allocate(mapping, used); assertThat(allocation, hasEntry(is("p1"), allOf(greaterThanOrEqualTo(20000), lessThanOrEqualTo(20010)))); assertThat(allocation, hasEntry("p2", 18)); }
@Test public void testAllocatePortsWithDifferentProtocols() throws Exception { final PortAllocator sut = new PortAllocator(20000, 20010); final Map<String, PortMapping> mapping = ImmutableMap.of( "p1", PortMapping.of(17), "p-tcp", PortMapping.of(18, 18), "p-udp", PortMapping.of(18, 18)); final Set<Integer> used = ImmutableSet.of(10, 11); final Map<String, Integer> allocation = sut.allocate(mapping, used); assertThat( allocation, hasEntry(is("p1"), allOf(greaterThanOrEqualTo(20000), lessThanOrEqualTo(20010)))); assertThat(allocation, hasEntry("p-tcp", 18)); assertThat(allocation, hasEntry("p-udp", 18)); }
@Test public void testInsufficientPortsFail1() throws Exception { final PortAllocator sut = new PortAllocator(10, 11); final Map<String, PortMapping> mapping = ImmutableMap.of("p1", PortMapping.of(17), "p2", PortMapping.of(18, 18)); final Set<Integer> used = ImmutableSet.of(10, 11); final Map<String, Integer> allocation = sut.allocate(mapping, used); assertNull(allocation); }
@Test public void testInsufficientPortsFail2() throws Exception { final PortAllocator sut = new PortAllocator(10, 11); final Map<String, PortMapping> mapping = ImmutableMap.of("p1", PortMapping.of(1), "p2", PortMapping.of(2), "p3", PortMapping.of(4), "p4", PortMapping.of(18, 18)); final Set<Integer> used = ImmutableSet.of(); final Map<String, Integer> allocation = sut.allocate(mapping, used); assertNull(allocation); }