Line data Source code
1 : // Copyright (C) 2021 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.acceptance; 16 : 17 : import com.google.gerrit.metrics.Counter0; 18 : import com.google.gerrit.metrics.Description; 19 : import com.google.gerrit.metrics.DisabledMetricMaker; 20 : import com.google.inject.Singleton; 21 : import java.util.concurrent.ConcurrentHashMap; 22 : import org.apache.commons.lang3.mutable.MutableLong; 23 : 24 : /** 25 : * {@link com.google.gerrit.metrics.MetricMaker} to be bound in tests. 26 : * 27 : * <p>Records how often {@link Counter0} metrics are invoked. Metrics of other types are not 28 : * recorded. 29 : * 30 : * <p>Allows test to check how much a {@link Counter0} metrics is increased by an operation. 31 : * 32 : * <p>Example: 33 : * 34 : * <pre> 35 : * public class MyTest extends AbstractDaemonTest { 36 : * {@literal @}Inject private TestMetricMaker testMetricMaker; 37 : * 38 : * ... 39 : * 40 : * {@literal @}Test 41 : * public void testFoo() throws Exception { 42 : * testMetricMaker.reset(); 43 : * doSomething(); 44 : * assertThat(testMetricMaker.getCount("foo/bar_count")).isEqualsTo(1); 45 : * } 46 : * } 47 : * </pre> 48 : */ 49 : @Singleton 50 132 : public class TestMetricMaker extends DisabledMetricMaker { 51 132 : private final ConcurrentHashMap<String, MutableLong> counts = new ConcurrentHashMap<>(); 52 : 53 : public long getCount(String counter0Name) { 54 0 : return get(counter0Name).longValue(); 55 : } 56 : 57 : public void reset() { 58 0 : counts.clear(); 59 0 : } 60 : 61 : private MutableLong get(String counter0Name) { 62 132 : return counts.computeIfAbsent(counter0Name, name -> new MutableLong(0)); 63 : } 64 : 65 : @Override 66 : public Counter0 newCounter(String name, Description desc) { 67 132 : return new Counter0() { 68 : @Override 69 : public void incrementBy(long value) { 70 132 : get(name).add(value); 71 132 : } 72 : 73 : @Override 74 0 : public void remove() {} 75 : }; 76 : } 77 : }