|
| 1 | +/* |
| 2 | + * Copyright The OpenTelemetry Authors |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +package io.opentelemetry.javaagent.muzzle; |
| 7 | + |
| 8 | +import static org.assertj.core.api.Assertions.assertThat; |
| 9 | + |
| 10 | +import io.opentelemetry.javaagent.IntegrationTestUtils; |
| 11 | +import java.lang.reflect.Field; |
| 12 | +import java.lang.reflect.Method; |
| 13 | +import java.util.ArrayList; |
| 14 | +import java.util.List; |
| 15 | +import java.util.ServiceLoader; |
| 16 | +import org.junit.jupiter.api.Test; |
| 17 | + |
| 18 | +class MuzzleBytecodeTransformTest { |
| 19 | + |
| 20 | + @Test |
| 21 | + void muzzleFieldsAddedToAllInstrumentation() throws Exception { |
| 22 | + List<Class<?>> unMuzzledClasses = new ArrayList<>(); |
| 23 | + List<Class<?>> nonLazyFields = new ArrayList<>(); |
| 24 | + List<Class<?>> unInitFields = new ArrayList<>(); |
| 25 | + |
| 26 | + Class<?> instrumentationModuleClass = IntegrationTestUtils.getAgentClassLoader() |
| 27 | + .loadClass("io.opentelemetry.javaagent.extension.instrumentation.InstrumentationModule"); |
| 28 | + |
| 29 | + for (Object instrumenter : ServiceLoader.load(instrumentationModuleClass)) { |
| 30 | + if (!instrumentationModuleClass.isAssignableFrom(instrumenter.getClass())) { |
| 31 | + // muzzle only applies to default instrumenters |
| 32 | + continue; |
| 33 | + } |
| 34 | + |
| 35 | + Field f = null; |
| 36 | + Method m = null; |
| 37 | + try { |
| 38 | + f = instrumenter.getClass().getDeclaredField("muzzleReferences"); |
| 39 | + f.setAccessible(true); |
| 40 | + if (f.get(instrumenter) != null) { |
| 41 | + nonLazyFields.add(instrumenter.getClass()); |
| 42 | + } |
| 43 | + |
| 44 | + m = instrumenter.getClass().getDeclaredMethod("getMuzzleReferences"); |
| 45 | + m.setAccessible(true); |
| 46 | + m.invoke(instrumenter); |
| 47 | + |
| 48 | + if (f.get(instrumenter) == null) { |
| 49 | + unInitFields.add(instrumenter.getClass()); |
| 50 | + } |
| 51 | + } catch (NoSuchFieldException | NoSuchMethodException e) { |
| 52 | + unMuzzledClasses.add(instrumenter.getClass()); |
| 53 | + } finally { |
| 54 | + if (f != null) { |
| 55 | + f.setAccessible(false); |
| 56 | + } |
| 57 | + if (m != null) { |
| 58 | + m.setAccessible(false); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + assertThat(unMuzzledClasses).isEmpty(); |
| 64 | + assertThat(nonLazyFields).isEmpty(); |
| 65 | + assertThat(unInitFields).isEmpty(); |
| 66 | + } |
| 67 | +} |
0 commit comments