This is an automated email from the ASF dual-hosted git repository.
garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-lang.git
The following commit(s) were added to refs/heads/master by this push:
new 8801ac812 Add reusable JUnit context class loader extension
8801ac812 is described below
commit 8801ac812b52f40a01061cb97b128f67dc03495b
Author: Gary Gregory <[email protected]>
AuthorDate: Sun Nov 15 16:52:52 2026 -0500
Add reusable JUnit context class loader extension
Support constructor-configured and per-test class loaders, restoring the
original loader after each test, including null loaders.
Refactor SerializationUtilsTest to use the extension and add lifecycle
tests for loader configuration and restoration.
Assisted-By: OpenAI Codex
---
.../commons/lang3/SerializationUtilsTest.java | 121 ++++++++++-----------
.../lang3/junit/ContextClassLoaderExtension.java | 80 ++++++++++++++
.../junit/ContextClassLoaderExtensionTest.java | 92 ++++++++++++++++
3 files changed, 229 insertions(+), 64 deletions(-)
diff --git a/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
b/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
index cd64055ac..4666f8a93 100644
--- a/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
@@ -54,9 +54,11 @@
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
+import org.apache.commons.lang3.junit.ContextClassLoaderExtension;
import org.apache.commons.lang3.reflect.testbed.Bar;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
@@ -125,6 +127,9 @@ public static byte[] replaceLastInt(final byte[] src, final
int from, final int
return null;
}
+ @RegisterExtension
+ final ContextClassLoaderExtension contextClassLoader = new
ContextClassLoaderExtension();
+
private String iString;
private Integer iInteger;
@@ -167,50 +172,6 @@ void testCloneNull() {
assertNull(test);
}
- @ParameterizedTest
- @ValueSource(strings = { "org.apache.commons.lang3.reflect.testbed.Bar",
"org.apache.commons.lang3.SerializableSupplier" })
- void testCloneProxyWithCustomClassLoader(final String interfaceName)
throws Exception {
- try (URLClassLoader loader = new URLClassLoader(new URL[] {
getClass().getProtectionDomain().getCodeSource().getLocation() }, null)) {
- final Class<?> proxyInterface = Class.forName(interfaceName,
false, loader);
- final Serializable proxy = (Serializable)
Proxy.newProxyInstance(loader, new Class<?>[] { proxyInterface }, new
SerializableInvocationHandler());
- final Serializable clone = SerializationUtils.clone(proxy);
- assertNotSame(proxy, clone);
- assertSame(proxy.getClass(), clone.getClass());
- assertTrue(proxyInterface.isInstance(clone));
- assertNotSame(Proxy.getInvocationHandler(proxy),
Proxy.getInvocationHandler(clone));
- assertEquals("test", clone.toString());
- }
- }
-
- @ParameterizedTest
- @ValueSource(strings = { "org.apache.commons.lang3.reflect.testbed.Bar",
"org.apache.commons.lang3.SerializableSupplier" })
- void testCloneProxyWithContextClassLoader(final String interfaceName)
throws Exception {
- final Thread thread = Thread.currentThread();
- final ClassLoader originalLoader = thread.getContextClassLoader();
- try (URLClassLoader loader = new URLClassLoader(new URL[] {
getClass().getProtectionDomain().getCodeSource().getLocation() }, null)) {
- final Class<?> proxyInterface = Class.forName(interfaceName,
false, loader);
- final Serializable proxy = (Serializable)
Proxy.newProxyInstance(loader, new Class<?>[] { proxyInterface }, new
SerializableInvocationHandler());
- final ArrayList<Serializable> holder = new ArrayList<>();
- holder.add(proxy);
- thread.setContextClassLoader(loader);
- final Serializable clone = SerializationUtils.clone(holder).get(0);
- assertNotSame(proxy, clone);
- assertSame(proxy.getClass(), clone.getClass());
- assertEquals("test", clone.toString());
- } finally {
- thread.setContextClassLoader(originalLoader);
- }
- }
-
- @Test
- void testCloneProxyWithDefaultClassLoader() {
- final Serializable proxy = (Serializable)
Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] {
SerializableSupplier.class },
- new SerializableInvocationHandler());
- final SerializableSupplier<?> clone = (SerializableSupplier<?>)
SerializationUtils.clone(proxy);
- assertNotSame(proxy, clone);
- assertEquals("test", clone.get());
- }
-
@ParameterizedTest
@ValueSource(strings = { "org.apache.commons.lang3.reflect.testbed.Bar",
"org.apache.commons.lang3.SerializableSupplier" })
void testCloneProxiesFromDifferentClassLoaders(final String interfaceName)
throws Exception {
@@ -245,8 +206,6 @@ void testCloneProxyDoesNotLookUpInterfaces() throws
Exception {
final int[] interfaceLookups = { 0 };
final URL[] urls = {
getClass().getProtectionDomain().getCodeSource().getLocation() };
final ClassLoader applicationLoader = getClass().getClassLoader();
- final Thread thread = Thread.currentThread();
- final ClassLoader originalLoader = thread.getContextClassLoader();
try (URLClassLoader loader = new URLClassLoader(urls,
applicationLoader) {
@Override
protected Class<?> loadClass(final String name, final boolean
resolve) throws ClassNotFoundException {
@@ -271,18 +230,66 @@ protected Class<?> loadClass(final String name, final
boolean resolve) throws Cl
new SerializableInvocationHandler());
final Class<?> holderClass =
Class.forName(ProxyHolder.class.getName(), true, loader);
final Serializable holder = (Serializable)
holderClass.getConstructor(Serializable.class).newInstance(proxy);
- thread.setContextClassLoader(applicationLoader);
+ contextClassLoader.setContextClassLoader(applicationLoader);
final Serializable clone = SerializationUtils.clone(holder);
final Object clonedProxy =
holderClass.getField("value").get(clone);
assertSame(proxy.getClass(), clonedProxy.getClass());
assertNotSame(proxy, clonedProxy);
assertEquals("test", clonedProxy.toString());
assertEquals(0, interfaceLookups[0]);
- } finally {
- thread.setContextClassLoader(originalLoader);
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = { "org.apache.commons.lang3.reflect.testbed.Bar",
"org.apache.commons.lang3.SerializableSupplier" })
+ void testCloneProxyWithContextClassLoader(final String interfaceName)
throws Exception {
+ try (URLClassLoader loader = new URLClassLoader(new URL[] {
getClass().getProtectionDomain().getCodeSource().getLocation() }, null)) {
+ final Class<?> proxyInterface = Class.forName(interfaceName,
false, loader);
+ final Serializable proxy = (Serializable)
Proxy.newProxyInstance(loader, new Class<?>[] { proxyInterface }, new
SerializableInvocationHandler());
+ final ArrayList<Serializable> holder = new ArrayList<>();
+ holder.add(proxy);
+ contextClassLoader.setContextClassLoader(loader);
+ final Serializable clone = SerializationUtils.clone(holder).get(0);
+ assertNotSame(proxy, clone);
+ assertSame(proxy.getClass(), clone.getClass());
+ assertEquals("test", clone.toString());
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = { "org.apache.commons.lang3.reflect.testbed.Bar",
"org.apache.commons.lang3.SerializableSupplier" })
+ void testCloneProxyWithCustomClassLoader(final String interfaceName)
throws Exception {
+ try (URLClassLoader loader = new URLClassLoader(new URL[] {
getClass().getProtectionDomain().getCodeSource().getLocation() }, null)) {
+ final Class<?> proxyInterface = Class.forName(interfaceName,
false, loader);
+ final Serializable proxy = (Serializable)
Proxy.newProxyInstance(loader, new Class<?>[] { proxyInterface }, new
SerializableInvocationHandler());
+ final Serializable clone = SerializationUtils.clone(proxy);
+ assertNotSame(proxy, clone);
+ assertSame(proxy.getClass(), clone.getClass());
+ assertTrue(proxyInterface.isInstance(clone));
+ assertNotSame(Proxy.getInvocationHandler(proxy),
Proxy.getInvocationHandler(clone));
+ assertEquals("test", clone.toString());
}
}
+ @Test
+ void testCloneProxyWithDefaultClassLoader() {
+ final Serializable proxy = (Serializable)
Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] {
SerializableSupplier.class },
+ new SerializableInvocationHandler());
+ final SerializableSupplier<?> clone = (SerializableSupplier<?>)
SerializationUtils.clone(proxy);
+ assertNotSame(proxy, clone);
+ assertEquals("test", clone.get());
+ }
+
+ @Test
+ void testCloneProxyWithNoInterfaces() {
+ final Serializable proxy = (Serializable)
Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[0], new
SerializableInvocationHandler());
+ final Serializable clone = SerializationUtils.clone(proxy);
+ assertNotSame(proxy, clone);
+ assertSame(proxy.getClass(), clone.getClass());
+ assertNotSame(Proxy.getInvocationHandler(proxy),
Proxy.getInvocationHandler(clone));
+ assertEquals("test", clone.toString());
+ }
+
@Test
void testCloneProxyWithPluginOnlyInterface(@TempDir final Path tempDir)
throws Exception {
final String interfaceName = "plugin.CloneInterface";
@@ -294,10 +301,8 @@ void testCloneProxyWithPluginOnlyInterface(@TempDir final
Path tempDir) throws E
assertEquals(0, compiler.run(null, diagnostics, diagnostics, "-d",
tempDir.toString(), source.toString()),
diagnostics.toString(StandardCharsets.UTF_8.name()));
final ClassLoader applicationLoader = getClass().getClassLoader();
- final Thread thread = Thread.currentThread();
- final ClassLoader originalLoader = thread.getContextClassLoader();
try (URLClassLoader loader = new URLClassLoader(new URL[] {
tempDir.toUri().toURL() }, null)) {
- thread.setContextClassLoader(applicationLoader);
+ contextClassLoader.setContextClassLoader(applicationLoader);
// Neither the application loader nor the context loader can
resolve this interface by name.
assertThrows(ClassNotFoundException.class, () ->
Class.forName(interfaceName, false, applicationLoader));
final Class<?> proxyInterface = Class.forName(interfaceName,
false, loader);
@@ -308,8 +313,6 @@ void testCloneProxyWithPluginOnlyInterface(@TempDir final
Path tempDir) throws E
assertTrue(proxyInterface.isInstance(clone));
assertNotSame(Proxy.getInvocationHandler(proxy),
Proxy.getInvocationHandler(clone));
assertEquals("test",
proxyInterface.getMethod("value").invoke(clone));
- } finally {
- thread.setContextClassLoader(originalLoader);
}
}
@@ -323,16 +326,6 @@ void testCloneProxyWithPublicInterfaces() {
assertEquals("test", clone.get());
}
- @Test
- void testCloneProxyWithNoInterfaces() {
- final Serializable proxy = (Serializable)
Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[0], new
SerializableInvocationHandler());
- final Serializable clone = SerializationUtils.clone(proxy);
- assertNotSame(proxy, clone);
- assertSame(proxy.getClass(), clone.getClass());
- assertNotSame(Proxy.getInvocationHandler(proxy),
Proxy.getInvocationHandler(clone));
- assertEquals("test", clone.toString());
- }
-
@Test
void testCloneSerializableSupplier() {
final SerializableSupplier<String> supplier = () -> "test";
diff --git
a/src/test/java/org/apache/commons/lang3/junit/ContextClassLoaderExtension.java
b/src/test/java/org/apache/commons/lang3/junit/ContextClassLoaderExtension.java
new file mode 100644
index 000000000..54456fd89
--- /dev/null
+++
b/src/test/java/org/apache/commons/lang3/junit/ContextClassLoaderExtension.java
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.lang3.junit;
+
+import org.junit.jupiter.api.extension.AfterEachCallback;
+import org.junit.jupiter.api.extension.BeforeEachCallback;
+import org.junit.jupiter.api.extension.ExtensionContext;
+
+/**
+ * Restores the test thread's context class loader after each test, including
a {@code null} loader. The loader may be configured at construction or changed
+ * from a test method.
+ */
+public class ContextClassLoaderExtension implements BeforeEachCallback,
AfterEachCallback {
+
+ private static final ExtensionContext.Namespace NAMESPACE =
ExtensionContext.Namespace.create(ContextClassLoaderExtension.class);
+
+ private final ClassLoader customClassLoader;
+
+ private final boolean setBeforeEach;
+
+ /**
+ * Constructs an extension that preserves the existing loader until the
test changes it.
+ */
+ public ContextClassLoaderExtension() {
+ customClassLoader = null;
+ setBeforeEach = false;
+ }
+
+ /**
+ * Constructs an extension that installs the given loader before each test.
+ *
+ * @param customClassLoader The context class loader to install, possibly
{@code null}.
+ */
+ public ContextClassLoaderExtension(final ClassLoader customClassLoader) {
+ this.customClassLoader = customClassLoader;
+ setBeforeEach = true;
+ }
+
+ @Override
+ public void afterEach(final ExtensionContext context) {
+ final Runnable restore = context.getStore(NAMESPACE).remove(this,
Runnable.class);
+ if (restore != null) {
+ restore.run();
+ }
+ }
+
+ @Override
+ public void beforeEach(final ExtensionContext context) {
+ final Thread thread = Thread.currentThread();
+ final ClassLoader original = thread.getContextClassLoader();
+ context.getStore(NAMESPACE).put(this, (Runnable) () ->
thread.setContextClassLoader(original));
+ if (setBeforeEach) {
+ setContextClassLoader(customClassLoader);
+ }
+ }
+
+ /**
+ * Sets the current thread's context class loader during a test.
+ *
+ * @param classLoader The context class loader to install, possibly {@code
null}.
+ */
+ public void setContextClassLoader(final ClassLoader classLoader) {
+ Thread.currentThread().setContextClassLoader(classLoader);
+ }
+}
diff --git
a/src/test/java/org/apache/commons/lang3/junit/ContextClassLoaderExtensionTest.java
b/src/test/java/org/apache/commons/lang3/junit/ContextClassLoaderExtensionTest.java
new file mode 100644
index 000000000..c459d8b60
--- /dev/null
+++
b/src/test/java/org/apache/commons/lang3/junit/ContextClassLoaderExtensionTest.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.lang3.junit;
+
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests {@link ContextClassLoaderExtension}.
+ */
+class ContextClassLoaderExtensionTest {
+
+ private ExtensionContext newContext() {
+ final ExtensionContext context = mock(ExtensionContext.class);
+ final ExtensionContext.Store store =
mock(ExtensionContext.Store.class);
+ final Map<Object, Object> values = new HashMap<>();
+
when(context.getStore(any(ExtensionContext.Namespace.class))).thenReturn(store);
+ doAnswer(invocation -> {
+ values.put(invocation.getArgument(0), invocation.getArgument(1));
+ return null;
+ }).when(store).put(any(), any());
+ when(store.remove(any(), any())).thenAnswer(invocation ->
values.remove(invocation.getArgument(0)));
+ return context;
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void testConfiguredLoader(final boolean nullOriginal) {
+ final Thread thread = Thread.currentThread();
+ final ClassLoader saved = thread.getContextClassLoader();
+ final ClassLoader original = nullOriginal ? null :
getClass().getClassLoader();
+ final ClassLoader custom = nullOriginal ? getClass().getClassLoader()
: null;
+ final ContextClassLoaderExtension extension = new
ContextClassLoaderExtension(custom);
+ final ExtensionContext context = newContext();
+ try {
+ thread.setContextClassLoader(original);
+ extension.beforeEach(context);
+ assertSame(custom, thread.getContextClassLoader());
+ extension.afterEach(context);
+ assertSame(original, thread.getContextClassLoader());
+ } finally {
+ thread.setContextClassLoader(saved);
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void testMethodScopedLoader(final boolean nullOriginal) {
+ final Thread thread = Thread.currentThread();
+ final ClassLoader saved = thread.getContextClassLoader();
+ final ClassLoader original = nullOriginal ? null :
getClass().getClassLoader();
+ final ContextClassLoaderExtension extension = new
ContextClassLoaderExtension();
+ final ExtensionContext context = newContext();
+ try {
+ thread.setContextClassLoader(original);
+ extension.beforeEach(context);
+ assertSame(original, thread.getContextClassLoader());
+ final ClassLoader custom = nullOriginal ?
getClass().getClassLoader() : null;
+ extension.setContextClassLoader(custom);
+ assertSame(custom, thread.getContextClassLoader());
+ extension.afterEach(context);
+ assertSame(original, thread.getContextClassLoader());
+ } finally {
+ thread.setContextClassLoader(saved);
+ }
+ }
+}