|
| 1 | +/* |
| 2 | + * Copyright 2012-2024 the original author or 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 | + * https://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 org.springframework.boot.testcontainers.lifecycle; |
| 18 | + |
| 19 | +import java.lang.reflect.InaccessibleObjectException; |
| 20 | +import java.util.concurrent.atomic.AtomicLong; |
| 21 | + |
| 22 | +import org.junit.jupiter.api.extension.AfterEachCallback; |
| 23 | +import org.junit.jupiter.api.extension.BeforeEachCallback; |
| 24 | +import org.junit.jupiter.api.extension.ExtensionContext; |
| 25 | +import org.testcontainers.lifecycle.Startables; |
| 26 | + |
| 27 | +import org.springframework.test.util.ReflectionTestUtils; |
| 28 | + |
| 29 | +/** |
| 30 | + * JUnit extension used by reset startables. |
| 31 | + * |
| 32 | + * @author Phillip Webb |
| 33 | + */ |
| 34 | +class ResetStartablesExtension implements BeforeEachCallback, AfterEachCallback { |
| 35 | + |
| 36 | + @Override |
| 37 | + public void afterEach(ExtensionContext context) throws Exception { |
| 38 | + reset(); |
| 39 | + } |
| 40 | + |
| 41 | + @Override |
| 42 | + public void beforeEach(ExtensionContext context) throws Exception { |
| 43 | + reset(); |
| 44 | + } |
| 45 | + |
| 46 | + private void reset() { |
| 47 | + try { |
| 48 | + Object executor = ReflectionTestUtils.getField(Startables.class, "EXECUTOR"); |
| 49 | + Object threadFactory = ReflectionTestUtils.getField(executor, "threadFactory"); |
| 50 | + AtomicLong counter = (AtomicLong) ReflectionTestUtils.getField(threadFactory, "COUNTER"); |
| 51 | + counter.set(0); |
| 52 | + } |
| 53 | + catch (InaccessibleObjectException ex) { |
| 54 | + throw new IllegalStateException( |
| 55 | + "Unable to reset field. Please run with '--add-opens=java.base/java.util.concurrent=ALL-UNNAMED'", |
| 56 | + ex); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | +} |
0 commit comments