1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package android.longevity.core.scheduler; 17 18 import static com.google.common.truth.Truth.assertThat; 19 import static org.mockito.Mockito.when; 20 21 import java.util.ArrayList; 22 import java.util.HashMap; 23 import java.util.List; 24 import java.util.Map; 25 import java.util.function.Function; 26 import java.util.stream.Collectors; 27 import java.util.stream.IntStream; 28 29 import org.junit.Test; 30 import org.junit.runner.Description; 31 import org.junit.runner.Runner; 32 import org.junit.runner.RunWith; 33 import org.junit.runners.JUnit4; 34 35 import org.mockito.Mockito; 36 37 /** 38 * Unit test the logic for {@link Iterate} 39 */ 40 @RunWith(JUnit4.class) 41 public class IterateTest { 42 private static final int NUM_TESTS = 10; 43 private static final int TEST_ITERATIONS = 25; 44 45 private Iterate mIterate = new Iterate(); 46 47 /** 48 * Unit test the iteration count is respected. 49 */ 50 @Test 51 public void testIterationsRespected() { 52 // Construct argument bundle. 53 Map<String, String> args = new HashMap(); 54 args.put(Iterate.OPTION_NAME, String.valueOf(TEST_ITERATIONS)); 55 // Construct input runners. 56 List<Runner> input = new ArrayList<>(); 57 IntStream.range(1, NUM_TESTS).forEach(i -> input.add(getMockRunner(i))); 58 // Apply iterator on arguments and runners. 59 List<Runner> output = mIterate.apply(args, input); 60 // Count occurrences of test descriptions into a map. 61 Map<String, Long> countMap = output.stream() 62 .map(Runner::getDescription) 63 .map(Description::getDisplayName) 64 .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); 65 // Ensure all test descriptions have N entries. 66 boolean respected = countMap.entrySet().stream() 67 .noneMatch(entry -> (entry.getValue() != TEST_ITERATIONS)); 68 assertThat(respected).isTrue(); 69 } 70 71 private Runner getMockRunner (int id) { 72 Runner result = Mockito.mock(Runner.class); 73 Description desc = Mockito.mock(Description.class); 74 when(result.getDescription()).thenReturn(desc); 75 when(desc.getDisplayName()).thenReturn(String.valueOf(id)); 76 return result; 77 } 78 } 79