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 e3df1cbe2 Fix default locale isolation in tests (#1911)
e3df1cbe2 is described below

commit e3df1cbe2b88f37b58ccb311d8ce8d31c5a27f68
Author: Gary Gregory <[email protected]>
AuthorDate: Thu Dec 3 16:14:11 2026 -0500

    Fix default locale isolation in tests (#1911)
    
    Preserve overall, DISPLAY, and FORMAT defaults around locale-writing
    tests, supplementing JUnit Pioneer 1.9.1's incomplete restoration.
    
    Restore category defaults in StringUtilsTest and make ValidateTest
    message expectations locale-aware. Document the extension's purpose
    and test annotation detection, failure cleanup, and read-only handling.
---
 .../org/apache/commons/lang3/AbstractLangTest.java |   7 +
 .../org/apache/commons/lang3/StringUtilsTest.java  |   4 +
 .../org/apache/commons/lang3/ValidateTest.java     |  18 +-
 .../lang3/junit/DefaultLocaleExtension.java        | 101 ++++++++
 .../lang3/junit/DefaultLocaleExtensionTest.java    | 281 +++++++++++++++++++++
 5 files changed, 403 insertions(+), 8 deletions(-)

diff --git a/src/test/java/org/apache/commons/lang3/AbstractLangTest.java 
b/src/test/java/org/apache/commons/lang3/AbstractLangTest.java
index 84373105b..11645a526 100644
--- a/src/test/java/org/apache/commons/lang3/AbstractLangTest.java
+++ b/src/test/java/org/apache/commons/lang3/AbstractLangTest.java
@@ -20,11 +20,18 @@
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import org.apache.commons.lang3.builder.ToStringStyle;
+import org.apache.commons.lang3.junit.DefaultLocaleExtension;
 import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.extension.ExtendWith;
 
 /**
  * All tests subclass this test.
+ *
+ * <p>
+ * Locale restoration is registered here so it captures defaults before 
subclass extensions and restores them after those extensions finish.
+ * </p>
  */
+@ExtendWith(DefaultLocaleExtension.class)
 public class AbstractLangTest {
 
     /**
diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java 
b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
index 10848f595..3ec7913bd 100644
--- a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
@@ -3259,11 +3259,15 @@ void testToRootUpperCase() {
         assertEquals("TITLE", StringUtils.toRootUpperCase("title"));
         // Make sure we are not using the default Locale:
         final Locale defaultLocale = Locale.getDefault();
+        final Locale displayLocale = 
Locale.getDefault(Locale.Category.DISPLAY);
+        final Locale formatLocale = Locale.getDefault(Locale.Category.FORMAT);
         try {
             Locale.setDefault(TURKISH);
             assertEquals("TITLE", StringUtils.toRootUpperCase("title"));
         } finally {
             Locale.setDefault(defaultLocale);
+            Locale.setDefault(Locale.Category.DISPLAY, displayLocale);
+            Locale.setDefault(Locale.Category.FORMAT, formatLocale);
         }
     }
 
diff --git a/src/test/java/org/apache/commons/lang3/ValidateTest.java 
b/src/test/java/org/apache/commons/lang3/ValidateTest.java
index 1d80d1fc5..a7d779b02 100644
--- a/src/test/java/org/apache/commons/lang3/ValidateTest.java
+++ b/src/test/java/org/apache/commons/lang3/ValidateTest.java
@@ -38,10 +38,12 @@
 
 import org.junit.jupiter.api.Nested;
 import org.junit.jupiter.api.Test;
+import org.junitpioneer.jupiter.ReadsDefaultLocale;
 
 /**
  * Tests {@link Validate}.
  */
+@ReadsDefaultLocale
 class ValidateTest extends AbstractLangTest {
 
     @Nested
@@ -863,7 +865,7 @@ void shouldReturnSameInstance() {
                 @Test
                 void 
shouldThrowIllegalArgumentExceptionWithDefaultMessageForArrayWithNullElement() {
                     final IllegalArgumentException ex = 
assertIllegalArgumentException(() -> Validate.noNullElements(new String[] {"a", 
null}));
-                    assertEquals("The validated array contains null element at 
index: 1", ex.getMessage());
+                    assertEquals(String.format("The validated array contains 
null element at index: %d", 1), ex.getMessage());
                 }
 
                 @Test
@@ -923,7 +925,7 @@ void shouldReturnSameInstance() {
                 void 
shouldThrowIllegalArgumentExceptionWithDefaultMessageForCollectionWithNullElement()
 {
                     final IllegalArgumentException ex = 
assertIllegalArgumentException(
                         () -> 
Validate.noNullElements(Collections.singleton(null)));
-                    assertEquals("The validated collection contains null 
element at index: 0", ex.getMessage());
+                    assertEquals(String.format("The validated collection 
contains null element at index: %d", 0), ex.getMessage());
                 }
 
                 @Test
@@ -1449,13 +1451,13 @@ void shouldReturnSameInstance() {
                 @Test
                 void 
shouldThrowIndexOutOfBoundsExceptionWithDefaultMessageForIndexOutOfBounds() {
                     final IndexOutOfBoundsException ex = 
assertIndexOutOfBoundsException(() -> Validate.validIndex(new String[] {"a"}, 
1));
-                    assertEquals("The validated array index is invalid: 1", 
ex.getMessage());
+                    assertEquals(String.format("The validated array index is 
invalid: %d", 1), ex.getMessage());
                 }
 
                 @Test
                 void 
shouldThrowIndexOutOfBoundsExceptionWithDefaultMessageForNegativeIndex() {
                     final IndexOutOfBoundsException ex = 
assertIndexOutOfBoundsException(() -> Validate.validIndex(new String[] {"a"}, 
-1));
-                    assertEquals("The validated array index is invalid: -1", 
ex.getMessage());
+                    assertEquals(String.format("The validated array index is 
invalid: %d", -1), ex.getMessage());
                 }
 
                 @Test
@@ -1519,13 +1521,13 @@ void shouldReturnSameInstance() {
                 @Test
                 void 
shouldThrowIndexOutOfBoundsExceptionWithDefaultMessageForIndexOutOfBounds() {
                     final IndexOutOfBoundsException ex = 
assertIndexOutOfBoundsException(() -> Validate.validIndex("a", 1));
-                    assertEquals("The validated character sequence index is 
invalid: 1", ex.getMessage());
+                    assertEquals(String.format("The validated character 
sequence index is invalid: %d", 1), ex.getMessage());
                 }
 
                 @Test
                 void 
shouldThrowIndexOutOfBoundsExceptionWithDefaultMessageForNegativeIndex() {
                     final IndexOutOfBoundsException ex = 
assertIndexOutOfBoundsException(() -> Validate.validIndex("a", -1));
-                    assertEquals("The validated character sequence index is 
invalid: -1", ex.getMessage());
+                    assertEquals(String.format("The validated character 
sequence index is invalid: %d", -1), ex.getMessage());
                 }
 
                 @Test
@@ -1591,14 +1593,14 @@ void shouldReturnSameInstance() {
                 void 
shouldThrowIndexOutOfBoundsExceptionWithDefaultMessageForIndexOutOfBounds() {
                     final IndexOutOfBoundsException ex = 
assertIndexOutOfBoundsException(
                         () -> Validate.validIndex(Collections.singleton("a"), 
1));
-                    assertEquals("The validated collection index is invalid: 
1", ex.getMessage());
+                    assertEquals(String.format("The validated collection index 
is invalid: %d", 1), ex.getMessage());
                 }
 
                 @Test
                 void 
shouldThrowIndexOutOfBoundsExceptionWithDefaultMessageForNegativeIndex() {
                     final IndexOutOfBoundsException ex = 
assertIndexOutOfBoundsException(
                         () -> Validate.validIndex(Collections.singleton("a"), 
-1));
-                    assertEquals("The validated collection index is invalid: 
-1", ex.getMessage());
+                    assertEquals(String.format("The validated collection index 
is invalid: %d", -1), ex.getMessage());
                 }
 
                 @Test
diff --git 
a/src/test/java/org/apache/commons/lang3/junit/DefaultLocaleExtension.java 
b/src/test/java/org/apache/commons/lang3/junit/DefaultLocaleExtension.java
new file mode 100644
index 000000000..975856dcf
--- /dev/null
+++ b/src/test/java/org/apache/commons/lang3/junit/DefaultLocaleExtension.java
@@ -0,0 +1,101 @@
+/*
+ * 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 java.util.Locale;
+
+import org.junit.jupiter.api.extension.AfterEachCallback;
+import org.junit.jupiter.api.extension.BeforeEachCallback;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.platform.commons.support.AnnotationSupport;
+import org.junitpioneer.jupiter.DefaultLocale;
+import org.junitpioneer.jupiter.WritesDefaultLocale;
+
+/**
+ * Preserves all default locale categories around locale-writing tests.
+ *
+ * <p>
+ * JUnit Pioneer 1.9.1, retained for Java 8 test compatibility, saves only 
{@link Locale#getDefault()} for {@link DefaultLocale}. Its setup and cleanup 
call
+ * {@link Locale#setDefault(Locale)}, which also resets the {@link 
Locale.Category#DISPLAY} and {@link Locale.Category#FORMAT} defaults. 
Consequently,
+ * independently configured category defaults are lost even when Pioneer 
restores the overall default correctly.
+ * </p>
+ *
+ * <p>
+ * This extension supplements Pioneer's locale selection and resource locking 
by saving all three defaults and restoring the category defaults after the
+ * overall default. It applies to {@link WritesDefaultLocale} on a test method 
or enclosing test context, including the composed annotation on
+ * {@link DefaultLocale}. Tests that only read the default locale do not 
create restoration state or reset global locale settings.
+ * </p>
+ *
+ * <p>
+ * Register this extension before extensions that change the default locale so 
that it captures the original defaults first and restores them last, including
+ * after setup or test failures. Registration on {@link 
org.apache.commons.lang3.AbstractLangTest} provides this ordering for subclass 
annotations. The guard
+ * remains necessary while the configured Pioneer version does not preserve 
category-specific defaults.
+ * </p>
+ */
+public class DefaultLocaleExtension implements BeforeEachCallback, 
AfterEachCallback {
+
+    /**
+     * Namespace for each test invocation's restoration callback.
+     */
+    private static final ExtensionContext.Namespace NAMESPACE = 
ExtensionContext.Namespace.create(DefaultLocaleExtension.class);
+
+    /**
+     * Tests whether the method or an enclosing test context declares that it 
writes the default locale.
+     *
+     * @param context The test invocation's context.
+     * @return Whether locale restoration is needed.
+     */
+    private static boolean writesDefaultLocale(final ExtensionContext context) 
{
+        ExtensionContext current = context;
+        while (current != null) {
+            if (AnnotationSupport.isAnnotated(current.getElement(), 
WritesDefaultLocale.class)) {
+                return true;
+            }
+            current = current.getParent().orElse(null);
+        }
+        return false;
+    }
+
+    /**
+     * Constructs an extension that preserves all default locale categories.
+     */
+    public DefaultLocaleExtension() {
+    }
+
+    @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) {
+        if (writesDefaultLocale(context)) {
+            final Locale defaultLocale = Locale.getDefault();
+            final Locale displayLocale = 
Locale.getDefault(Locale.Category.DISPLAY);
+            final Locale formatLocale = 
Locale.getDefault(Locale.Category.FORMAT);
+            context.getStore(NAMESPACE).put(this, (Runnable) () -> {
+                Locale.setDefault(defaultLocale);
+                Locale.setDefault(Locale.Category.DISPLAY, displayLocale);
+                Locale.setDefault(Locale.Category.FORMAT, formatLocale);
+            });
+        }
+    }
+}
diff --git 
a/src/test/java/org/apache/commons/lang3/junit/DefaultLocaleExtensionTest.java 
b/src/test/java/org/apache/commons/lang3/junit/DefaultLocaleExtensionTest.java
new file mode 100644
index 000000000..b0b246e16
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/lang3/junit/DefaultLocaleExtensionTest.java
@@ -0,0 +1,281 @@
+/*
+ * 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.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.fail;
+
+import java.lang.reflect.Proxy;
+import java.util.Locale;
+import java.util.Optional;
+
+import org.apache.commons.lang3.AbstractLangTest;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.AfterEachCallback;
+import org.junit.jupiter.api.extension.BeforeEachCallback;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.parallel.ResourceLock;
+import org.junit.jupiter.api.parallel.Resources;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.junit.platform.engine.discovery.DiscoverySelectors;
+import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
+import org.junit.platform.launcher.core.LauncherFactory;
+import org.junit.platform.launcher.listeners.SummaryGeneratingListener;
+import org.junit.platform.launcher.listeners.TestExecutionSummary;
+import org.junitpioneer.jupiter.DefaultLocale;
+import org.junitpioneer.jupiter.ReadsDefaultLocale;
+import org.junitpioneer.jupiter.WritesDefaultLocale;
+
+/**
+ * Tests restoration after method, class, nested, and parameterized locale 
changes using the actual JUnit extension lifecycle.
+ *
+ * <p>
+ * The harness uses a JUnit resource lock instead of {@link 
WritesDefaultLocale} so that it does not activate the extension for every test. 
Each locale-writing
+ * scenario must be detected through its own Pioneer annotation. Static 
failure fixtures are launched explicitly and are not nested tests of this class.
+ * </p>
+ */
+@ExtendWith({DefaultLocaleExtensionTest.VerifyLocales.class, 
DefaultLocaleExtension.class})
+@ResourceLock(Resources.LOCALE)
+class DefaultLocaleExtensionTest {
+
+    /**
+     * Tests class defaults and method overrides.
+     */
+    @Nested
+    @DefaultLocale(language = "de")
+    class ClassLocale {
+
+        /**
+         * Tests that the class-level locale is installed.
+         */
+        @Test
+        void testClassLocale() {
+            assertDefaultLocales(Locale.GERMAN);
+        }
+
+        /**
+         * Tests that a method annotation overrides the class annotation.
+         */
+        @Test
+        @DefaultLocale(language = "fr", country = "FR")
+        void testMethodOverride() {
+            assertDefaultLocales(Locale.FRANCE);
+        }
+    }
+
+    /**
+     * Provides an unannotated context for checking that restoration state is 
not created.
+     */
+    static class NoLocaleAnnotation {
+        // No locale annotations.
+    }
+
+    /**
+     * Provides a read-only context for checking that restoration state is not 
created.
+     */
+    @ReadsDefaultLocale
+    static class ReadOnlyLocale {
+        // Reading the locale must not enable restoration.
+    }
+
+    /**
+     * Fails during setup after Pioneer has changed the default locale.
+     */
+    @DefaultLocale("de")
+    static class SetupFailure extends AbstractLangTest {
+
+        /**
+         * Deliberately fails before the test body is invoked.
+         */
+        @BeforeEach
+        void failSetup() {
+            throw new IllegalStateException("Expected setup failure");
+        }
+
+        /**
+         * Must be skipped because setup failed.
+         */
+        @Test
+        void testBody() {
+            fail("The test body must not run after setup fails");
+        }
+    }
+
+    /**
+     * Fails in the test body after Pioneer has changed the default locale.
+     */
+    static class TestFailure extends AbstractLangTest {
+
+        /**
+         * Deliberately fails after checking the configured locale.
+         */
+        @Test
+        @DefaultLocale("tr")
+        void testBody() {
+            assertDefaultLocales(Locale.forLanguageTag("tr"));
+            throw new IllegalStateException("Expected test failure");
+        }
+    }
+
+    /**
+     * Installs distinct defaults before the extension under test and verifies 
their restoration afterward.
+     */
+    static class VerifyLocales implements BeforeEachCallback, 
AfterEachCallback {
+
+        /**
+         * Namespace for the surrounding test process's original defaults.
+         */
+        private static final ExtensionContext.Namespace NAMESPACE = 
ExtensionContext.Namespace.create(VerifyLocales.class);
+
+        @Override
+        public void afterEach(final ExtensionContext context) {
+            final Locale[] original = context.getStore(NAMESPACE).remove(this, 
Locale[].class);
+            try {
+                assertEquals(Locale.US, Locale.getDefault());
+                assertEquals(Locale.FRANCE, 
Locale.getDefault(Locale.Category.DISPLAY));
+                assertEquals(Locale.GERMANY, 
Locale.getDefault(Locale.Category.FORMAT));
+            } finally {
+                Locale.setDefault(original[0]);
+                Locale.setDefault(Locale.Category.DISPLAY, original[1]);
+                Locale.setDefault(Locale.Category.FORMAT, original[2]);
+            }
+        }
+
+        @Override
+        public void beforeEach(final ExtensionContext context) {
+            context.getStore(NAMESPACE).put(this, new Locale[] {
+                Locale.getDefault(), 
Locale.getDefault(Locale.Category.DISPLAY), 
Locale.getDefault(Locale.Category.FORMAT)
+            });
+            Locale.setDefault(Locale.US);
+            Locale.setDefault(Locale.Category.DISPLAY, Locale.FRANCE);
+            Locale.setDefault(Locale.Category.FORMAT, Locale.GERMANY);
+        }
+    }
+
+    /**
+     * Asserts that the overall default and both categories match the 
requested locale.
+     *
+     * @param expected The expected locale.
+     */
+    private static void assertDefaultLocales(final Locale expected) {
+        assertEquals(expected, Locale.getDefault());
+        assertEquals(expected, Locale.getDefault(Locale.Category.DISPLAY));
+        assertEquals(expected, Locale.getDefault(Locale.Category.FORMAT));
+    }
+
+    /**
+     * Runs an intentionally failing fixture and verifies that the failure 
does not prevent locale restoration.
+     *
+     * @param fixture The fixture class to launch.
+     * @param expectedMessage The expected failure message.
+     */
+    private static void assertFailureRestoresLocales(final Class<?> fixture, 
final String expectedMessage) {
+        final SummaryGeneratingListener listener = new 
SummaryGeneratingListener();
+        
LauncherFactory.create().execute(LauncherDiscoveryRequestBuilder.request()
+                .selectors(DiscoverySelectors.selectClass(fixture))
+                
.configurationParameter("junit.jupiter.execution.parallel.enabled", "false")
+                .build(), listener);
+        final TestExecutionSummary summary = listener.getSummary();
+        assertEquals(1, summary.getTestsStartedCount());
+        assertEquals(1, summary.getTestsFailedCount());
+        assertEquals(0, summary.getContainersFailedCount());
+        assertEquals(1, summary.getFailures().size());
+        final IllegalStateException exception = 
assertInstanceOf(IllegalStateException.class, 
summary.getFailures().get(0).getException());
+        assertEquals(expectedMessage, exception.getMessage());
+        assertEquals(Locale.US, Locale.getDefault());
+        assertEquals(Locale.FRANCE, 
Locale.getDefault(Locale.Category.DISPLAY));
+        assertEquals(Locale.GERMANY, 
Locale.getDefault(Locale.Category.FORMAT));
+    }
+
+    /**
+     * Tests restoration after a test changes both the overall and 
category-specific defaults.
+     *
+     * @param languageTag The locale to install.
+     */
+    @ParameterizedTest
+    @ValueSource(strings = {"ja-JP", "tr"})
+    @WritesDefaultLocale
+    void testManualLocaleChange(final String languageTag) {
+        Locale.setDefault(Locale.forLanguageTag(languageTag));
+        Locale.setDefault(Locale.Category.DISPLAY, Locale.ITALY);
+        Locale.setDefault(Locale.Category.FORMAT, Locale.CANADA);
+    }
+
+    /**
+     * Tests a method-level locale annotation.
+     */
+    @Test
+    @DefaultLocale("tr")
+    void testMethodLocale() {
+        assertDefaultLocales(Locale.forLanguageTag("tr"));
+    }
+
+    /**
+     * Tests cleanup after a failing setup method.
+     */
+    @Test
+    void testRestoresAfterSetupFailure() {
+        assertFailureRestoresLocales(SetupFailure.class, "Expected setup 
failure");
+    }
+
+    /**
+     * Tests cleanup after a failing test method.
+     */
+    @Test
+    void testRestoresAfterTestFailure() {
+        assertFailureRestoresLocales(TestFailure.class, "Expected test 
failure");
+    }
+
+    /**
+     * Tests that unannotated and read-only contexts never request restoration 
storage.
+     *
+     * @param element The class supplying the context's annotations.
+     */
+    @ParameterizedTest
+    @ValueSource(classes = {NoLocaleAnnotation.class, ReadOnlyLocale.class})
+    void testSkipsRestorationState(final Class<?> element) {
+        final ExtensionContext context = (ExtensionContext) 
Proxy.newProxyInstance(ExtensionContext.class.getClassLoader(),
+                new Class<?>[] {ExtensionContext.class}, (proxy, method, args) 
-> {
+                    switch (method.getName()) {
+                    case "getElement":
+                        return Optional.of(element);
+                    case "getParent":
+                        return Optional.empty();
+                    default:
+                        throw new AssertionError("Read-only contexts must not 
request restoration storage: " + method.getName());
+                    }
+                });
+        assertDoesNotThrow(() -> new 
DefaultLocaleExtension().beforeEach(context));
+    }
+
+    /**
+     * Tests preserving distinct categories when the test does not change them.
+     */
+    @Test
+    void testUnchangedLocales() {
+        assertEquals(Locale.US, Locale.getDefault());
+        assertEquals(Locale.FRANCE, 
Locale.getDefault(Locale.Category.DISPLAY));
+        assertEquals(Locale.GERMANY, 
Locale.getDefault(Locale.Category.FORMAT));
+    }
+}

Reply via email to