|
| 1 | +/* |
| 2 | + * Copyright 2026 The gRPC Authors |
| 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 | + |
| 17 | +package io.grpc.internal; |
| 18 | + |
| 19 | +import java.util.ArrayDeque; |
| 20 | +import java.util.Deque; |
| 21 | +import org.junit.rules.ExternalResource; |
| 22 | + |
| 23 | +/** |
| 24 | + * A {@link org.junit.rules.TestRule} that lets you set one or more feature flags just for |
| 25 | + * the duration of the current test case. |
| 26 | + * |
| 27 | + * <p>Flags and other global variables must be reset to ensure no state leaks across tests. |
| 28 | + */ |
| 29 | +public final class FlagResetRule extends ExternalResource { |
| 30 | + |
| 31 | + /** A functional interface representing a standard gRPC feature flag setter. */ |
| 32 | + public interface SetterMethod<T> { |
| 33 | + /** Sets a flag for testing and returns its previous value. */ |
| 34 | + T set(T val); |
| 35 | + } |
| 36 | + |
| 37 | + private final Deque<Runnable> toRunAfter = new ArrayDeque<>(); |
| 38 | + |
| 39 | + /** |
| 40 | + * Sets a global feature flag to 'value' using 'setter' and arranges for its previous value to be |
| 41 | + * unconditionally restored when the test completes. |
| 42 | + */ |
| 43 | + public <T> void setFlagForTest(SetterMethod<T> setter, T value) { |
| 44 | + final T oldValue = setter.set(value); |
| 45 | + toRunAfter.push(() -> setter.set(oldValue)); |
| 46 | + } |
| 47 | + |
| 48 | + @Override |
| 49 | + protected void after() { |
| 50 | + RuntimeException toThrow = null; |
| 51 | + while (!toRunAfter.isEmpty()) { |
| 52 | + try { |
| 53 | + toRunAfter.pop().run(); |
| 54 | + } catch (RuntimeException e) { |
| 55 | + if (toThrow == null) { |
| 56 | + toThrow = e; |
| 57 | + } else { |
| 58 | + toThrow.addSuppressed(e); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + if (toThrow != null) { |
| 63 | + throw toThrow; |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments