Line data Source code
1 : // Copyright (C) 2019 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.testing; 16 : 17 : import static com.google.common.truth.Truth.assertWithMessage; 18 : 19 : import com.google.common.util.concurrent.ForwardingExecutorService; 20 : import com.google.common.util.concurrent.MoreExecutors; 21 : import java.util.concurrent.Callable; 22 : import java.util.concurrent.ExecutorService; 23 : import java.util.concurrent.Future; 24 : import java.util.concurrent.atomic.AtomicInteger; 25 : 26 : /** 27 : * Forwards all calls to a direct executor making it so that the submitted {@link Runnable}s run 28 : * synchronously. Holds a count of the number of tasks that were executed. 29 : */ 30 1 : public class AssertableExecutorService extends ForwardingExecutorService { 31 : 32 1 : private final ExecutorService delegate = MoreExecutors.newDirectExecutorService(); 33 1 : private final AtomicInteger numInteractions = new AtomicInteger(); 34 : 35 : @Override 36 : protected ExecutorService delegate() { 37 1 : return delegate; 38 : } 39 : 40 : @Override 41 : public <T> Future<T> submit(Callable<T> task) { 42 0 : numInteractions.incrementAndGet(); 43 0 : return super.submit(task); 44 : } 45 : 46 : @Override 47 : public Future<?> submit(Runnable task) { 48 1 : numInteractions.incrementAndGet(); 49 1 : return super.submit(task); 50 : } 51 : 52 : @Override 53 : public <T> Future<T> submit(Runnable task, T result) { 54 0 : numInteractions.incrementAndGet(); 55 0 : return super.submit(task, result); 56 : } 57 : 58 : /** Asserts and resets the number of executions this executor observed. */ 59 : public void assertInteractions(int expectedNumInteractions) { 60 1 : assertWithMessage("expectedRunnablesSubmittedOnExecutor") 61 1 : .that(numInteractions.get()) 62 1 : .isEqualTo(expectedNumInteractions); 63 1 : numInteractions.set(0); 64 1 : } 65 : }