Merge branch 'LANG-1127'

LANG-1127: Use JUnit rules to set and reset the default Locale and TimeZone.
This commit is contained in:
Benedikt Ritter 2015-05-07 22:13:32 +02:00
commit cfe63beeac
11 changed files with 385 additions and 305 deletions

View File

@ -30,7 +30,7 @@
<action issue="LANG-1131" type="fix" dev="britter">StrBuilder.equals(StrBuilder) doesn't check for null inputs</action> <action issue="LANG-1131" type="fix" dev="britter">StrBuilder.equals(StrBuilder) doesn't check for null inputs</action>
<action issue="LANG-1105" type="add" dev="britter" due-to="Hendrik Saly">Add ThreadUtils - A utility class which provides helper methods related to java.lang.Thread</action> <action issue="LANG-1105" type="add" dev="britter" due-to="Hendrik Saly">Add ThreadUtils - A utility class which provides helper methods related to java.lang.Thread</action>
<action issue="LANG-1031" type="add" dev="britter" due-to="Felipe Adorno">Add annotations to exclude fields from ReflectionEqualsBuilder, ReflectionToStringBuilder and ReflectionHashCodeBuilder</action> <action issue="LANG-1031" type="add" dev="britter" due-to="Felipe Adorno">Add annotations to exclude fields from ReflectionEqualsBuilder, ReflectionToStringBuilder and ReflectionHashCodeBuilder</action>
<action issue="LANG-1127" type="add" dev="chas">Unit test helpers which set and reset default Locale and TimeZone</action> <action issue="LANG-1127" type="add" dev="chas, britter">Use JUnit rules to set and reset the default Locale and TimeZone</action>
<action issue="LANG-1128" type="fix" dev="britter" due-to="Jack Tan">JsonToStringStyle doesn't handle chars and objects correctly</action> <action issue="LANG-1128" type="fix" dev="britter" due-to="Jack Tan">JsonToStringStyle doesn't handle chars and objects correctly</action>
<action issue="LANG-456" type="fix" dev="britter" due-to="Bob Fields, Woosan Ko, Bruno P. Kinoshita">HashCodeBuilder throws StackOverflowError in bidirectional navigable association</action> <action issue="LANG-456" type="fix" dev="britter" due-to="Bob Fields, Woosan Ko, Bruno P. Kinoshita">HashCodeBuilder throws StackOverflowError in bidirectional navigable association</action>
<action issue="LANG-1126" type="fix" dev="britter">DateFormatUtilsTest.testSMTP depends on the default Locale</action> <action issue="LANG-1126" type="fix" dev="britter">DateFormatUtilsTest.testSMTP depends on the default Locale</action>

View File

@ -23,14 +23,20 @@
import java.util.Locale; import java.util.Locale;
import org.apache.commons.lang3.test.DefaultLocale; import org.apache.commons.lang3.test.SystemDefaultsSwitch;
import org.apache.commons.lang3.test.SystemDefaults;
import org.hamcrest.core.IsNot; import org.hamcrest.core.IsNot;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
/** /**
* Unit tests {@link org.apache.commons.lang3.StringUtils} - Substring methods * Unit tests {@link org.apache.commons.lang3.StringUtils} - Substring methods
*/ */
public class StringUtilsEqualsIndexOfTest { public class StringUtilsEqualsIndexOfTest {
@Rule
public SystemDefaultsSwitch defaults = new SystemDefaultsSwitch();
private static final String BAR = "bar"; private static final String BAR = "bar";
/** /**
* Supplementary character U+20000 * Supplementary character U+20000
@ -232,6 +238,7 @@ public void testContainsAny_StringStringArray() {
assertFalse(StringUtils.containsAny("hello, null", new String[] { "Hello", null })); assertFalse(StringUtils.containsAny("hello, null", new String[] { "Hello", null }));
} }
@SystemDefaults(locale="de_DE")
@Test @Test
public void testContainsIgnoreCase_LocaleIndependence() { public void testContainsIgnoreCase_LocaleIndependence() {
final Locale[] locales = { Locale.ENGLISH, new Locale("tr"), Locale.getDefault() }; final Locale[] locales = { Locale.ENGLISH, new Locale("tr"), Locale.getDefault() };
@ -248,22 +255,17 @@ public void testContainsIgnoreCase_LocaleIndependence() {
{ "\u00DF", "SS" }, { "\u00DF", "SS" },
}; };
new DefaultLocale<RuntimeException>(Locale.ENGLISH) { for (final Locale testLocale : locales) {
@Override Locale.setDefault(testLocale);
public void test() { for (int j = 0; j < tdata.length; j++) {
for (final Locale locale : locales) { assertTrue(Locale.getDefault() + ": " + j + " " + tdata[j][0] + " " + tdata[j][1], StringUtils
Locale.setDefault(locale); .containsIgnoreCase(tdata[j][0], tdata[j][1]));
for (int j = 0; j < tdata.length; j++) {
assertTrue(Locale.getDefault() + ": " + j + " " + tdata[j][0] + " " + tdata[j][1], StringUtils
.containsIgnoreCase(tdata[j][0], tdata[j][1]));
}
for (int j = 0; j < fdata.length; j++) {
assertFalse(Locale.getDefault() + ": " + j + " " + fdata[j][0] + " " + fdata[j][1], StringUtils
.containsIgnoreCase(fdata[j][0], fdata[j][1]));
}
}
} }
}; for (int j = 0; j < fdata.length; j++) {
assertFalse(Locale.getDefault() + ": " + j + " " + fdata[j][0] + " " + fdata[j][1], StringUtils
.containsIgnoreCase(fdata[j][0], fdata[j][1]));
}
}
} }
@Test @Test

View File

@ -1,43 +0,0 @@
/*
* 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
*
* http://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.test;
import java.util.TimeZone;
/**
* run a test with a different default TimeZone
*/
public abstract class DefaultTimeZone<E extends Throwable> {
public DefaultTimeZone(TimeZone targetZone) throws E {
// only one test at a time may change default
synchronized (getClass()) {
TimeZone defaultZone = TimeZone.getDefault();
try {
TimeZone.setDefault(targetZone);
test();
} finally {
TimeZone.setDefault(defaultZone);
}
}
}
/**
* Implement test in this method
*/
abstract public void test() throws E;
}

View File

@ -1,45 +0,0 @@
/*
* 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
*
* http://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.test;
import java.util.Locale;
import java.util.TimeZone;
/**
* run a test with a different default TimeZone and Locale
*/
public abstract class DefaultTimeZoneAndLocale<E extends Throwable> {
public DefaultTimeZoneAndLocale(TimeZone targetZone, final Locale targetLocale) throws E {
new DefaultTimeZone<E>(targetZone) {
@Override
public void test() throws E {
new DefaultLocale<E>(targetLocale) {
@Override
public void test() throws E {
DefaultTimeZoneAndLocale.this.test();
}
};
}
};
}
/**
* Implement test in this method
*/
abstract public void test() throws E;
}

View File

@ -5,39 +5,36 @@
* The ASF licenses this file to You under the Apache License, Version 2.0 * 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 not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.apache.commons.lang3.test; package org.apache.commons.lang3.test;
import java.util.Locale; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** /**
* run a test with a different default Locale * Annotation used with {@link SystemDefaults} that specifies the
* system default Locale and TimeZone to be used in a test method.
*/ */
public abstract class DefaultLocale<E extends Throwable> { @Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public DefaultLocale(Locale targetLocale) throws E { public @interface SystemDefaults {
// only one test at a time may change default
synchronized (getClass()) {
Locale defaultLocale = Locale.getDefault();
try {
Locale.setDefault(targetLocale);
test();
} finally {
Locale.setDefault(defaultLocale);
}
}
}
/** /**
* Implement test in this method * The name of the Locale to be used while running a test method
*/ */
abstract public void test() throws E; String locale() default "";
/**
* The name of the TimeZone to be used while running a test method
*/
String timezone() default "";
} }

View File

@ -0,0 +1,113 @@
/*
* 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
*
* http://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.test;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.commons.lang3.LocaleUtils;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/**
* Test Rule used with {@link SystemDefaults} annotation that sets and restores the system default Locale and TimeZone.
*
* <p>
* Set up tests to use alternate system default Locale and/or TimeZone by creating an instance of this rule
* and annotating the test method with {@link SystemDefaults}
* </p>
*
* <pre>
* public class SystemDefaultsDependentTest {
*
* {@literal@}Rule
* public SystemDefaultsSwitch locale = new SystemDefaultsSwitch();
*
* {@literal@}Test
* public void testThatWillExecuteWithTheDefaultLocaleAndTimeZone() {
* // nothing to do, just implement the test
* }
*
* {@literal@}Test
* {@literal@}SystemDefaults(local="zh_CN")
* public void testWithSimplifiedChinaDefaultLocale() {
* // Locale.getDefault() will return Locale.CHINA until the end of this test method
* }
*
* {@literal@}Test
* {@literal@}SystemDefaults(timezone="America/New_York")
* public void testWithNorthAmericaEasternTimeZone() {
* // TimeZone.getDefault() will equal TimeZone.getTimeZone("America/New_York") until the end of this method
* }
* }
* </pre>
*/
public class SystemDefaultsSwitch implements TestRule {
@Override
public Statement apply(Statement stmt, Description description) {
SystemDefaults defaults = description.getAnnotation(SystemDefaults.class);
if (defaults == null) {
return stmt;
}
return applyTimeZone(defaults, applyLocale(defaults, stmt));
}
private Statement applyTimeZone(SystemDefaults defaults, final Statement stmt) {
if (defaults.timezone().isEmpty()) {
return stmt;
}
final TimeZone newTimeZone = TimeZone.getTimeZone(defaults.timezone());
return new Statement() {
@Override
public void evaluate() throws Throwable {
TimeZone save = TimeZone.getDefault();
try {
TimeZone.setDefault(newTimeZone);
stmt.evaluate();
} finally {
TimeZone.setDefault(save);
}
}
};
}
private Statement applyLocale(SystemDefaults defaults, final Statement stmt) {
if (defaults.locale().isEmpty()) {
return stmt;
}
final Locale newLocale = LocaleUtils.toLocale(defaults.locale());
return new Statement() {
@Override
public void evaluate() throws Throwable {
Locale save = Locale.getDefault();
try {
Locale.setDefault(newLocale);
stmt.evaluate();
} finally {
Locale.setDefault(save);
}
}
};
}
}

View File

@ -0,0 +1,88 @@
/*
* 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
*
* http://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.test;
import static org.junit.Assert.assertEquals;
import java.util.Locale;
import java.util.TimeZone;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
public class SystemDefaultsSwitchTest {
private static Locale TEST_DEFAULT_LOCALE;
private static Locale DEFAULT_LOCALE_BEFORE_TEST;
private static TimeZone DEFAULT_TIMEZONE_BEFORE_TEST;
private static TimeZone TEST_DEFAULT_TIMEZONE;
@BeforeClass
public static void classSetUp() {
DEFAULT_LOCALE_BEFORE_TEST = Locale.getDefault();
if (!DEFAULT_LOCALE_BEFORE_TEST.equals(Locale.CANADA)) {
Locale.setDefault(Locale.CANADA);
} else {
// you seem to be from Canada...
Locale.setDefault(Locale.CHINESE);
}
TEST_DEFAULT_LOCALE = Locale.getDefault();
DEFAULT_TIMEZONE_BEFORE_TEST = TimeZone.getDefault();
TimeZone utc = TimeZone.getTimeZone("UTC");
if (!DEFAULT_TIMEZONE_BEFORE_TEST.equals(utc)) {
TimeZone.setDefault(utc);
} else {
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
}
TEST_DEFAULT_TIMEZONE = TimeZone.getDefault();
}
@Rule
public SystemDefaultsSwitch defaultsSwitch = new SystemDefaultsSwitch();
@Test
public void testDefaultLocaleNoAnnotation() throws Exception {
assertEquals(TEST_DEFAULT_LOCALE, Locale.getDefault());
}
@Test
@SystemDefaults(locale = "en_EN")
public void testUseDifferentLocale() throws Exception {
assertEquals(new Locale("en", "EN"), Locale.getDefault());
}
@Test
public void testDefaultTimeZoneNoAnnotation() throws Exception {
assertEquals(TEST_DEFAULT_TIMEZONE, TimeZone.getDefault());
}
@Test
@SystemDefaults(timezone = "CET")
public void testUseDifferentTimeZone() throws Exception {
assertEquals(TimeZone.getTimeZone("CET"), TimeZone.getDefault());
}
@AfterClass
public static void classTearDown() {
Locale.setDefault(DEFAULT_LOCALE_BEFORE_TEST);
TimeZone.setDefault(DEFAULT_TIMEZONE_BEFORE_TEST);
}
}

View File

@ -29,8 +29,9 @@
import java.util.Locale; import java.util.Locale;
import java.util.TimeZone; import java.util.TimeZone;
import org.apache.commons.lang3.test.DefaultLocale; import org.apache.commons.lang3.test.SystemDefaultsSwitch;
import org.apache.commons.lang3.test.DefaultTimeZone; import org.apache.commons.lang3.test.SystemDefaults;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
/** /**
@ -38,6 +39,9 @@
*/ */
public class DateFormatUtilsTest { public class DateFormatUtilsTest {
@Rule
public SystemDefaultsSwitch defaults = new SystemDefaultsSwitch();
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
@Test @Test
public void testConstructor() { public void testConstructor() {
@ -166,23 +170,19 @@ public void testTimeNoTISO() {
testUTC("09:11:12Z", DateFormatUtils.ISO_TIME_NO_T_TIME_ZONE_FORMAT.getPattern()); testUTC("09:11:12Z", DateFormatUtils.ISO_TIME_NO_T_TIME_ZONE_FORMAT.getPattern());
} }
@SystemDefaults(locale="en")
@Test @Test
public void testSMTP() { public void testSMTP() {
new DefaultLocale<RuntimeException>(Locale.ENGLISH) { TimeZone timeZone = TimeZone.getTimeZone("GMT-3");
@Override Calendar june = createJuneTestDate(timeZone);
public void test() {
TimeZone timeZone = TimeZone.getTimeZone("GMT-3");
Calendar june = createJuneTestDate(timeZone);
assertFormats("Sun, 08 Jun 2003 10:11:12 -0300", DateFormatUtils.SMTP_DATETIME_FORMAT.getPattern(), assertFormats("Sun, 08 Jun 2003 10:11:12 -0300", DateFormatUtils.SMTP_DATETIME_FORMAT.getPattern(),
timeZone, june); timeZone, june);
timeZone = TimeZone.getTimeZone("UTC"); timeZone = TimeZone.getTimeZone("UTC");
june = createJuneTestDate(timeZone); june = createJuneTestDate(timeZone);
assertFormats("Sun, 08 Jun 2003 10:11:12 +0000", DateFormatUtils.SMTP_DATETIME_FORMAT.getPattern(), assertFormats("Sun, 08 Jun 2003 10:11:12 +0000", DateFormatUtils.SMTP_DATETIME_FORMAT.getPattern(),
timeZone, june); timeZone, june);
}
};
} }
/* /*
@ -219,18 +219,14 @@ public void testLANG1000() throws Exception {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(date); DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(date);
} }
@SystemDefaults(timezone="UTC")
@Test @Test
public void testLang530() throws ParseException { public void testLang530() throws ParseException {
new DefaultTimeZone<ParseException>(TimeZone.getTimeZone("UTC")) { final Date d = new Date();
@Override final String isoDateStr = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(d);
public void test() throws ParseException { final Date d2 = DateUtils.parseDate(isoDateStr, new String[] { DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern() });
final Date d = new Date(); // the format loses milliseconds so have to reintroduce them
final String isoDateStr = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(d); assertEquals("Date not equal to itself ISO formatted and parsed", d.getTime(), d2.getTime() + d.getTime() % 1000);
final Date d2 = DateUtils.parseDate(isoDateStr, new String[] { DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern() });
// the format loses milliseconds so have to reintroduce them
assertEquals("Date not equal to itself ISO formatted and parsed", d.getTime(), d2.getTime() + d.getTime() % 1000);
}
};
} }
/** /**

View File

@ -38,9 +38,11 @@
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import org.apache.commons.lang3.test.DefaultLocale; import org.apache.commons.lang3.test.SystemDefaultsSwitch;
import org.apache.commons.lang3.test.SystemDefaults;
import org.junit.Before; import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
/** /**
@ -57,6 +59,9 @@ public static void classSetup() {
BASE_DATE = cal.getTime(); BASE_DATE = cal.getTime();
} }
@Rule
public SystemDefaultsSwitch defaults = new SystemDefaultsSwitch();
private DateFormat dateParser = null; private DateFormat dateParser = null;
private DateFormat dateTimeParser = null; private DateFormat dateTimeParser = null;
private Date dateAmPm1 = null; private Date dateAmPm1 = null;
@ -1560,59 +1565,39 @@ public void testMonthIterator() throws Exception {
dateParser.parse("December 2, 2001")); dateParser.parse("December 2, 2001"));
} }
@SystemDefaults(locale="en")
@Test @Test
public void testLANG799_EN_OK() throws ParseException { public void testLANG799_EN_OK() throws ParseException {
new DefaultLocale<ParseException>(Locale.ENGLISH){ DateUtils.parseDate("Wed, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
@Override DateUtils.parseDateStrictly("Wed, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
public void test() throws ParseException {
DateUtils.parseDate("Wed, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
DateUtils.parseDateStrictly("Wed, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
}
};
} }
// Parse German date with English Locale // Parse German date with English Locale
@Test(expected=ParseException.class) @SystemDefaults(locale="en")
@Test(expected = ParseException.class)
public void testLANG799_EN_FAIL() throws ParseException { public void testLANG799_EN_FAIL() throws ParseException {
new DefaultLocale<ParseException>(Locale.ENGLISH){ DateUtils.parseDate("Mi, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
@Override
public void test() throws ParseException {
DateUtils.parseDate("Mi, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
}
};
} }
@SystemDefaults(locale="de")
@Test @Test
public void testLANG799_DE_OK() throws ParseException { public void testLANG799_DE_OK() throws ParseException {
new DefaultLocale<ParseException>(Locale.GERMAN){ DateUtils.parseDate("Mi, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
@Override DateUtils.parseDateStrictly("Mi, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
public void test() throws ParseException {
DateUtils.parseDate("Mi, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
DateUtils.parseDateStrictly("Mi, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
}
};
} }
// Parse English date with German Locale // Parse English date with German Locale
@SystemDefaults(locale="de")
@Test(expected=ParseException.class) @Test(expected=ParseException.class)
public void testLANG799_DE_FAIL() throws ParseException { public void testLANG799_DE_FAIL() throws ParseException {
new DefaultLocale<ParseException>(Locale.GERMAN){ DateUtils.parseDate("Wed, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
@Override
public void test() throws ParseException {
DateUtils.parseDate("Wed, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
}
};
} }
// Parse German date with English Locale, specifying German Locale override // Parse German date with English Locale, specifying German Locale override
@SystemDefaults(locale="en")
@Test @Test
public void testLANG799_EN_WITH_DE_LOCALE() throws ParseException { public void testLANG799_EN_WITH_DE_LOCALE() throws ParseException {
new DefaultLocale<ParseException>(Locale.ENGLISH){ DateUtils.parseDate("Mi, 09 Apr 2008 23:55:38 GMT", Locale.GERMAN, "EEE, dd MMM yyyy HH:mm:ss zzz");
@Override
public void test() throws ParseException {
DateUtils.parseDate("Mi, 09 Apr 2008 23:55:38 GMT", Locale.GERMAN, "EEE, dd MMM yyyy HH:mm:ss zzz");
}
};
} }
/** /**

View File

@ -18,6 +18,7 @@
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -34,8 +35,9 @@
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.lang3.test.DefaultLocale; import org.apache.commons.lang3.test.SystemDefaultsSwitch;
import org.apache.commons.lang3.test.DefaultTimeZoneAndLocale; import org.apache.commons.lang3.test.SystemDefaults;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
/** /**
@ -45,6 +47,9 @@
*/ */
public class FastDateFormatTest { public class FastDateFormatTest {
@Rule
public SystemDefaultsSwitch defaults = new SystemDefaultsSwitch();
/* /*
* Only the cache methods need to be tested here. * Only the cache methods need to be tested here.
* The print methods are tested by {@link FastDateFormat_PrinterTest} * The print methods are tested by {@link FastDateFormat_PrinterTest}
@ -70,104 +75,85 @@ public void test_getInstance_String() {
assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(TimeZone.getDefault(), format2.getTimeZone());
} }
@SystemDefaults(timezone="America/New_York", locale="en_US")
@Test @Test
public void test_getInstance_String_TimeZone() { public void test_getInstance_String_TimeZone() {
new DefaultTimeZoneAndLocale<RuntimeException>(TimeZone.getTimeZone("America/New_York"), Locale.US) {
@Override
public void test() {
final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy",
TimeZone.getTimeZone("Atlantic/Reykjavik"));
final FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy");
final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault());
final FastDateFormat format4 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault());
final FastDateFormat format5 = FastDateFormat.getInstance("MM-DD-yyyy", TimeZone.getDefault());
final FastDateFormat format6 = FastDateFormat.getInstance("MM-DD-yyyy");
assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy",
assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone()); TimeZone.getTimeZone("Atlantic/Reykjavik"));
assertEquals(TimeZone.getDefault(), format2.getTimeZone()); final FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy");
assertSame(format3, format4); final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault());
assertTrue(format3 != format5); // -- junit 3.8 version -- assertFalse(format3 == format5); final FastDateFormat format4 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault());
assertTrue(format4 != format6); // -- junit 3.8 version -- assertFalse(format3 == format5); final FastDateFormat format5 = FastDateFormat.getInstance("MM-DD-yyyy", TimeZone.getDefault());
} final FastDateFormat format6 = FastDateFormat.getInstance("MM-DD-yyyy");
};
assertNotSame(format1, format2);
assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone());
assertEquals(TimeZone.getDefault(), format2.getTimeZone());
assertSame(format3, format4);
assertNotSame(format3, format5);
assertNotSame(format4, format6);
} }
@SystemDefaults(locale="en_US")
@Test @Test
public void test_getInstance_String_Locale() { public void test_getInstance_String_Locale() {
new DefaultLocale<RuntimeException>(Locale.US) { final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
@Override final FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy");
public void test() throws RuntimeException { final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
final FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy");
final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertNotSame(format1, format2);
assertSame(format1, format3); assertSame(format1, format3);
assertEquals(Locale.GERMANY, format1.getLocale()); assertEquals(Locale.GERMANY, format1.getLocale());
}
};
} }
@SystemDefaults(locale="en_US")
@Test @Test
public void test_changeDefault_Locale_DateInstance() { public void test_changeDefault_Locale_DateInstance() {
new DefaultLocale<RuntimeException>(Locale.US) { final FastDateFormat format1 = FastDateFormat.getDateInstance(FastDateFormat.FULL, Locale.GERMANY);
@Override final FastDateFormat format2 = FastDateFormat.getDateInstance(FastDateFormat.FULL);
public void test() throws RuntimeException { Locale.setDefault(Locale.GERMANY);
final FastDateFormat format1 = FastDateFormat.getDateInstance(FastDateFormat.FULL, Locale.GERMANY); final FastDateFormat format3 = FastDateFormat.getDateInstance(FastDateFormat.FULL);
final FastDateFormat format2 = FastDateFormat.getDateInstance(FastDateFormat.FULL);
Locale.setDefault(Locale.GERMANY);
final FastDateFormat format3 = FastDateFormat.getDateInstance(FastDateFormat.FULL);
assertSame(Locale.GERMANY, format1.getLocale()); assertSame(Locale.GERMANY, format1.getLocale());
assertSame(Locale.US, format2.getLocale()); assertEquals(Locale.US, format2.getLocale());
assertSame(Locale.GERMANY, format3.getLocale()); assertSame(Locale.GERMANY, format3.getLocale());
assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertNotSame(format1, format2);
assertTrue(format2 != format3); assertNotSame(format2, format3);
}
};
} }
@SystemDefaults(locale="en_US")
@Test @Test
public void test_changeDefault_Locale_DateTimeInstance() { public void test_changeDefault_Locale_DateTimeInstance() {
new DefaultLocale<RuntimeException>(Locale.US) { final FastDateFormat format1 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL, Locale.GERMANY);
@Override final FastDateFormat format2 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL);
public void test() throws RuntimeException { Locale.setDefault(Locale.GERMANY);
final FastDateFormat format1 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL, Locale.GERMANY); final FastDateFormat format3 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL);
final FastDateFormat format2 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL);
Locale.setDefault(Locale.GERMANY);
final FastDateFormat format3 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL);
assertSame(Locale.GERMANY, format1.getLocale()); assertSame(Locale.GERMANY, format1.getLocale());
assertSame(Locale.US, format2.getLocale()); assertEquals(Locale.US, format2.getLocale());
assertSame(Locale.GERMANY, format3.getLocale()); assertSame(Locale.GERMANY, format3.getLocale());
assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertNotSame(format1, format2);
assertTrue(format2 != format3); assertNotSame(format2, format3);
}
};
} }
@SystemDefaults(locale="en_US", timezone="America/New_York")
@Test @Test
public void test_getInstance_String_TimeZone_Locale() { public void test_getInstance_String_TimeZone_Locale() {
new DefaultTimeZoneAndLocale<RuntimeException>(TimeZone.getTimeZone("America/New_York"), Locale.US) { final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy",
@Override TimeZone.getTimeZone("Atlantic/Reykjavik"), Locale.GERMANY);
public void test() { final FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy",
TimeZone.getTimeZone("Atlantic/Reykjavik"), Locale.GERMANY); TimeZone.getDefault(), Locale.GERMANY);
final FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy",
TimeZone.getDefault(), Locale.GERMANY);
assertTrue(format1 != format2); // -- junit 3.8 version -- assertNotSame(format1, format2); assertNotSame(format1, format2);
assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone()); assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone());
assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(TimeZone.getDefault(), format2.getTimeZone());
assertEquals(TimeZone.getDefault(), format3.getTimeZone()); assertEquals(TimeZone.getDefault(), format3.getTimeZone());
assertEquals(Locale.GERMANY, format1.getLocale()); assertEquals(Locale.GERMANY, format1.getLocale());
assertEquals(Locale.GERMANY, format2.getLocale()); assertEquals(Locale.GERMANY, format2.getLocale());
assertEquals(Locale.GERMANY, format3.getLocale()); assertEquals(Locale.GERMANY, format3.getLocale());
} }
};
}
@Test @Test
public void testCheckDefaults() { public void testCheckDefaults() {

View File

@ -30,7 +30,9 @@
import java.util.TimeZone; import java.util.TimeZone;
import org.apache.commons.lang3.SerializationUtils; import org.apache.commons.lang3.SerializationUtils;
import org.apache.commons.lang3.test.DefaultTimeZoneAndLocale; import org.apache.commons.lang3.test.SystemDefaultsSwitch;
import org.apache.commons.lang3.test.SystemDefaults;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
/** /**
@ -73,56 +75,54 @@ protected DatePrinter getInstance(final String format, final TimeZone timeZone,
return new FastDatePrinter(format, timeZone, locale); return new FastDatePrinter(format, timeZone, locale);
} }
@Rule
public SystemDefaultsSwitch defaults = new SystemDefaultsSwitch();
@SystemDefaults(timezone="America/New_York", locale="en_US")
@Test @Test
public void testFormat() { public void testFormat() {
new DefaultTimeZoneAndLocale<RuntimeException>(NEW_YORK, Locale.US) { final GregorianCalendar cal1 = new GregorianCalendar(2003, 0, 10, 15, 33, 20);
@Override final GregorianCalendar cal2 = new GregorianCalendar(2003, 6, 10, 9, 0, 0);
public void test() { final Date date1 = cal1.getTime();
final Date date2 = cal2.getTime();
final long millis1 = date1.getTime();
final long millis2 = date2.getTime();
final GregorianCalendar cal1 = new GregorianCalendar(2003, 0, 10, 15, 33, 20); DatePrinter fdf = getInstance("yyyy-MM-dd'T'HH:mm:ss");
final GregorianCalendar cal2 = new GregorianCalendar(2003, 6, 10, 9, 0, 0); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
final Date date1 = cal1.getTime(); assertEquals(sdf.format(date1), fdf.format(date1));
final Date date2 = cal2.getTime(); assertEquals("2003-01-10T15:33:20", fdf.format(date1));
final long millis1 = date1.getTime(); assertEquals("2003-01-10T15:33:20", fdf.format(cal1));
final long millis2 = date2.getTime(); assertEquals("2003-01-10T15:33:20", fdf.format(millis1));
assertEquals("2003-07-10T09:00:00", fdf.format(date2));
assertEquals("2003-07-10T09:00:00", fdf.format(cal2));
assertEquals("2003-07-10T09:00:00", fdf.format(millis2));
DatePrinter fdf = getInstance("yyyy-MM-dd'T'HH:mm:ss"); fdf = getInstance("Z");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); assertEquals("-0500", fdf.format(date1));
assertEquals(sdf.format(date1), fdf.format(date1)); assertEquals("-0500", fdf.format(cal1));
assertEquals("2003-01-10T15:33:20", fdf.format(date1)); assertEquals("-0500", fdf.format(millis1));
assertEquals("2003-01-10T15:33:20", fdf.format(cal1));
assertEquals("2003-01-10T15:33:20", fdf.format(millis1));
assertEquals("2003-07-10T09:00:00", fdf.format(date2));
assertEquals("2003-07-10T09:00:00", fdf.format(cal2));
assertEquals("2003-07-10T09:00:00", fdf.format(millis2));
fdf = getInstance("Z"); assertEquals("-0400", fdf.format(date2));
assertEquals("-0500", fdf.format(date1)); assertEquals("-0400", fdf.format(cal2));
assertEquals("-0500", fdf.format(cal1)); assertEquals("-0400", fdf.format(millis2));
assertEquals("-0500", fdf.format(millis1));
assertEquals("-0400", fdf.format(date2)); fdf = getInstance("ZZ");
assertEquals("-0400", fdf.format(cal2)); assertEquals("-05:00", fdf.format(date1));
assertEquals("-0400", fdf.format(millis2)); assertEquals("-05:00", fdf.format(cal1));
assertEquals("-05:00", fdf.format(millis1));
fdf = getInstance("ZZ"); assertEquals("-04:00", fdf.format(date2));
assertEquals("-05:00", fdf.format(date1)); assertEquals("-04:00", fdf.format(cal2));
assertEquals("-05:00", fdf.format(cal1)); assertEquals("-04:00", fdf.format(millis2));
assertEquals("-05:00", fdf.format(millis1));
assertEquals("-04:00", fdf.format(date2)); final String pattern = "GGGG GGG GG G yyyy yyy yy y MMMM MMM MM M" +
assertEquals("-04:00", fdf.format(cal2)); " dddd ddd dd d DDDD DDD DD D EEEE EEE EE E aaaa aaa aa a zzzz zzz zz z";
assertEquals("-04:00", fdf.format(millis2)); fdf = getInstance(pattern);
sdf = new SimpleDateFormat(pattern);
final String pattern = "GGGG GGG GG G yyyy yyy yy y MMMM MMM MM M" + // SDF bug fix starting with Java 7
" dddd ddd dd d DDDD DDD DD D EEEE EEE EE E aaaa aaa aa a zzzz zzz zz z"; assertEquals(sdf.format(date1).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date1));
fdf = getInstance(pattern); assertEquals(sdf.format(date2).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date2));
sdf = new SimpleDateFormat(pattern);
// SDF bug fix starting with Java 7
assertEquals(sdf.format(date1).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date1));
assertEquals(sdf.format(date2).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date2));
}
};
} }
/** /**
@ -261,6 +261,7 @@ public void testTimeZoneMatches() {
assertEquals(NEW_YORK, printer.getTimeZone()); assertEquals(NEW_YORK, printer.getTimeZone());
} }
@SystemDefaults(timezone="UTC")
@Test @Test
public void testTimeZoneAsZ() throws Exception { public void testTimeZoneAsZ() throws Exception {
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));