From 2d29e1bff0c5c599da2104b6e10fed29fbb5bf4b Mon Sep 17 00:00:00 2001 From: Goetz Lindenmaier Date: Sat, 18 Jan 2025 14:13:33 +0000 Subject: [PATCH] 8316696: Remove the testing base classes: IntlTest and CollatorTest Reviewed-by: mdoerr Backport-of: b859da9c548fbd1463b336059d1c55312c7b7ba4 --- .../text/BreakIterator/BreakIteratorTest.java | 194 +++--- .../java/text/BreakIterator/Bug4533872.java | 36 +- .../CharacterIteratorTest.java | 86 +-- test/jdk/java/text/Collator/APITest.java | 102 +-- test/jdk/java/text/Collator/Bug6271411.java | 22 +- test/jdk/java/text/Collator/CollatorTest.java | 141 ---- test/jdk/java/text/Collator/DanishTest.java | 21 +- test/jdk/java/text/Collator/DummyTest.java | 26 +- test/jdk/java/text/Collator/EnglishTest.java | 24 +- test/jdk/java/text/Collator/FinnishTest.java | 19 +- test/jdk/java/text/Collator/FrenchTest.java | 18 +- test/jdk/java/text/Collator/G7Test.java | 38 +- test/jdk/java/text/Collator/GermanTest.java | 19 +- test/jdk/java/text/Collator/IteratorTest.java | 44 +- test/jdk/java/text/Collator/MonkeyTest.java | 29 +- test/jdk/java/text/Collator/Regression.java | 137 ++-- test/jdk/java/text/Collator/SpanishTest.java | 19 +- .../java/text/Collator/SurrogatesTest.java | 21 +- test/jdk/java/text/Collator/Test4401726.java | 18 +- test/jdk/java/text/Collator/ThaiTest.java | 14 +- test/jdk/java/text/Collator/TurkishTest.java | 19 +- .../java/text/Collator/VietnameseTest.java | 19 +- .../Format/ChoiceFormat/Bug4185732Test.java | 51 +- .../text/Format/DateFormat/Bug4322313.java | 24 +- .../DateFormat/DateFormatRegression.java | 280 ++++---- .../DateFormat/DateFormatRoundTripTest.java | 35 +- .../Format/DateFormat/DateFormatTest.java | 292 ++++---- .../Format/DateFormat/IntlTestDateFormat.java | 51 +- .../DateFormat/IntlTestDateFormatAPI.java | 71 +- .../DateFormat/IntlTestDateFormatSymbols.java | 52 +- .../IntlTestSimpleDateFormatAPI.java | 66 +- .../Format/DateFormat/TimeZoneNameTest.java | 43 +- .../text/Format/DateFormat/bug4358730.java | 17 +- .../Format/MessageFormat/Bug4185816Test.java | 56 +- .../MessageFormat/MessageRegression.java | 265 +++---- .../Format/MessageFormat/MessageTest.java | 25 +- .../text/Format/MessageFormat/bug4492719.java | 26 +- .../Format/NumberFormat/BigDecimalFormat.java | 21 +- .../Format/NumberFormat/BigDecimalParse.java | 88 ++- .../text/Format/NumberFormat/Bug4838107.java | 6 +- .../Format/NumberFormat/DFSExponential.java | 30 +- .../Format/NumberFormat/DFSSerialization.java | 35 +- .../IntlTestDecimalFormatAPI.java | 93 +-- .../IntlTestDecimalFormatSymbols.java | 40 +- .../NumberFormat/IntlTestNumberFormatAPI.java | 71 +- .../Format/NumberFormat/NumberRegression.java | 514 ++++++++------ .../Format/NumberFormat/NumberRoundTrip.java | 52 +- .../text/Format/NumberFormat/NumberTest.java | 129 ++-- .../Format/NumberFormat/PositionTest.java | 82 ++- .../Format/common/FormatIteratorTest.java | 96 ++- .../java/text/Normalizer/ICUBasicTest.java | 72 +- .../text/Normalizer/NormalizerAPITest.java | 48 +- test/jdk/java/text/testlib/HexDumpReader.java | 11 +- test/jdk/java/text/testlib/IntlTest.java | 262 ------- test/jdk/java/text/testlib/TestUtils.java | 132 +++- .../java/util/Calendar/CalendarLimitTest.java | 44 +- .../util/Calendar/CalendarRegression.java | 655 ++++++++++-------- test/jdk/java/util/Calendar/CalendarTest.java | 242 ++++--- .../java/util/Calendar/FieldStateTest.java | 83 ++- .../util/Calendar/GregorianCutoverTest.java | 148 ++-- test/jdk/java/util/Calendar/JulianTest.java | 15 +- .../java/util/Calendar/NonLenientTest.java | 43 +- test/jdk/java/util/Calendar/bug4243802.java | 11 +- test/jdk/java/util/Calendar/bug4316678.java | 4 +- test/jdk/java/util/Calendar/bug4372743.java | 5 +- test/jdk/java/util/Calendar/bug4409072.java | 43 +- test/jdk/java/util/Date/DateRegression.java | 79 ++- test/jdk/java/util/Date/DateTest.java | 62 +- test/jdk/java/util/Date/TimestampTest.java | 23 +- .../Locale/LegacyCodesClassInvariant.java | 66 +- .../java/util/Locale/LocaleEnhanceTest.java | 86 ++- test/jdk/java/util/Locale/LocaleTest.java | 230 +++--- test/jdk/java/util/TimeZone/Bug4322313.java | 29 +- test/jdk/java/util/TimeZone/Bug6329116.java | 25 +- .../util/TimeZone/TimeZoneBoundaryTest.java | 223 +++--- .../util/TimeZone/TimeZoneRegression.java | 182 ++--- test/jdk/java/util/TimeZone/TimeZoneTest.java | 160 +++-- .../java/util/TimeZone/TransitionTest.java | 28 +- .../sun/util/resources/TimeZone/IntlTest.java | 228 ------ 79 files changed, 3377 insertions(+), 3539 deletions(-) delete mode 100644 test/jdk/java/text/Collator/CollatorTest.java delete mode 100644 test/jdk/java/text/testlib/IntlTest.java delete mode 100644 test/jdk/sun/util/resources/TimeZone/IntlTest.java diff --git a/test/jdk/java/text/BreakIterator/BreakIteratorTest.java b/test/jdk/java/text/BreakIterator/BreakIteratorTest.java index 703adc1fadc..017530d4e1e 100644 --- a/test/jdk/java/text/BreakIterator/BreakIteratorTest.java +++ b/test/jdk/java/text/BreakIterator/BreakIteratorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,8 +26,7 @@ * @bug 4035266 4052418 4068133 4068137 4068139 4086052 4095322 4097779 * 4097920 4098467 4111338 4113835 4117554 4143071 4146175 4152117 * 4152416 4153072 4158381 4214367 4217703 4638433 8264765 - * @library /java/text/testlib - * @run main/timeout=2000 BreakIteratorTest + * @run junit/timeout=2000 BreakIteratorTest * @summary test BreakIterator */ @@ -75,24 +74,16 @@ import java.util.Enumeration; import java.io.*; -public class BreakIteratorTest extends IntlTest -{ - private BreakIterator characterBreak; - private BreakIterator wordBreak; - private BreakIterator lineBreak; - private BreakIterator sentenceBreak; +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new BreakIteratorTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class BreakIteratorTest { + private final BreakIterator characterBreak = BreakIterator.getCharacterInstance(); + private final BreakIterator wordBreak = BreakIterator.getWordInstance(); + private final BreakIterator lineBreak = BreakIterator.getLineInstance(); + private final BreakIterator sentenceBreak = BreakIterator.getSentenceInstance(); - public BreakIteratorTest() - { - characterBreak = BreakIterator.getCharacterInstance(); - wordBreak = BreakIterator.getWordInstance(); - lineBreak = BreakIterator.getLineInstance(); - sentenceBreak = BreakIterator.getSentenceInstance(); - } //========================================================================= // general test subroutines @@ -112,15 +103,12 @@ private void generalIteratorTest(BreakIterator bi, Vector expectedResult) { Vector nextResults = testFirstAndNext(bi, text); Vector previousResults = testLastAndPrevious(bi, text); - logln("comparing forward and backward..."); - int errs = getErrorCount(); + System.out.println("comparing forward and backward..."); compareFragmentLists("forward iteration", "backward iteration", nextResults, previousResults); - if (getErrorCount() == errs) { - logln("comparing expected and actual..."); - compareFragmentLists("expected result", "actual result", expectedResult, - nextResults); - } + System.out.println("comparing expected and actual..."); + compareFragmentLists("expected result", "actual result", expectedResult, + nextResults); int[] boundaries = new int[expectedResult.size() + 3]; boundaries[0] = BreakIterator.DONE; @@ -143,19 +131,19 @@ private Vector testFirstAndNext(BreakIterator bi, String text) { Vector result = new Vector(); if (p != 0) - errln("first() returned " + p + " instead of 0"); + fail("first() returned " + p + " instead of 0"); while (p != BreakIterator.DONE) { p = bi.next(); if (p != BreakIterator.DONE) { if (p <= lastP) - errln("next() failed to move forward: next() on position " + fail("next() failed to move forward: next() on position " + lastP + " yielded " + p); result.addElement(text.substring(lastP, p)); } else { if (lastP != text.length()) - errln("next() returned DONE prematurely: offset was " + fail("next() returned DONE prematurely: offset was " + lastP + " instead of " + text.length()); } lastP = p; @@ -169,19 +157,19 @@ private Vector testLastAndPrevious(BreakIterator bi, String text) { Vector result = new Vector(); if (p != text.length()) - errln("last() returned " + p + " instead of " + text.length()); + fail("last() returned " + p + " instead of " + text.length()); while (p != BreakIterator.DONE) { p = bi.previous(); if (p != BreakIterator.DONE) { if (p >= lastP) - errln("previous() failed to move backward: previous() on position " + fail("previous() failed to move backward: previous() on position " + lastP + " yielded " + p); result.insertElementAt(text.substring(p, lastP), 0); } else { if (lastP != 0) - errln("previous() returned DONE prematurely: offset was " + fail("previous() returned DONE prematurely: offset was " + lastP + " instead of 0"); } lastP = p; @@ -224,27 +212,28 @@ private void compareFragmentLists(String f1Name, String f2Name, Vector f1, Vecto ++tempP2; } } - logln("*** " + f1Name + " has:"); + System.out.println("*** " + f1Name + " has:"); while (p1 <= tempP1 && p1 < f1.size()) { s1 = (String)f1.elementAt(p1); t1 += s1.length(); debugLogln(" *** >" + s1 + "<"); ++p1; } - logln("***** " + f2Name + " has:"); + System.out.println("***** " + f2Name + " has:"); while (p2 <= tempP2 && p2 < f2.size()) { s2 = (String)f2.elementAt(p2); t2 += s2.length(); debugLogln(" ***** >" + s2 + "<"); ++p2; } - errln("Discrepancy between " + f1Name + " and " + f2Name + "\n---\n" + f1 +"\n---\n" + f2); + fail("Discrepancy between " + f1Name + " and " + f2Name + + "\n---\n" + f1 +"\n---\n" + f2); } } } private void testFollowing(BreakIterator bi, String text, int[] boundaries) { - logln("testFollowing():"); + System.out.println("testFollowing():"); int p = 2; int i = 0; try { @@ -253,59 +242,59 @@ private void testFollowing(BreakIterator bi, String text, int[] boundaries) { ++p; int b = bi.following(i); - logln("bi.following(" + i + ") -> " + b); + System.out.println("bi.following(" + i + ") -> " + b); if (b != boundaries[p]) - errln("Wrong result from following() for " + i + ": expected " + boundaries[p] + fail("Wrong result from following() for " + i + ": expected " + boundaries[p] + ", got " + b); } } catch (IllegalArgumentException illargExp) { - errln("IllegalArgumentException caught from following() for offset: " + i); + fail("IllegalArgumentException caught from following() for offset: " + i); } } private void testPreceding(BreakIterator bi, String text, int[] boundaries) { - logln("testPreceding():"); + System.out.println("testPreceding():"); int p = 0; int i = 0; try { for (i = 0; i <= text.length(); i++) { // change to <= when new BI code goes in int b = bi.preceding(i); - logln("bi.preceding(" + i + ") -> " + b); + System.out.println("bi.preceding(" + i + ") -> " + b); if (b != boundaries[p]) - errln("Wrong result from preceding() for " + i + ": expected " + boundaries[p] + fail("Wrong result from preceding() for " + i + ": expected " + boundaries[p] + ", got " + b); if (i == boundaries[p + 1]) ++p; } } catch (IllegalArgumentException illargExp) { - errln("IllegalArgumentException caught from preceding() for offset: " + i); + fail("IllegalArgumentException caught from preceding() for offset: " + i); } } private void testIsBoundary(BreakIterator bi, String text, int[] boundaries) { - logln("testIsBoundary():"); + System.out.println("testIsBoundary():"); int p = 1; boolean isB; for (int i = 0; i <= text.length(); i++) { // change to <= when new BI code goes in isB = bi.isBoundary(i); - logln("bi.isBoundary(" + i + ") -> " + isB); + System.out.println("bi.isBoundary(" + i + ") -> " + isB); if (i == boundaries[p]) { if (!isB) - errln("Wrong result from isBoundary() for " + i + ": expected true, got false"); + fail("Wrong result from isBoundary() for " + i + ": expected true, got false"); ++p; } else { if (isB) - errln("Wrong result from isBoundary() for " + i + ": expected false, got true"); + fail("Wrong result from isBoundary() for " + i + ": expected false, got true"); } } } private void doMultipleSelectionTest(BreakIterator iterator, String testText) { - logln("Multiple selection test..."); + System.out.println("Multiple selection test..."); BreakIterator testIterator = (BreakIterator)iterator.clone(); int offset = iterator.first(); int testOffset; @@ -314,9 +303,9 @@ private void doMultipleSelectionTest(BreakIterator iterator, String testText) do { testOffset = testIterator.first(); testOffset = testIterator.next(count); - logln("next(" + count + ") -> " + testOffset); + System.out.println("next(" + count + ") -> " + testOffset); if (offset != testOffset) - errln("next(n) and next() not returning consistent results: for step " + count + ", next(n) returned " + testOffset + " and next() had " + offset); + fail("next(n) and next() not returning consistent results: for step " + count + ", next(n) returned " + testOffset + " and next() had " + offset); if (offset != BreakIterator.DONE) { count++; @@ -331,9 +320,9 @@ private void doMultipleSelectionTest(BreakIterator iterator, String testText) do { testOffset = testIterator.last(); testOffset = testIterator.next(count); - logln("next(" + count + ") -> " + testOffset); + System.out.println("next(" + count + ") -> " + testOffset); if (offset != testOffset) - errln("next(n) and next() not returning consistent results: for step " + count + ", next(n) returned " + testOffset + " and next() had " + offset); + fail("next(n) and next() not returning consistent results: for step " + count + ", next(n) returned " + testOffset + " and next() had " + offset); if (offset != BreakIterator.DONE) { count--; @@ -379,7 +368,7 @@ private void doBreakInvariantTest(BreakIterator tb, String testChars) seen2 = true; } if (!seen2) { - errln("No break between U+" + Integer.toHexString((int)(work.charAt(1))) + fail("No break between U+" + Integer.toHexString((int)(work.charAt(1))) + " and U+" + Integer.toHexString((int)(work.charAt(2)))); errorCount++; if (errorCount >= 75) @@ -403,7 +392,7 @@ private void doOtherInvariantTest(BreakIterator tb, String testChars) tb.setText(work.toString()); for (int k = tb.first(); k != BreakIterator.DONE; k = tb.next()) if (k == 2) { - errln("Break between CR and LF in string U+" + Integer.toHexString( + fail("Break between CR and LF in string U+" + Integer.toHexString( (int)(work.charAt(0))) + ", U+d U+a U+" + Integer.toHexString( (int)(work.charAt(3)))); errorCount++; @@ -441,7 +430,7 @@ private void doOtherInvariantTest(BreakIterator tb, String testChars) tb.setText(work.toString()); for (int k = tb.first(); k != BreakIterator.DONE; k = tb.next()) if (k == 2) { - errln("Break between U+" + Integer.toHexString((int)(work.charAt(1))) + fail("Break between U+" + Integer.toHexString((int)(work.charAt(1))) + " and U+" + Integer.toHexString((int)(work.charAt(2)))); errorCount++; if (errorCount >= 75) @@ -466,13 +455,14 @@ public void debugLogln(String s) { out.append(temp); } } - logln(out.toString()); + System.out.println(out.toString()); } //========================================================================= // tests //========================================================================= + @Test public void TestWordBreak() { Vector wordSelectionData = new Vector(); @@ -556,6 +546,7 @@ public void TestWordBreak() { generalIteratorTest(wordBreak, wordSelectionData); } + @Test public void TestBug4097779() { Vector wordSelectionData = new Vector(); @@ -565,6 +556,7 @@ public void TestBug4097779() { generalIteratorTest(wordBreak, wordSelectionData); } + @Test public void TestBug4098467Words() { Vector wordSelectionData = new Vector(); @@ -594,6 +586,7 @@ public void TestBug4098467Words() { generalIteratorTest(wordBreak, wordSelectionData); } + @Test public void TestBug4117554Words() { Vector wordSelectionData = new Vector(); @@ -606,6 +599,7 @@ public void TestBug4117554Words() { generalIteratorTest(wordBreak, wordSelectionData); } + @Test public void TestSentenceBreak() { Vector sentenceSelectionData = new Vector(); @@ -641,6 +635,7 @@ public void TestSentenceBreak() { generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestBug4113835() { Vector sentenceSelectionData = new Vector(); @@ -650,6 +645,7 @@ public void TestBug4113835() { generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestBug4111338() { Vector sentenceSelectionData = new Vector(); @@ -669,6 +665,7 @@ public void TestBug4111338() { generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestBug4117554Sentences() { Vector sentenceSelectionData = new Vector(); @@ -691,6 +688,7 @@ public void TestBug4117554Sentences() { generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestBug4158381() { Vector sentenceSelectionData = new Vector(); @@ -708,6 +706,7 @@ public void TestBug4158381() { generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestBug4143071() { Vector sentenceSelectionData = new Vector(); @@ -719,6 +718,7 @@ public void TestBug4143071() { generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestBug4152416() { Vector sentenceSelectionData = new Vector(); @@ -731,6 +731,7 @@ public void TestBug4152416() { generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestBug4152117() { Vector sentenceSelectionData = new Vector(); @@ -749,6 +750,7 @@ public void TestBug4152117() { generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestBug8264765() { Vector sentenceSelectionData = new Vector(); @@ -760,6 +762,7 @@ public void TestBug8264765() { generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestLineBreak() { Vector lineSelectionData = new Vector(); @@ -796,6 +799,7 @@ public void TestLineBreak() { generalIteratorTest(lineBreak, lineSelectionData); } + @Test public void TestBug4068133() { Vector lineSelectionData = new Vector(); @@ -812,6 +816,7 @@ public void TestBug4068133() { generalIteratorTest(lineBreak, lineSelectionData); } + @Test public void TestBug4086052() { Vector lineSelectionData = new Vector(); @@ -821,6 +826,7 @@ public void TestBug4086052() { generalIteratorTest(lineBreak, lineSelectionData); } + @Test public void TestBug4097920() { Vector lineSelectionData = new Vector(); @@ -833,6 +839,7 @@ public void TestBug4097920() { generalIteratorTest(lineBreak, lineSelectionData); } /* + @Test public void TestBug4035266() { Vector lineSelectionData = new Vector(); @@ -846,6 +853,7 @@ public void TestBug4035266() { generalIteratorTest(lineBreak, lineSelectionData); } */ + @Test public void TestBug4098467Lines() { Vector lineSelectionData = new Vector(); @@ -871,13 +879,14 @@ public void TestBug4098467Lines() { lineSelectionData.addElement("\u110c\u1161\u11bc\u1105\u1169\u1100\u116d\u1112\u116c"); if (Locale.getDefault().getLanguage().equals("th")) { - logln("This test is skipped in th locale."); + System.out.println("This test is skipped in th locale."); return; } generalIteratorTest(lineBreak, lineSelectionData); } + @Test public void TestBug4117554Lines() { Vector lineSelectionData = new Vector(); @@ -889,9 +898,10 @@ public void TestBug4117554Lines() { generalIteratorTest(lineBreak, lineSelectionData); } + @Test public void TestBug4217703() { if (Locale.getDefault().getLanguage().equals("th")) { - logln("This test is skipped in th locale."); + System.out.println("This test is skipped in th locale."); return; } @@ -918,6 +928,7 @@ public void TestBug4217703() { private static final String circumflexA = "a\u0302"; private static final String tildeE = "e\u0303"; + @Test public void TestCharacterBreak() { Vector characterSelectionData = new Vector(); @@ -949,6 +960,7 @@ public void TestCharacterBreak() { generalIteratorTest(characterBreak, characterSelectionData); } + @Test public void TestBug4098467Characters() { Vector characterSelectionData = new Vector(); @@ -989,6 +1001,7 @@ public void TestBug4098467Characters() { generalIteratorTest(characterBreak, characterSelectionData); } + @Test public void TestBug4153072() { BreakIterator iter = BreakIterator.getWordInstance(); String str = "...Hello, World!..."; @@ -1002,17 +1015,18 @@ public void TestBug4153072() { try { dummy = iter.isBoundary(index); if (index < begin) - errln("Didn't get exception with offset = " + index + + fail("Didn't get exception with offset = " + index + " and begin index = " + begin); } catch (IllegalArgumentException e) { if (index >= begin) - errln("Got exception with offset = " + index + + fail("Got exception with offset = " + index + " and begin index = " + begin); } } } + @Test public void TestBug4146175Sentences() { Vector sentenceSelectionData = new Vector(); @@ -1028,9 +1042,10 @@ public void TestBug4146175Sentences() { generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestBug4146175Lines() { if (Locale.getDefault().getLanguage().equals("th")) { - logln("This test is skipped in th locale."); + System.out.println("This test is skipped in th locale."); return; } @@ -1043,9 +1058,10 @@ public void TestBug4146175Lines() { generalIteratorTest(lineBreak, lineSelectionData); } + @Test public void TestBug4214367() { if (Locale.getDefault().getLanguage().equals("th")) { - logln("This test is skipped in th locale."); + System.out.println("This test is skipped in th locale."); return; } @@ -1067,16 +1083,18 @@ public void TestBug4214367() { + "\u2001\u2002\u200c\u200d\u200e\u200f\u2010\u2011\u2012\u2028\u2029\u202a\u203e\u203f" + "\u2040\u20dd\u20de\u20df\u20e0\u2160\u2161\u2162\u2163\u2164"; + @Test public void TestSentenceInvariants() { BreakIterator e = BreakIterator.getSentenceInstance(); doOtherInvariantTest(e, cannedTestChars + ".,\u3001\u3002\u3041\u3042\u3043\ufeff"); } + @Test public void TestWordInvariants() { if (Locale.getDefault().getLanguage().equals("th")) { - logln("This test is skipped in th locale."); + System.out.println("This test is skipped in th locale."); return; } @@ -1087,10 +1105,11 @@ public void TestWordInvariants() + "\u30a3\u4e00\u4e01\u4e02"); } + @Test public void TestLineInvariants() { if (Locale.getDefault().getLanguage().equals("th")) { - logln("This test is skipped in th locale."); + System.out.println("This test is skipped in th locale."); return; } @@ -1139,7 +1158,7 @@ public void TestLineInvariants() work.charAt(l) == '\ufeff')) { continue; } - errln("Got break between U+" + Integer.toHexString((int) + fail("Got break between U+" + Integer.toHexString((int) (work.charAt(l - 1))) + " and U+" + Integer.toHexString( (int)(work.charAt(l)))); errorCount++; @@ -1192,7 +1211,7 @@ public void TestLineInvariants() if (l == 2) saw2 = true; if (!saw2) { - errln("Didn't get break between U+" + Integer.toHexString((int) + fail("Didn't get break between U+" + Integer.toHexString((int) (work.charAt(1))) + " and U+" + Integer.toHexString( (int)(work.charAt(2)))); errorCount++; @@ -1205,6 +1224,7 @@ public void TestLineInvariants() */ } + @Test public void TestCharacterInvariants() { BreakIterator e = BreakIterator.getCharacterInstance(); @@ -1214,6 +1234,7 @@ public void TestCharacterInvariants() + "\u11a9\u11aa"); } + @Test public void TestEmptyString() { String text = ""; @@ -1223,12 +1244,13 @@ public void TestEmptyString() generalIteratorTest(lineBreak, x); } + @Test public void TestGetAvailableLocales() { Locale[] locList = BreakIterator.getAvailableLocales(); if (locList.length == 0) - errln("getAvailableLocales() returned an empty list!"); + fail("getAvailableLocales() returned an empty list!"); // I have no idea how to test this function... } @@ -1236,6 +1258,7 @@ public void TestGetAvailableLocales() /** * Bug 4095322 */ + @Test public void TestJapaneseLineBreak() { StringBuffer testString = new StringBuffer("\u4e00x\u4e8c"); @@ -1284,18 +1307,18 @@ public void TestJapaneseLineBreak() iter.setText(testString.toString()); int j = iter.first(); if (j != 0) { - errln("ja line break failure: failed to start at 0 and bounced at " + j); + fail("ja line break failure: failed to start at 0 and bounced at " + j); } j = iter.next(); if (j != 1) { - errln("ja line break failure: failed to stop before '" + fail("ja line break failure: failed to stop before '" + precedingChars.charAt(i) + "' (\\u" + Integer.toString(precedingChars.charAt(i), 16) + ") at 1 and bounded at " + j); } j = iter.next(); if (j != 3) { - errln("ja line break failure: failed to skip position after '" + fail("ja line break failure: failed to skip position after '" + precedingChars.charAt(i) + "' (\\u" + Integer.toString(precedingChars.charAt(i), 16) + ") at 3 and bounded at " + j); @@ -1307,18 +1330,18 @@ public void TestJapaneseLineBreak() iter.setText(testString.toString()); int j = iter.first(); if (j != 0) { - errln("ja line break failure: failed to start at 0 and bounded at " + j); + fail("ja line break failure: failed to start at 0 and bounded at " + j); } j = iter.next(); if (j != 2) { - errln("ja line break failure: failed to skip position before '" + fail("ja line break failure: failed to skip position before '" + followingChars.charAt(i) + "' (\\u" + Integer.toString(followingChars.charAt(i), 16) + ") at 2 and bounded at " + j); } j = iter.next(); if (j != 3) { - errln("ja line break failure: failed to stop after '" + fail("ja line break failure: failed to stop after '" + followingChars.charAt(i) + "' (\\u" + Integer.toString(followingChars.charAt(i), 16) + ") at 3 and bounded at " + j); @@ -1329,6 +1352,7 @@ public void TestJapaneseLineBreak() /** * Bug 4638433 */ + @Test public void TestLineBreakBasedOnUnicode3_0_0() { BreakIterator iter; @@ -1342,7 +1366,7 @@ public void TestLineBreakBasedOnUnicode3_0_0() i = iter.first(); i = iter.next(); if (i != 5) { - errln("Word break failure: failed to stop at 5 and bounded at " + i); + fail("Word break failure: failed to stop at 5 and bounded at " + i); } @@ -1355,7 +1379,7 @@ public void TestLineBreakBasedOnUnicode3_0_0() i = iter.first(); i = iter.next(); if (i != 3) { - errln("Line break failure: failed to skip before \\u301F(Pe) at 3 and bounded at " + i); + fail("Line break failure: failed to skip before \\u301F(Pe) at 3 and bounded at " + i); } /* Mongolian @@ -1365,7 +1389,7 @@ public void TestLineBreakBasedOnUnicode3_0_0() i = iter.first(); i = iter.next(); if (i != 2) { - errln("Mongolian line break failure: failed to skip position before \\u1806(Pd) at 2 and bounded at " + i); + fail("Mongolian line break failure: failed to skip position before \\u1806(Pd) at 2 and bounded at " + i); } /* Khmer which have @@ -1375,11 +1399,11 @@ public void TestLineBreakBasedOnUnicode3_0_0() i = iter.first(); i = iter.next(); if (i != 1) { - errln("Khmer line break failure: failed to stop before \\u17DB(Sc) at 1 and bounded at " + i); + fail("Khmer line break failure: failed to stop before \\u17DB(Sc) at 1 and bounded at " + i); } i = iter.next(); if (i != 3) { - errln("Khmer line break failure: failed to skip position after \\u17DB(Sc) at 3 and bounded at " + i); + fail("Khmer line break failure: failed to skip position after \\u17DB(Sc) at 3 and bounded at " + i); } /* Ogham which have @@ -1389,7 +1413,7 @@ public void TestLineBreakBasedOnUnicode3_0_0() i = iter.first(); i = iter.next(); if (i != 2) { - errln("Ogham line break failure: failed to skip postion before \\u1680(Zs) at 2 and bounded at " + i); + fail("Ogham line break failure: failed to skip postion before \\u1680(Zs) at 2 and bounded at " + i); } @@ -1406,17 +1430,18 @@ public void TestLineBreakBasedOnUnicode3_0_0() i = iter.first(); i = iter.next(); if (i != 1) { - errln("Thai line break failure: failed to stop before \\u201C(Pi) at 1 and bounded at " + i); + fail("Thai line break failure: failed to stop before \\u201C(Pi) at 1 and bounded at " + i); } i = iter.next(); if (i != 4) { - errln("Thai line break failure: failed to stop after \\u201D(Pf) at 4 and bounded at " + i); + fail("Thai line break failure: failed to stop after \\u201D(Pf) at 4 and bounded at " + i); } } /** * Bug 4068137 */ + @Test public void TestEndBehavior() { String testString = "boo."; @@ -1424,11 +1449,11 @@ public void TestEndBehavior() wb.setText(testString); if (wb.first() != 0) - errln("Didn't get break at beginning of string."); + fail("Didn't get break at beginning of string."); if (wb.next() != 3) - errln("Didn't get break before period in \"boo.\""); + fail("Didn't get break before period in \"boo.\""); if (wb.current() != 4 && wb.next() != 4) - errln("Didn't get break at end of string."); + fail("Didn't get break at end of string."); } // [serialization test has been removed pursuant to bug #4152965] @@ -1436,6 +1461,7 @@ public void TestEndBehavior() /** * Bug 4450804 */ + @Test public void TestLineBreakContractions() { Vector expected = new Vector(); diff --git a/test/jdk/java/text/BreakIterator/Bug4533872.java b/test/jdk/java/text/BreakIterator/Bug4533872.java index 64a4ccf569e..b6a6f16340c 100644 --- a/test/jdk/java/text/BreakIterator/Bug4533872.java +++ b/test/jdk/java/text/BreakIterator/Bug4533872.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,18 +24,18 @@ /** * @test * @bug 4533872 4640853 - * @library /java/text/testlib * @summary Unit tests for supplementary character support (JSR-204) and Unicode 4.0 support + * @run junit Bug4533872 */ import java.text.BreakIterator; import java.util.Locale; -public class Bug4533872 extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new Bug4533872().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class Bug4533872 { static final String[] given = { /* Lu Nd Lu Ll */ @@ -73,7 +73,7 @@ void TestNext() { end = iter.next(); if (!expected[i][j].equals(given[i].substring(start, end))) { - errln("Word break failure: printEachForward() expected:<" + + fail("Word break failure: printEachForward() expected:<" + expected[i][j] + ">, got:<" + given[i].substring(start, end) + "> start=" + start + " end=" + end); @@ -95,7 +95,7 @@ void TestIsBoundary() { while (end < given[i].length()) { if (!iter.isBoundary(end)) { - errln("Word break failure: isBoundary() This should be a boundary. Index=" + + fail("Word break failure: isBoundary() This should be a boundary. Index=" + end + " for " + given[i]); } end = iter.next(); @@ -122,7 +122,7 @@ void TestPrintEachForward() { // Check current()'s return value - should be same as first()'s. current = iter.current(); if (start != current) { - errln("Word break failure: printEachForward() Unexpected current value: current()=" + + fail("Word break failure: printEachForward() Unexpected current value: current()=" + current + ", expected(=first())=" + start); } @@ -134,12 +134,12 @@ void TestPrintEachForward() { // Check current()'s return value - should be same as next()'s. current = iter.current(); if (end != current) { - errln("Word break failure: printEachForward() Unexpected current value: current()=" + + fail("Word break failure: printEachForward() Unexpected current value: current()=" + current + ", expected(=next())=" + end); } if (!expected[i][j].equals(given[i].substring(start, end))) { - errln("Word break failure: printEachForward() expected:<" + + fail("Word break failure: printEachForward() expected:<" + expected[i][j] + ">, got:<" + given[i].substring(start, end) + "> start=" + start + " end=" + end); @@ -161,7 +161,7 @@ void TestPrintEachBackward() { // Check current()'s return value - should be same as last()'s. current = iter.current(); if (end != current) { - errln("Word break failure: printEachBackward() Unexpected current value: current()=" + + fail("Word break failure: printEachBackward() Unexpected current value: current()=" + current + ", expected(=last())=" + end); } @@ -173,12 +173,12 @@ void TestPrintEachBackward() { // Check current()'s return value - should be same as previous()'s. current = iter.current(); if (start != current) { - errln("Word break failure: printEachBackward() Unexpected current value: current()=" + + fail("Word break failure: printEachBackward() Unexpected current value: current()=" + current + ", expected(=previous())=" + start); } if (!expected[i][j].equals(given[i].substring(start, end))) { - errln("Word break failure: printEachBackward() expected:<" + + fail("Word break failure: printEachBackward() expected:<" + expected[i][j] + ">, got:<" + given[i].substring(start, end) + "> start=" + start + " end=" + end); @@ -207,7 +207,7 @@ void TestPrintAt_1() { start = iter.previous(); if (!expected[i][j].equals(given[i].substring(start, end))) { - errln("Word break failure: printAt_1() expected:<" + + fail("Word break failure: printAt_1() expected:<" + expected[i][j] + ">, got:<" + given[i].substring(start, end) + "> start=" + start + " end=" + end); @@ -234,7 +234,7 @@ void TestPrintAt_2() { // Check preceding(0)'s return value - should equals BreakIterator.DONE. if (iter.preceding(0) != BreakIterator.DONE) { - errln("Word break failure: printAt_2() expected:-1(BreakIterator.DONE), got:" + + fail("Word break failure: printAt_2() expected:-1(BreakIterator.DONE), got:" + iter.preceding(0)); } @@ -243,7 +243,7 @@ void TestPrintAt_2() { end = iter.next(); if (!expected[i][j].equals(given[i].substring(start, end))) { - errln("Word break failure: printAt_2() expected:<" + + fail("Word break failure: printAt_2() expected:<" + expected[i][j] + ">, got:<" + given[i].substring(start, end) + "> start=" + start + " end=" + end); @@ -254,7 +254,7 @@ void TestPrintAt_2() { end = iter.last(); start = iter.next(); if (start != BreakIterator.DONE) { - errln("Word break failure: printAt_2() expected:-1(BreakIterator.DONE), got:" + start); + fail("Word break failure: printAt_2() expected:-1(BreakIterator.DONE), got:" + start); } } } diff --git a/test/jdk/java/text/CharacterIterator/CharacterIteratorTest.java b/test/jdk/java/text/CharacterIterator/CharacterIteratorTest.java index 48133100e73..a559c3897b2 100644 --- a/test/jdk/java/text/CharacterIterator/CharacterIteratorTest.java +++ b/test/jdk/java/text/CharacterIterator/CharacterIteratorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,8 +23,8 @@ /* * @test - * @library /java/text/testlib * @summary test for Character Iterator + * @run junit CharacterIteratorTest */ /* @@ -65,14 +65,15 @@ import java.text.*; -public class CharacterIteratorTest extends IntlTest { - public static void main(String[] args) throws Exception { - new CharacterIteratorTest().run(args); - } +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; +public class CharacterIteratorTest { public CharacterIteratorTest() { } + @Test public void TestConstructionAndEquality() { String testText = "Now is the time for all good men to come to the aid of their country."; String testText2 = "Don't bother using this string."; @@ -84,49 +85,50 @@ public void TestConstructionAndEquality() { CharacterIterator test5 = (CharacterIterator)test1.clone(); if (test1.equals(test2) || test1.equals(test3) || test1.equals(test4)) - errln("Construation or equals() failed: Two unequal iterators tested equal"); + fail("Construation or equals() failed: Two unequal iterators tested equal"); if (!test1.equals(test5)) - errln("clone() or equals() failed: Two clones tested unequal"); + fail("clone() or equals() failed: Two clones tested unequal"); if (test1.hashCode() == test2.hashCode() || test1.hashCode() == test3.hashCode() || test1.hashCode() == test4.hashCode()) - errln("hash() failed: different objects have same hash code"); + fail("hash() failed: different objects have same hash code"); if (test1.hashCode() != test5.hashCode()) - errln("hash() failed: identical objects have different hash codes"); + fail("hash() failed: identical objects have different hash codes"); test1.setIndex(5); if (!test1.equals(test2) || test1.equals(test5)) - errln("setIndex() failed"); + fail("setIndex() failed"); } + @Test public void TestIteration() { String text = "Now is the time for all good men to come to the aid of their country."; CharacterIterator iter = new StringCharacterIterator(text, 5); if (iter.current() != text.charAt(5)) - errln("Iterator didn't start out in the right place."); + fail("Iterator didn't start out in the right place."); char c = iter.first(); int i = 0; if (iter.getBeginIndex() != 0 || iter.getEndIndex() != text.length()) - errln("getBeginIndex() or getEndIndex() failed"); + fail("getBeginIndex() or getEndIndex() failed"); - logln("Testing forward iteration..."); + System.out.println("Testing forward iteration..."); do { if (c == CharacterIterator.DONE && i != text.length()) - errln("Iterator reached end prematurely"); + fail("Iterator reached end prematurely"); else if (c != text.charAt(i)) - errln("Character mismatch at position " + i + ", iterator has " + c + + fail("Character mismatch at position " + i + ", iterator has " + c + ", string has " + text.charAt(c)); if (iter.current() != c) - errln("current() isn't working right"); + fail("current() isn't working right"); if (iter.getIndex() != i) - errln("getIndex() isn't working right"); + fail("getIndex() isn't working right"); if (c != CharacterIterator.DONE) { c = iter.next(); @@ -137,18 +139,18 @@ else if (c != text.charAt(i)) c = iter.last(); i = text.length() - 1; - logln("Testing backward iteration..."); + System.out.println("Testing backward iteration..."); do { if (c == CharacterIterator.DONE && i >= 0) - errln("Iterator reached end prematurely"); + fail("Iterator reached end prematurely"); else if (c != text.charAt(i)) - errln("Character mismatch at position " + i + ", iterator has " + c + + fail("Character mismatch at position " + i + ", iterator has " + c + ", string has " + text.charAt(c)); if (iter.current() != c) - errln("current() isn't working right"); + fail("current() isn't working right"); if (iter.getIndex() != i) - errln("getIndex() isn't working right"); + fail("getIndex() isn't working right"); if (c != CharacterIterator.DONE) { c = iter.previous(); @@ -158,26 +160,26 @@ else if (c != text.charAt(i)) iter = new StringCharacterIterator(text, 5, 15, 10); if (iter.getBeginIndex() != 5 || iter.getEndIndex() != 15) - errln("creation of a restricted-range iterator failed"); + fail("creation of a restricted-range iterator failed"); if (iter.getIndex() != 10 || iter.current() != text.charAt(10)) - errln("starting the iterator in the middle didn't work"); + fail("starting the iterator in the middle didn't work"); c = iter.first(); i = 5; - logln("Testing forward iteration over a range..."); + System.out.println("Testing forward iteration over a range..."); do { if (c == CharacterIterator.DONE && i != 15) - errln("Iterator reached end prematurely"); + fail("Iterator reached end prematurely"); else if (c != text.charAt(i)) - errln("Character mismatch at position " + i + ", iterator has " + c + + fail("Character mismatch at position " + i + ", iterator has " + c + ", string has " + text.charAt(c)); if (iter.current() != c) - errln("current() isn't working right"); + fail("current() isn't working right"); if (iter.getIndex() != i) - errln("getIndex() isn't working right"); + fail("getIndex() isn't working right"); if (c != CharacterIterator.DONE) { c = iter.next(); @@ -188,18 +190,18 @@ else if (c != text.charAt(i)) c = iter.last(); i = 14; - logln("Testing backward iteration over a range..."); + System.out.println("Testing backward iteration over a range..."); do { if (c == CharacterIterator.DONE && i >= 5) - errln("Iterator reached end prematurely"); + fail("Iterator reached end prematurely"); else if (c != text.charAt(i)) - errln("Character mismatch at position " + i + ", iterator has " + c + + fail("Character mismatch at position " + i + ", iterator has " + c + ", string has " + text.charAt(c)); if (iter.current() != c) - errln("current() isn't working right"); + fail("current() isn't working right"); if (iter.getIndex() != i) - errln("getIndex() isn't working right"); + fail("getIndex() isn't working right"); if (c != CharacterIterator.DONE) { c = iter.previous(); @@ -211,6 +213,7 @@ else if (c != text.charAt(i)) /** * @bug 4082050 4078261 4078255 */ + @Test public void TestPathologicalCases() { String text = "This is only a test."; @@ -227,7 +230,7 @@ public void TestPathologicalCases() { || iter.previous() != CharacterIterator.DONE || iter.current() != CharacterIterator.DONE || iter.getIndex() != 5) - errln("Got something other than DONE when performing operations on an empty StringCharacterIterator"); + fail("Got something other than DONE when performing operations on an empty StringCharacterIterator"); */ CharacterIterator iter = null; @@ -242,7 +245,7 @@ public void TestPathologicalCases() { gotException = true; } if (!gotException) - errln("StringCharacterIterator didn't throw an exception when given an invalid substring range."); + fail("StringCharacterIterator didn't throw an exception when given an invalid substring range."); // test for bug #4078255 (getting wrong value from next() when we're at the end // of the string) @@ -253,17 +256,17 @@ public void TestPathologicalCases() { iter.last(); actualIndex = iter.getIndex(); if (actualIndex != expectedIndex - 1) - errln("last() failed: expected " + (expectedIndex - 1) + ", got " + actualIndex); + fail("last() failed: expected " + (expectedIndex - 1) + ", got " + actualIndex); iter.next(); actualIndex = iter.getIndex(); if (actualIndex != expectedIndex) - errln("next() after last() failed: expected " + expectedIndex + ", got " + actualIndex); + fail("next() after last() failed: expected " + expectedIndex + ", got " + actualIndex); iter.next(); actualIndex = iter.getIndex(); if (actualIndex != expectedIndex) - errln("second next() after last() failed: expected " + expectedIndex + ", got " + actualIndex); + fail("second next() after last() failed: expected " + expectedIndex + ", got " + actualIndex); } /* @@ -271,6 +274,7 @@ public void TestPathologicalCases() { * #4123771 is actually a duplicate of bug #4051073, which was fixed some time ago, but * no one ever added a regression test for it. */ + @Test public void TestBug4123771() { String text = "Some string for testing"; StringCharacterIterator iter = new StringCharacterIterator(text); @@ -283,7 +287,7 @@ public void TestBug4123771() { System.out.println(" position: " + index); System.out.println(" getEndIndex(): " + iter.getEndIndex()); System.out.println(" text.length(): " + text.length()); - errln(""); // re-throw the exception through our test framework + fail(""); // re-throw the exception through our test framework } } } diff --git a/test/jdk/java/text/Collator/APITest.java b/test/jdk/java/text/Collator/APITest.java index 43782c5ad90..45cb52b851f 100644 --- a/test/jdk/java/text/Collator/APITest.java +++ b/test/jdk/java/text/Collator/APITest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @library /java/text/testlib * @summary test Collation API * @modules jdk.localedata + * @run junit APITest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -45,17 +46,16 @@ import java.text.CollationKey; import java.text.CollationElementIterator; -public class APITest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new APITest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class APITest { final void doAssert(boolean condition, String message) { if (!condition) { - err("ERROR: "); - errln(message); + fail("ERROR: " + message); } } @@ -64,103 +64,103 @@ public final void TestProperty( ) Collator col = null; try { col = Collator.getInstance(Locale.ROOT); - logln("The property tests begin : "); - logln("Test ctors : "); + System.out.println("The property tests begin : "); + System.out.println("Test ctors : "); doAssert(col.compare("ab", "abc") < 0, "ab < abc comparison failed"); doAssert(col.compare("ab", "AB") < 0, "ab < AB comparison failed"); doAssert(col.compare("black-bird", "blackbird") > 0, "black-bird > blackbird comparison failed"); doAssert(col.compare("black bird", "black-bird") < 0, "black bird < black-bird comparison failed"); doAssert(col.compare("Hello", "hello") > 0, "Hello > hello comparison failed"); - logln("Test ctors ends."); - logln("testing Collator.getStrength() method ..."); + System.out.println("Test ctors ends."); + System.out.println("testing Collator.getStrength() method ..."); doAssert(col.getStrength() == Collator.TERTIARY, "collation object has the wrong strength"); doAssert(col.getStrength() != Collator.PRIMARY, "collation object's strength is primary difference"); - logln("testing Collator.setStrength() method ..."); + System.out.println("testing Collator.setStrength() method ..."); col.setStrength(Collator.SECONDARY); doAssert(col.getStrength() != Collator.TERTIARY, "collation object's strength is secondary difference"); doAssert(col.getStrength() != Collator.PRIMARY, "collation object's strength is primary difference"); doAssert(col.getStrength() == Collator.SECONDARY, "collation object has the wrong strength"); - logln("testing Collator.setDecomposition() method ..."); + System.out.println("testing Collator.setDecomposition() method ..."); col.setDecomposition(Collator.NO_DECOMPOSITION); doAssert(col.getDecomposition() != Collator.FULL_DECOMPOSITION, "collation object's strength is secondary difference"); doAssert(col.getDecomposition() != Collator.CANONICAL_DECOMPOSITION, "collation object's strength is primary difference"); doAssert(col.getDecomposition() == Collator.NO_DECOMPOSITION, "collation object has the wrong strength"); } catch (Exception foo) { - errln("Error : " + foo.getMessage()); - errln("Default Collator creation failed."); + fail("Error : " + foo.getMessage() + + "\n Default Collator creation failed."); } - logln("Default collation property test ended."); - logln("Collator.getRules() testing ..."); + System.out.println("Default collation property test ended."); + System.out.println("Collator.getRules() testing ..."); doAssert(((RuleBasedCollator)col).getRules().length() != 0, "getRules() result incorrect" ); - logln("getRules tests end."); + System.out.println("getRules tests end."); try { col = Collator.getInstance(Locale.FRENCH); col.setStrength(Collator.PRIMARY); - logln("testing Collator.getStrength() method again ..."); + System.out.println("testing Collator.getStrength() method again ..."); doAssert(col.getStrength() != Collator.TERTIARY, "collation object has the wrong strength"); doAssert(col.getStrength() == Collator.PRIMARY, "collation object's strength is not primary difference"); - logln("testing French Collator.setStrength() method ..."); + System.out.println("testing French Collator.setStrength() method ..."); col.setStrength(Collator.TERTIARY); doAssert(col.getStrength() == Collator.TERTIARY, "collation object's strength is not tertiary difference"); doAssert(col.getStrength() != Collator.PRIMARY, "collation object's strength is primary difference"); doAssert(col.getStrength() != Collator.SECONDARY, "collation object's strength is secondary difference"); } catch (Exception bar) { - errln("Error : " + bar.getMessage()); - errln("Creating French collation failed."); + fail("Error : " + bar.getMessage() + + "\n Creating French collation failed."); } - logln("Create junk collation: "); + System.out.println("Create junk collation: "); Locale abcd = new Locale("ab", "CD", ""); Collator junk = null; try { junk = Collator.getInstance(abcd); } catch (Exception err) { - errln("Error : " + err.getMessage()); - errln("Junk collation creation failed, should at least return the collator for the base bundle."); + fail("Error : " + err.getMessage() + + "\n Junk collation creation failed, should at least return the collator for the base bundle."); } try { col = Collator.getInstance(Locale.ROOT); doAssert(col.equals(junk), "The base bundle's collation should be returned."); } catch (Exception exc) { - errln("Error : " + exc.getMessage()); - errln("Default collation comparison, caching not working."); + fail("Error : " + exc.getMessage() + + "\n Default collation comparison, caching not working."); } - logln("Collator property test ended."); + System.out.println("Collator property test ended."); } public final void TestHashCode( ) { - logln("hashCode tests begin."); + System.out.println("hashCode tests begin."); Collator col1 = null; try { col1 = Collator.getInstance(Locale.ROOT); } catch (Exception foo) { - errln("Error : " + foo.getMessage()); - errln("Default collation creation failed."); + fail("Error : " + foo.getMessage() + + "\n Default collation creation failed."); } Collator col2 = null; Locale dk = new Locale("da", "DK", ""); try { col2 = Collator.getInstance(dk); } catch (Exception bar) { - errln("Error : " + bar.getMessage()); - errln("Danish collation creation failed."); + fail("Error : " + bar.getMessage() + + "\n Danish collation creation failed."); return; } Collator col3 = null; try { col3 = Collator.getInstance(Locale.ROOT); } catch (Exception err) { - errln("Error : " + err.getMessage()); - errln("2nd default collation creation failed."); + fail("Error : " + err.getMessage() + + "\n 2nd default collation creation failed."); } - logln("Collator.hashCode() testing ..."); + System.out.println("Collator.hashCode() testing ..."); if (col1 != null) { doAssert(col1.hashCode() != col2.hashCode(), "Hash test1 result incorrect"); @@ -169,7 +169,7 @@ public final void TestHashCode( ) } } - logln("hashCode tests end."); + System.out.println("hashCode tests end."); } //---------------------------------------------------------------------------- @@ -177,20 +177,20 @@ public final void TestHashCode( ) // public final void TestCollationKey( ) { - logln("testing CollationKey begins..."); + System.out.println("testing CollationKey begins..."); Collator col = null; try { col = Collator.getInstance(Locale.ROOT); } catch (Exception foo) { - errln("Error : " + foo.getMessage()); - errln("Default collation creation failed."); + fail("Error : " + foo.getMessage() + + "\n Default collation creation failed."); } if (col == null) { return; } String test1 = "Abcda", test2 = "abcda"; - logln("Use tertiary comparison level testing ...."); + System.out.println("Use tertiary comparison level testing ...."); CollationKey sortk1 = col.getCollationKey(test1); CollationKey sortk2 = col.getCollationKey(test2); doAssert(sortk1.compareTo(sortk2) > 0, @@ -209,20 +209,20 @@ public final void TestCollationKey( ) byte byteArray1[] = sortk1.toByteArray(); byte byteArray2[] = sortk2.toByteArray(); doAssert(byteArray1 != null && byteArray2 != null, "CollationKey.toByteArray failed."); - logln("testing sortkey ends..."); + System.out.println("testing sortkey ends..."); } //---------------------------------------------------------------------------- // ctor -- Tests the constructor methods // public final void TestElemIter( ) { - logln("testing sortkey begins..."); + System.out.println("testing sortkey begins..."); Collator col = null; try { col = Collator.getInstance(); } catch (Exception foo) { - errln("Error : " + foo.getMessage()); - errln("Default collation creation failed."); + fail("Error : " + foo.getMessage() + + "\n Default collation creation failed."); } RuleBasedCollator rbCol; if (col instanceof RuleBasedCollator) { @@ -232,7 +232,7 @@ public final void TestElemIter( ) } String testString1 = "XFILE What subset of all possible test cases has the highest probability of detecting the most errors?"; String testString2 = "Xf ile What subset of all possible test cases has the lowest probability of detecting the least errors?"; - logln("Constructors and comparison testing...."); + System.out.println("Constructors and comparison testing...."); CollationElementIterator iterator1 = rbCol.getCollationElementIterator(testString1); CollationElementIterator iterator2 = rbCol.getCollationElementIterator(testString1); CollationElementIterator iterator3 = rbCol.getCollationElementIterator(testString2); @@ -303,17 +303,17 @@ public final void TestElemIter( ) != CollationElementIterator.secondaryOrder(order3), "The secondary orders should be different"); doAssert(order1 != CollationElementIterator.NULLORDER, "Unexpected end of iterator reached"); - logln("testing CollationElementIterator ends..."); + System.out.println("testing CollationElementIterator ends..."); } public final void TestGetAll() { Locale[] list = Collator.getAvailableLocales(); for (int i = 0; i < list.length; ++i) { - log("Locale name: "); - log(list[i].toString()); - log(" , the display name is : "); - logln(list[i].getDisplayName()); + System.out.println("Locale name: "); + System.out.println(list[i].toString()); + System.out.println(" , the display name is : "); + System.out.println(list[i].getDisplayName()); } } } diff --git a/test/jdk/java/text/Collator/Bug6271411.java b/test/jdk/java/text/Collator/Bug6271411.java index 16495d04bea..b78f11583d8 100644 --- a/test/jdk/java/text/Collator/Bug6271411.java +++ b/test/jdk/java/text/Collator/Bug6271411.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,21 +24,20 @@ /* * @test * @bug 6271411 - * @library /java/text/testlib * @summary Confirm that three JCK testcases for CollationElementIterator pass. + * @run junit Bug6271411 */ import java.text.*; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + /* * Based on JCK-runtime-15/tests/api/java_text/CollationElementIterator/ColltnElmtIterTests.java. */ -public class Bug6271411 extends IntlTest { - - public static void main(String argv[]) throws Exception { - Bug6271411 test = new Bug6271411(); - test.run(argv); - } +public class Bug6271411 { /* * Rule for RuleBasedCollator @@ -58,6 +57,7 @@ public static void main(String argv[]) throws Exception { * (not IndexOutOfBoundsException) if the given offset is invalid. * Use CollationElementIterator.setText(String). */ + @Test public void Test_CollationElementIterator0007() throws Exception { int[] offsets = { Integer.MIN_VALUE, Integer.MIN_VALUE + 1, -10000, -2, -1, @@ -90,7 +90,7 @@ public void Test_CollationElementIterator0007() throws Exception { } if (err) { - errln("CollationElementIterator.setOffset() didn't throw an expected IllegalArguemntException."); + fail("CollationElementIterator.setOffset() didn't throw an expected IllegalArguemntException."); } } @@ -99,6 +99,7 @@ public void Test_CollationElementIterator0007() throws Exception { * IllegalArgumentException if the given offset is invalid. * Use CollationElementIterator.setText(CharacterIterator). */ + @Test public void Test_CollationElementIterator0010() throws Exception { String prefix = "xyz abc"; String suffix = "1234567890"; @@ -144,7 +145,7 @@ public void Test_CollationElementIterator0010() throws Exception { } if (err) { - errln("CollationElementIterator.setOffset() didn't throw an expected IllegalArguemntException."); + fail("CollationElementIterator.setOffset() didn't throw an expected IllegalArguemntException."); } } @@ -153,6 +154,7 @@ public void Test_CollationElementIterator0010() throws Exception { * an offset as expected. * Use CollationElementIterator.setText(CharacterIterator). */ + @Test public void Test_CollationElementIterator0011() throws Exception { String prefix = "xyz abc"; String suffix = "1234567890"; diff --git a/test/jdk/java/text/Collator/CollatorTest.java b/test/jdk/java/text/Collator/CollatorTest.java deleted file mode 100644 index bb6785b888f..00000000000 --- a/test/jdk/java/text/Collator/CollatorTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.lang.reflect.*; -import java.util.Hashtable; -import java.util.Enumeration; -import java.util.Vector; -import java.io.*; -import java.text.*; - -/** - * CollatorTest is a base class for tests that can be run conveniently from - * the command line as well as under the Java test harness. - *

- * Sub-classes implement a set of methods named Test. Each - * of these methods performs some test. Test methods should indicate - * errors by calling either err or errln. This will increment the - * errorCount field and may optionally print a message to the log. - * Debugging information may also be added to the log via the log - * and logln methods. These methods will add their arguments to the - * log only if the test is being run in verbose mode. - */ -public abstract class CollatorTest extends IntlTest { - - //------------------------------------------------------------------------ - // These methods are utilities specific to the Collation tests.. - //------------------------------------------------------------------------ - - protected void assertEqual(CollationElementIterator i1, CollationElementIterator i2) { - int c1, c2, count = 0; - do { - c1 = i1.next(); - c2 = i2.next(); - if (c1 != c2) { - errln(" " + count + ": " + c1 + " != " + c2); - break; - } - count++; - } while (c1 != CollationElementIterator.NULLORDER); - } - - // Replace nonprintable characters with unicode escapes - static protected String prettify(String str) { - StringBuffer result = new StringBuffer(); - - String zero = "0000"; - - for (int i = 0; i < str.length(); i++) { - char ch = str.charAt(i); - if (ch < 0x09 || (ch > 0x0A && ch < 0x20)|| (ch > 0x7E && ch < 0xA0) || ch > 0x100) { - String hex = Integer.toString((int)ch,16); - - result.append("\\u" + zero.substring(0, 4 - hex.length()) + hex); - } else { - result.append(ch); - } - } - return result.toString(); - } - - // Produce a printable representation of a CollationKey - static protected String prettify(CollationKey key) { - StringBuffer result = new StringBuffer(); - byte[] bytes = key.toByteArray(); - - for (int i = 0; i < bytes.length; i += 2) { - int val = (bytes[i] << 8) + bytes[i+1]; - result.append(Integer.toString(val, 16) + " "); - } - return result.toString(); - } - - //------------------------------------------------------------------------ - // Everything below here is boilerplate code that makes it possible - // to add a new test by simply adding a function to an existing class - //------------------------------------------------------------------------ - - protected void doTest(Collator col, int strength, - String[] source, String[] target, int[] result) { - if (source.length != target.length) { - errln("Data size mismatch: source = " + - source.length + ", target = " + target.length); - - return; // Return if "-nothrow" is specified. - } - if (source.length != result.length) { - errln("Data size mismatch: source & target = " + - source.length + ", result = " + result.length); - - return; // Return if "-nothrow" is specified. - } - - col.setStrength(strength); - for (int i = 0; i < source.length ; i++) { - doTest(col, source[i], target[i], result[i]); - } - } - - protected void doTest(Collator col, - String source, String target, int result) { - char relation = '='; - if (result <= -1) { - relation = '<'; - } else if (result >= 1) { - relation = '>'; - } - - int compareResult = col.compare(source, target); - CollationKey sortKey1 = col.getCollationKey(source); - CollationKey sortKey2 = col.getCollationKey(target); - int keyResult = sortKey1.compareTo(sortKey2); - if (compareResult != keyResult) { - errln("Compare and Collation Key results are different! Source = " + - source + " Target = " + target); - } - if (keyResult != result) { - errln("Collation Test failed! Source = " + source + " Target = " + - target + " result should be " + relation); - } - } -} diff --git a/test/jdk/java/text/Collator/DanishTest.java b/test/jdk/java/text/Collator/DanishTest.java index 0c35d22e488..f2f5c030b71 100644 --- a/test/jdk/java/text/Collator/DanishTest.java +++ b/test/jdk/java/text/Collator/DanishTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,6 +27,7 @@ * @library /java/text/testlib * @summary test Danish Collation * @modules jdk.localedata + * @run junit DanishTest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -43,12 +44,12 @@ import java.util.Locale; import java.text.Collator; -// Quick dummy program for printing out test results -public class DanishTest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new DanishTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +// Quick dummy program for printing out test results +public class DanishTest { /* * Data for TestPrimary() @@ -196,18 +197,20 @@ public static void main(String[] args) throws Exception { "\u00F6BERG" // o-diaeresis }; + @Test public void TestPrimary() { - doTest(myCollation, Collator.PRIMARY, + TestUtils.doCollatorTest(myCollation, Collator.PRIMARY, primarySourceData, primaryTargetData, primaryResults); } + @Test public void TestTertiary() { - doTest(myCollation, Collator.TERTIARY, + TestUtils.doCollatorTest(myCollation, Collator.TERTIARY, tertiarySourceData, tertiaryTargetData, tertiaryResults); for (int i = 0; i < testData.length-1; i++) { for (int j = i+1; j < testData.length; j++) { - doTest(myCollation, testData[i], testData[j], -1); + TestUtils.doCollatorTest(myCollation, testData[i], testData[j], -1); } } } diff --git a/test/jdk/java/text/Collator/DummyTest.java b/test/jdk/java/text/Collator/DummyTest.java index 3e3124edb07..814b5544ea8 100644 --- a/test/jdk/java/text/Collator/DummyTest.java +++ b/test/jdk/java/text/Collator/DummyTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,11 +25,16 @@ * @test * @library /java/text/testlib * @summary test Dummy Collation + * @run junit DummyTest */ import java.text.Collator; import java.text.RuleBasedCollator; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved (C) Copyright IBM Corp. 1996 - All Rights Reserved @@ -42,11 +47,7 @@ Taligent is a registered trademark of Taligent, Inc. */ -public class DummyTest extends CollatorTest { - - public static void main(String[] args) throws Exception { - new DummyTest().run(args); - } +public class DummyTest { private static final String DEFAULTRULES = "='\u200B'=\u200C=\u200D=\u200E=\u200F" @@ -382,25 +383,28 @@ public static void main(String[] args) throws Exception { "z" }; + @Test public void TestPrimary() { - doTest(getCollator(), Collator.PRIMARY, + TestUtils.doCollatorTest(getCollator(), Collator.PRIMARY, primarySourceData, primaryTargetData, primaryResults); } + @Test public void TestSecondary() { - doTest(getCollator(), Collator.SECONDARY, + TestUtils.doCollatorTest(getCollator(), Collator.SECONDARY, secondarySourceData, secondaryTargetData, secondaryResults); } + @Test public void TestTertiary() { Collator col = getCollator(); - doTest(col, Collator.TERTIARY, + TestUtils.doCollatorTest(col, Collator.TERTIARY, tertiarySourceData, tertiaryTargetData, tertiaryResults); for (int i = 0; i < testData.length-1; i++) { for (int j = i+1; j < testData.length; j++) { - doTest(col, testData[i], testData[j], -1); + TestUtils.doCollatorTest(col, testData[i], testData[j], -1); } } } @@ -412,7 +416,7 @@ private Collator getCollator() { myCollation = new RuleBasedCollator (DEFAULTRULES + "& C < ch, cH, Ch, CH & Five, 5 & Four, 4 & one, 1 & Ampersand; '&' & Two, 2 "); } catch (Exception foo) { - errln("Collator creation failed."); + fail("Collator creation failed."); myCollation = (RuleBasedCollator)Collator.getInstance(); } } diff --git a/test/jdk/java/text/Collator/EnglishTest.java b/test/jdk/java/text/Collator/EnglishTest.java index 3c4da57b75c..ee948de21b6 100644 --- a/test/jdk/java/text/Collator/EnglishTest.java +++ b/test/jdk/java/text/Collator/EnglishTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,11 +25,16 @@ * @test * @library /java/text/testlib * @summary test English Collation + * @run junit EnglishTest */ import java.util.Locale; import java.text.Collator; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved (C) Copyright IBM Corp. 1996 - All Rights Reserved @@ -42,11 +47,7 @@ Taligent is a registered trademark of Taligent, Inc. */ -public class EnglishTest extends CollatorTest { - - public static void main(String[] args) throws Exception { - new EnglishTest().run(args); - } +public class EnglishTest { /* * Data for TestPrimary() @@ -201,23 +202,26 @@ public static void main(String[] args) throws Exception { "x" }; + @Test public void TestPrimary() { - doTest(myCollation, Collator.PRIMARY, + TestUtils.doCollatorTest(myCollation, Collator.PRIMARY, primarySourceData, primaryTargetData, primaryResults); } + @Test public void TestSecondary() { - doTest(myCollation, Collator.SECONDARY, + TestUtils.doCollatorTest(myCollation, Collator.SECONDARY, secondarySourceData, secondaryTargetData, secondaryResults); } + @Test public void TestTertiary() { - doTest(myCollation, Collator.TERTIARY, + TestUtils.doCollatorTest(myCollation, Collator.TERTIARY, tertiarySourceData, tertiaryTargetData, tertiaryResults); for (int i = 0; i < testData.length-1; i++) { for (int j = i+1; j < testData.length; j++) { - doTest(myCollation, testData[i], testData[j], -1); + TestUtils.doCollatorTest(myCollation, testData[i], testData[j], -1); } } } diff --git a/test/jdk/java/text/Collator/FinnishTest.java b/test/jdk/java/text/Collator/FinnishTest.java index 9efc3cd861d..3e66f91f2a6 100644 --- a/test/jdk/java/text/Collator/FinnishTest.java +++ b/test/jdk/java/text/Collator/FinnishTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @library /java/text/testlib * @summary test Finnish Collation * @modules jdk.localedata + * @run junit FinnishTest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -42,12 +43,12 @@ import java.util.Locale; import java.text.Collator; -// Quick dummy program for printing out test results -public class FinnishTest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new FinnishTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +// Quick dummy program for printing out test results +public class FinnishTest { /* * Data for TestPrimary() @@ -85,13 +86,15 @@ public static void main(String[] args) throws Exception { 1, -1, 1 }; + @Test public void TestPrimary() { - doTest(myCollation, Collator.PRIMARY, + TestUtils.doCollatorTest(myCollation, Collator.PRIMARY, primarySourceData, primaryTargetData, primaryResults); } + @Test public void TestTertiary() { - doTest(myCollation, Collator.TERTIARY, + TestUtils.doCollatorTest(myCollation, Collator.TERTIARY, tertiarySourceData, tertiaryTargetData, tertiaryResults); } diff --git a/test/jdk/java/text/Collator/FrenchTest.java b/test/jdk/java/text/Collator/FrenchTest.java index 38492db023c..fa6ca031859 100644 --- a/test/jdk/java/text/Collator/FrenchTest.java +++ b/test/jdk/java/text/Collator/FrenchTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @library /java/text/testlib * @summary test French Collation * @modules jdk.localedata + * @run junit FrenchTest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -42,12 +43,12 @@ import java.util.Locale; import java.text.Collator; -// Quick dummy program for printing out test results -public class FrenchTest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new FrenchTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +// Quick dummy program for printing out test results +public class FrenchTest { private static final String[] tertiarySourceData = { "abc", @@ -86,13 +87,14 @@ public static void main(String[] args) throws Exception { "x" }; + @Test public void TestTertiary() { - doTest(myCollation, Collator.TERTIARY, + TestUtils.doCollatorTest(myCollation, Collator.TERTIARY, tertiarySourceData, tertiaryTargetData, tertiaryResults); for (int i = 0; i < testData.length-1; i++) { for (int j = i+1; j < testData.length; j++) { - doTest(myCollation, testData[i], testData[j], -1); + TestUtils.doCollatorTest(myCollation, testData[i], testData[j], -1); } } } diff --git a/test/jdk/java/text/Collator/G7Test.java b/test/jdk/java/text/Collator/G7Test.java index f7bdfa4f868..fcb201b0719 100644 --- a/test/jdk/java/text/Collator/G7Test.java +++ b/test/jdk/java/text/Collator/G7Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @library /java/text/testlib * @summary test G7 Collation * @modules jdk.localedata + * @run junit G7Test */ /* * @@ -54,13 +55,13 @@ import java.text.RuleBasedCollator; import java.util.Locale; -// G7 test program for printing out test results +import org.junit.jupiter.api.Test; -public class G7Test extends CollatorTest { +import static org.junit.jupiter.api.Assertions.fail; - public static void main(String[] args) throws Exception { - new G7Test().run(args); - } +// G7 test program for printing out test results + +public class G7Test { private static final String testCases[] = { "black-birds", // 0 @@ -158,6 +159,7 @@ public static void main(String[] args) throws Exception { 2, 3, 4, 5, 20, 6, 8, 10, 7, 29 }; + @Test public void TestG7Data() { for (int i = 0; i < locales.length; i++) { Collator myCollation= null; @@ -167,14 +169,14 @@ public void TestG7Data() { myCollation = Collator.getInstance(locales[i]); tblColl1 = new RuleBasedCollator(((RuleBasedCollator)myCollation).getRules()); } catch (Exception foo) { - errln("Exception: " + foo.getMessage() + + fail("Exception: " + foo.getMessage() + " Locale : " + locales[i].getDisplayName() + " getRules failed\n"); continue; } for (int j = 0; j < FIXEDTESTSET; j++) { for (int n = j+1; n < FIXEDTESTSET; n++) { - doTest(tblColl1, testCases[G7Results[i][j]], + TestUtils.doCollatorTest(tblColl1, testCases[G7Results[i][j]], testCases[G7Results[i][n]], -1); } } @@ -185,6 +187,7 @@ public void TestG7Data() { /* * Demo Test 1 : Create a new table collation with rules "& Z < p, P" */ + @Test public void TestDemoTest1() { int j = 0; final Collator myCollation = Collator.getInstance(Locale.US); @@ -196,13 +199,13 @@ public void TestDemoTest1() { tblColl = new RuleBasedCollator(newRules); for (j = 0; j < FIXEDTESTSET; j++) { for (int n = j+1; n < FIXEDTESTSET; n++) { - doTest(tblColl, testCases[Test1Results[j]], + TestUtils.doCollatorTest(tblColl, testCases[Test1Results[j]], testCases[Test1Results[n]], -1); } } tblColl = null; } catch (Exception foo) { - errln("Exception: " + foo.getMessage() + + fail("Exception: " + foo.getMessage() + "\nDemo Test 1 Table Collation object creation failed."); } } @@ -211,6 +214,7 @@ public void TestDemoTest1() { * Demo Test 2 : Create a new table collation with rules * "& C < ch , cH, Ch, CH" */ + @Test public void TestDemoTest2() { final Collator myCollation = Collator.getInstance(Locale.US); final String defRules = ((RuleBasedCollator)myCollation).getRules(); @@ -220,12 +224,12 @@ public void TestDemoTest2() { RuleBasedCollator tblColl = new RuleBasedCollator(newRules); for (int j = 0; j < TOTALTESTSET; j++) { for (int n = j+1; n < TOTALTESTSET; n++) { - doTest(tblColl, testCases[Test2Results[j]], + TestUtils.doCollatorTest(tblColl, testCases[Test2Results[j]], testCases[Test2Results[n]], -1); } } } catch (Exception foo) { - errln("Exception: " + foo.getMessage() + + fail("Exception: " + foo.getMessage() + "\nDemo Test 2 Table Collation object creation failed.\n"); } } @@ -234,6 +238,7 @@ public void TestDemoTest2() { * Demo Test 3 : Create a new table collation with rules * "& Question'-'mark ; '?' & Hash'-'mark ; '#' & Ampersand ; '&'" */ + @Test public void TestDemoTest3() { final Collator myCollation = Collator.getInstance(Locale.US); final String defRules = ((RuleBasedCollator)myCollation).getRules(); @@ -244,12 +249,12 @@ public void TestDemoTest3() { tblColl = new RuleBasedCollator(newRules); for (int j = 0; j < TOTALTESTSET; j++) { for (int n = j+1; n < TOTALTESTSET; n++) { - doTest(tblColl, testCases[Test3Results[j]], + TestUtils.doCollatorTest(tblColl, testCases[Test3Results[j]], testCases[Test3Results[n]], -1); } } } catch (Exception foo) { - errln("Exception: " + foo.getMessage() + + fail("Exception: " + foo.getMessage() + "\nDemo Test 3 Table Collation object creation failed."); } } @@ -258,6 +263,7 @@ public void TestDemoTest3() { * Demo Test 4 : Create a new table collation with rules * " & aa ; a'-' & ee ; e'-' & ii ; i'-' & oo ; o'-' & uu ; u'-' " */ + @Test public void TestDemoTest4() { final Collator myCollation = Collator.getInstance(Locale.US); final String defRules = ((RuleBasedCollator)myCollation).getRules(); @@ -268,12 +274,12 @@ public void TestDemoTest4() { tblColl = new RuleBasedCollator(newRules); for (int j = 0; j < TOTALTESTSET; j++) { for (int n = j+1; n < TOTALTESTSET; n++) { - doTest(tblColl, testCases[Test4Results[j]], + TestUtils.doCollatorTest(tblColl, testCases[Test4Results[j]], testCases[Test4Results[n]], -1); } } } catch (Exception foo) { - errln("Exception: " + foo.getMessage() + + fail("Exception: " + foo.getMessage() + "\nDemo Test 4 Table Collation object creation failed."); } tblColl = null; diff --git a/test/jdk/java/text/Collator/GermanTest.java b/test/jdk/java/text/Collator/GermanTest.java index 74129e96f93..92c6466e8c1 100644 --- a/test/jdk/java/text/Collator/GermanTest.java +++ b/test/jdk/java/text/Collator/GermanTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,6 +25,7 @@ * @test * @library /java/text/testlib * @summary test German Collation + * @run junit GermanTest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -41,12 +42,12 @@ import java.util.Locale; import java.text.Collator; -// Quick dummy program for printing out test results -public class GermanTest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new GermanTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +// Quick dummy program for printing out test results +public class GermanTest { /* * Shared data for TestPrimary() and TestTertiary() @@ -97,13 +98,15 @@ public static void main(String[] args) throws Exception { -1, 1 }; + @Test public void TestPrimary() { - doTest(myCollation, Collator.PRIMARY, + TestUtils.doCollatorTest(myCollation, Collator.PRIMARY, testSourceData, testTargetData, primaryResults); } + @Test public void TestTertiary() { - doTest(myCollation, Collator.TERTIARY, + TestUtils.doCollatorTest(myCollation, Collator.TERTIARY, testSourceData, testTargetData, tertiaryResults); } diff --git a/test/jdk/java/text/Collator/IteratorTest.java b/test/jdk/java/text/Collator/IteratorTest.java index a5c7f9bedfa..38b6bb41565 100644 --- a/test/jdk/java/text/Collator/IteratorTest.java +++ b/test/jdk/java/text/Collator/IteratorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @bug 4062985 4108758 4108762 4157299 * @library /java/text/testlib * @summary Test CollationElementIterator, particularly the new methods in 1.2 + * @run junit IteratorTest */ /* * (C) Copyright IBM Corp. 1998 - All Rights Reserved @@ -40,22 +41,23 @@ import java.util.Locale; import java.text.*; -public class IteratorTest extends CollatorTest { +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class IteratorTest { // TODO: // - Test previous() with contracting character sequences, which don't work // at the moment. // - Test edge cases on setOffset(), e.g. offset > length, etc. // - public static void main(String[] args) throws Exception { - new IteratorTest().run(args); - } - /** * Test for CollationElementIterator.previous() * * @bug 4108758 - Make sure it works with contracting characters * */ + @Test public void TestPrevious() throws ParseException { // A basic test to see if it's working at all backAndForth(en_us.getCollationElementIterator(test1)); @@ -82,6 +84,7 @@ public void TestPrevious() throws ParseException { /** * Test for getOffset() and setOffset() */ + @Test public void TestOffset() { CollationElementIterator iter = en_us.getCollationElementIterator(test1); @@ -96,7 +99,7 @@ public void TestOffset() { // Now set the offset back to the beginning and see if it works iter.setOffset(0); - assertEqual(iter, en_us.getCollationElementIterator(test1)); + TestUtils.compareCollationElementIters(iter, en_us.getCollationElementIterator(test1)); // TODO: try iterating halfway through a messy string. } @@ -104,6 +107,7 @@ public void TestOffset() { /** * Test for setText() */ + @Test public void TestSetText() { CollationElementIterator iter1 = en_us.getCollationElementIterator(test1); CollationElementIterator iter2 = en_us.getCollationElementIterator(test2); @@ -117,12 +121,13 @@ public void TestSetText() { // Now set it to point to the same string as the first iterator iter2.setText(test1); - assertEqual(iter1, iter2); + TestUtils.compareCollationElementIters(iter1, iter2); } /** @bug 4108762 * Test for getMaxExpansion() */ + @Test public void TestMaxExpansion() throws ParseException { // Try a simple one first: // The only expansion ends with 'e' and has length 2 @@ -151,6 +156,7 @@ public void TestMaxExpansion() throws ParseException { /* * @bug 4157299 */ + @Test public void TestClearBuffers() throws ParseException { RuleBasedCollator c = new RuleBasedCollator("< a < b < c & ab = d"); CollationElementIterator i = c.getCollationElementIterator("abcd"); @@ -160,7 +166,7 @@ public void TestClearBuffers() throws ParseException { i.setOffset(0); // go back to the beginning int e = i.next(); // and get this one again if (e != e0) { - errln("got " + Integer.toString(e, 16) + ", expected " + + fail("got " + Integer.toString(e, 16) + ", expected " + Integer.toString(e0, 16)); } } @@ -179,26 +185,26 @@ private void backAndForth(CollationElementIterator iter) { while ((o = iter.previous()) != CollationElementIterator.NULLORDER) { if (o != orders[--index]) { - errln("Mismatch at index " + index + ": " + fail("Mismatch at index " + index + ": " + orders[index] + " vs " + o); break; } } if (index != 0) { - errln("Didn't get back to beginning - index is " + index); + fail("Didn't get back to beginning - index is " + index); iter.reset(); - err("next: "); + fail("next: "); while ((o = iter.next()) != NULLORDER) { - err( Integer.toHexString(o) + " "); + fail( Integer.toHexString(o) + " "); } - errln(""); + fail(""); - err("prev: "); + fail("prev: "); while ((o = iter.previous()) != NULLORDER) { - err( Integer.toHexString(o) + " "); + fail( Integer.toHexString(o) + " "); } - errln(""); + fail(""); } } @@ -226,7 +232,7 @@ private void verifyExpansion(String[][] tests) throws ParseException if (order == NULLORDER || iter.next() != NULLORDER) { iter.reset(); - errln("verifyExpansion: '" + tests[i][0] + + fail("verifyExpansion: '" + tests[i][0] + "' has multiple orders:" + orderString(iter)); } @@ -234,7 +240,7 @@ private void verifyExpansion(String[][] tests) throws ParseException int expect = new Integer(tests[i][1]).intValue(); if (expansion != expect) { - errln("expansion for '" + tests[i][0] + "' is wrong: " + + fail("expansion for '" + tests[i][0] + "' is wrong: " + "expected " + expect + ", got " + expansion); } } diff --git a/test/jdk/java/text/Collator/MonkeyTest.java b/test/jdk/java/text/Collator/MonkeyTest.java index 9539bf5f5ae..5ae343ce150 100644 --- a/test/jdk/java/text/Collator/MonkeyTest.java +++ b/test/jdk/java/text/Collator/MonkeyTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,6 +25,7 @@ * @test * @library /java/text/testlib * @summary test Collation, Monkey style + * @run junit MonkeyTest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -47,31 +48,32 @@ import java.text.RuleBasedCollator; import java.text.CollationKey; -public class MonkeyTest extends CollatorTest -{ - public static void main(String[] args) throws Exception { - new MonkeyTest().run(args); - } +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.fail; + +public class MonkeyTest +{ public void report(String s, String t, int result, int revResult) { if (result == -1) { if (revResult != 1) - errln(" --> Test Failed"); + fail(" --> Test Failed"); } else if (result == 1) { if (revResult != -1) - errln(" --> Test Failed"); + fail(" --> Test Failed"); } else if (result == 0) { if (revResult != 0) - errln(" --> Test Failed"); + fail(" --> Test Failed"); } } + @Test public void TestCollationKey() { String source = "-abcdefghijklmnopqrstuvwxyz#&^$@"; @@ -105,16 +107,17 @@ public void TestCollationKey() CollationKey2 = myCollator.getCollationKey(addOne); result = CollationKey1.compareTo(CollationKey2); if (result != -1) - errln("CollationKey(" + subs + ")" + ".LT." + "CollationKey(" + addOne + ") Failed."); + fail("CollationKey(" + subs + ")" + ".LT." + "CollationKey(" + addOne + ") Failed."); result = CollationKey2.compareTo(CollationKey1); if (result != 1) - errln("CollationKey(" + addOne + ")" + ".GT." + "CollationKey(" + subs + ") Failed."); + fail("CollationKey(" + addOne + ")" + ".GT." + "CollationKey(" + subs + ") Failed."); } private static int checkValue(int value) { value *= (value > 0) ? 1 : -1; return value; } + @Test public void TestCompare() { String source = "-abcdefghijklmnopqrstuvwxyz#&^$@"; @@ -140,10 +143,10 @@ public void TestCompare() String addOne = subs + "\uE000"; result = myCollator.compare(subs, addOne); if (result != -1) - errln("Test : " + subs + " .LT. " + addOne + " Failed."); + fail("Test : " + subs + " .LT. " + addOne + " Failed."); result = myCollator.compare(addOne, subs); if (result != 1) - errln("Test : " + addOne + " .GE. " + subs + " Failed."); + fail("Test : " + addOne + " .GE. " + subs + " Failed."); } private static Collator myCollator = Collator.getInstance(); } diff --git a/test/jdk/java/text/Collator/Regression.java b/test/jdk/java/text/Collator/Regression.java index 212ab39d557..daef87e6fe5 100644 --- a/test/jdk/java/text/Collator/Regression.java +++ b/test/jdk/java/text/Collator/Regression.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,7 @@ * @library /java/text/testlib * @summary Regression tests for Collation and associated classes * @modules jdk.localedata + * @run junit Regression */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -47,15 +48,16 @@ import java.util.Locale; import java.util.Vector; +import org.junit.jupiter.api.Test; -public class Regression extends CollatorTest { +import static org.junit.jupiter.api.Assertions.fail; - public static void main(String[] args) throws Exception { - new Regression().run(args); - } + +public class Regression { // CollationElementIterator.reset() doesn't work // + @Test public void Test4048446() { CollationElementIterator i1 = en_us.getCollationElementIterator(test1); CollationElementIterator i2 = en_us.getCollationElementIterator(test1); @@ -64,12 +66,13 @@ public void Test4048446() { } i1.reset(); - assertEqual(i1, i2); + TestUtils.compareCollationElementIters(i1, i2); } // Collator -> rules -> Collator round-trip broken for expanding characters // + @Test public void Test4051866() throws ParseException { // Build a collator containing expanding characters RuleBasedCollator c1 = new RuleBasedCollator("< o " @@ -84,15 +87,16 @@ public void Test4051866() throws ParseException { // Make sure they're the same if (!c1.getRules().equals(c2.getRules())) { - errln("Rules are not equal"); + fail("Rules are not equal"); } } // Collator thinks "black-bird" == "black" // + @Test public void Test4053636() { if (en_us.equals("black-bird","black")) { - errln("black-bird == black"); + fail("black-bird == black"); } } @@ -100,6 +104,7 @@ public void Test4053636() { // CollationElementIterator will not work correctly if the associated // Collator object's mode is changed // + @Test public void Test4054238() { RuleBasedCollator c = (RuleBasedCollator) en_us.clone(); @@ -111,18 +116,19 @@ public void Test4054238() { // At this point, BOTH iterators should use NO_DECOMPOSITION, since the // collator itself is in that mode - assertEqual(i1, i2); + TestUtils.compareCollationElementIters(i1, i2); } // Collator.IDENTICAL documented but not implemented // + @Test public void Test4054734() { RuleBasedCollator c = (RuleBasedCollator) en_us.clone(); try { c.setStrength(Collator.IDENTICAL); } catch (Exception e) { - errln("Caught " + e.toString() + " setting Collator.IDENTICAL"); + fail("Caught " + e.toString() + " setting Collator.IDENTICAL"); } String[] decomp = { @@ -143,6 +149,7 @@ public void Test4054734() { // Full Decomposition mode not implemented // + @Test public void Test4054736() { RuleBasedCollator c = (RuleBasedCollator) en_us.clone(); c.setDecomposition(Collator.FULL_DECOMPOSITION); @@ -156,6 +163,7 @@ public void Test4054736() { // Collator.getInstance() causes an ArrayIndexOutofBoundsException for Korean // + @Test public void Test4058613() { // Creating a default collator doesn't work when Korean is the default // locale @@ -169,7 +177,7 @@ public void Test4058613() { // Since the fix to this bug was to turn of decomposition for Korean collators, // ensure that's what we got if (c.getDecomposition() != Collator.NO_DECOMPOSITION) { - errln("Decomposition is not set to NO_DECOMPOSITION"); + fail("Decomposition is not set to NO_DECOMPOSITION"); } } finally { @@ -180,28 +188,30 @@ public void Test4058613() { // RuleBasedCollator.getRules does not return the exact pattern as input // for expanding character sequences // + @Test public void Test4059820() { RuleBasedCollator c = null; try { c = new RuleBasedCollator("< a < b , c/a < d < z"); } catch (ParseException e) { - errln("Exception building collator: " + e.toString()); + fail("Exception building collator: " + e.toString()); return; } if ( c.getRules().indexOf("c/a") == -1) { - errln("returned rules do not contain 'c/a'"); + fail("returned rules do not contain 'c/a'"); } } // MergeCollation::fixEntry broken for "& H < \u0131, \u0130, i, I" // + @Test public void Test4060154() { RuleBasedCollator c = null; try { c = new RuleBasedCollator("< g, G < h, H < i, I < j, J" + " & H < \u0131, \u0130, i, I" ); } catch (ParseException e) { - errln("Exception building collator: " + e.toString()); + fail("Exception building collator: " + e.toString()); return; } c.setDecomposition(Collator.CANONICAL_DECOMPOSITION); @@ -227,6 +237,7 @@ public void Test4060154() { // Secondary/Tertiary comparison incorrect in French Secondary // + @Test public void Test4062418() throws ParseException { RuleBasedCollator c = (RuleBasedCollator) Collator.getInstance(Locale.FRANCE); c.setStrength(Collator.SECONDARY); @@ -240,9 +251,10 @@ public void Test4062418() throws ParseException { // Collator.compare() method broken if either string contains spaces // + @Test public void Test4065540() { if (en_us.compare("abcd e", "abcd f") == 0) { - errln("'abcd e' == 'abcd f'"); + fail("'abcd e' == 'abcd f'"); } } @@ -250,6 +262,7 @@ public void Test4065540() { // correct result. For example, // u1EB1 -> \u0103 + \u0300 -> a + \u0306 + \u0300. // + @Test public void Test4066189() { String test1 = "\u1EB1"; String test2 = "a\u0306\u0300"; @@ -262,11 +275,12 @@ public void Test4066189() { c2.setDecomposition(Collator.NO_DECOMPOSITION); CollationElementIterator i2 = en_us.getCollationElementIterator(test2); - assertEqual(i1, i2); + TestUtils.compareCollationElementIters(i1, i2); } // French secondary collation checking at the end of compare iteration fails // + @Test public void Test4066696() { RuleBasedCollator c = (RuleBasedCollator) Collator.getInstance(Locale.FRANCE); c.setStrength(Collator.SECONDARY); @@ -281,6 +295,7 @@ public void Test4066696() { // Bad canonicalization of same-class combining characters // + @Test public void Test4076676() { // These combining characters are all in the same class, so they should not // be reordered, and they should compare as unequal. @@ -291,38 +306,41 @@ public void Test4076676() { c.setStrength(Collator.TERTIARY); if (c.compare(s1,s2) == 0) { - errln("Same-class combining chars were reordered"); + fail("Same-class combining chars were reordered"); } } // RuleBasedCollator.equals(null) throws NullPointerException // + @Test public void Test4079231() { try { if (en_us.equals(null)) { - errln("en_us.equals(null) returned true"); + fail("en_us.equals(null) returned true"); } } catch (Exception e) { - errln("en_us.equals(null) threw " + e.toString()); + fail("en_us.equals(null) threw " + e.toString()); } } // RuleBasedCollator breaks on "< a < bb" rule // + @Test public void Test4078588() throws ParseException { RuleBasedCollator rbc=new RuleBasedCollator("< a < bb"); int result = rbc.compare("a","bb"); if (result != -1) { - errln("Compare(a,bb) returned " + result + "; expected -1"); + fail("Compare(a,bb) returned " + result + "; expected -1"); } } // Combining characters in different classes not reordered properly. // + @Test public void Test4081866() throws ParseException { // These combining characters are all in different classes, // so they should be reordered and the strings should compare as equal. @@ -338,12 +356,13 @@ public void Test4081866() throws ParseException { c.setDecomposition(Collator.CANONICAL_DECOMPOSITION); if (c.compare(s1,s2) != 0) { - errln("Combining chars were not reordered"); + fail("Combining chars were not reordered"); } } // string comparison errors in Scandinavian collators // + @Test public void Test4087241() { RuleBasedCollator c = (RuleBasedCollator) Collator.getInstance( new Locale("da", "DK")); @@ -360,6 +379,7 @@ public void Test4087241() { // CollationKey takes ignorable strings into account when it shouldn't // + @Test public void Test4087243() { RuleBasedCollator c = (RuleBasedCollator) en_us.clone(); c.setStrength(Collator.TERTIARY); @@ -374,6 +394,7 @@ public void Test4087243() { // Mu/micro conflict // Micro symbol and greek lowercase letter Mu should sort identically // + @Test public void Test4092260() { Collator c = Collator.getInstance(new Locale("el", "")); @@ -401,6 +422,7 @@ void Test4095316() { compareArray(c, tests); } + @Test public void Test4101940() { try { RuleBasedCollator c = new RuleBasedCollator("< a < b"); @@ -408,16 +430,17 @@ public void Test4101940() { i.reset(); if (i.next() != i.NULLORDER) { - errln("next did not return NULLORDER"); + fail("next did not return NULLORDER"); } } catch (Exception e) { - errln("Caught " + e ); + fail("Caught " + e ); } } // Collator.compare not handling spaces properly // + @Test public void Test4103436() { RuleBasedCollator c = (RuleBasedCollator) en_us.clone(); c.setStrength(Collator.TERTIARY); @@ -432,6 +455,7 @@ public void Test4103436() { // Collation not Unicode conformant with Hangul syllables // + @Test public void Test4114076() { RuleBasedCollator c = (RuleBasedCollator) en_us.clone(); c.setStrength(Collator.TERTIARY); @@ -457,18 +481,20 @@ public void Test4114076() { // Collator.getCollationKey was hanging on certain character sequences // + @Test public void Test4124632() throws Exception { Collator coll = Collator.getInstance(Locale.JAPAN); try { coll.getCollationKey("A\u0308bc"); } catch (OutOfMemoryError e) { - errln("Ran out of memory -- probably an infinite loop"); + fail("Ran out of memory -- probably an infinite loop"); } } // sort order of french words with multiple accents has errors // + @Test public void Test4132736() { Collator c = Collator.getInstance(Locale.FRANCE); @@ -481,6 +507,7 @@ public void Test4132736() { // The sorting using java.text.CollationKey is not in the exact order // + @Test public void Test4133509() { String[] test1 = { "Exception", "<", "ExceptionInInitializerError", @@ -492,6 +519,7 @@ public void Test4133509() { // Collation with decomposition off doesn't work for Europe // + @Test public void Test4114077() { // Ensure that we get the same results with decomposition off // as we do with it on.... @@ -519,6 +547,7 @@ public void Test4114077() { // Support for Swedish gone in 1.1.6 (Can't create Swedish collator) // + @Test public void Test4141640() { // // Rather than just creating a Swedish collator, we might as well @@ -531,7 +560,7 @@ public void Test4141640() { try { Collator c = Collator.getInstance(locales[i]); } catch (Exception e) { - errln("Caught " + e + " creating collator for " + locales[i]); + fail("Caught " + e + " creating collator for " + locales[i]); } } } @@ -539,6 +568,7 @@ public void Test4141640() { // getCollationKey throws exception for spanish text // Cannot reproduce this bug on 1.2, however it DOES fail on 1.1.6 // + @Test public void Test4139572() { // // Code pasted straight from the bug report @@ -553,6 +583,7 @@ public void Test4139572() { // RuleBasedCollator doesn't use getCollationElementIterator internally // + @Test public void Test4146160() throws ParseException { // // Use a custom collator class whose getCollationElementIterator @@ -561,13 +592,13 @@ public void Test4146160() throws ParseException { My4146160Collator.count = 0; new My4146160Collator().getCollationKey("1"); if (My4146160Collator.count < 1) { - errln("getCollationElementIterator not called"); + fail("getCollationElementIterator not called"); } My4146160Collator.count = 0; new My4146160Collator().compare("1", "2"); if (My4146160Collator.count < 1) { - errln("getCollationElementIterator not called"); + fail("getCollationElementIterator not called"); } } @@ -592,6 +623,7 @@ public CollationElementIterator getCollationElementIterator( // CollationElementIterator.previous broken for expanding char sequences // + @Test public void Test4179686() throws ParseException { // Create a collator with a few expanding character sequences in it.... @@ -617,7 +649,7 @@ public void Test4179686() throws ParseException { int expect = ((Integer)elements.elementAt(index)).intValue(); if (elem != expect) { - errln("Mismatch at index " + index + fail("Mismatch at index " + index + ": got " + Integer.toString(elem,16) + ", expected " + Integer.toString(expect,16)); } @@ -625,6 +657,7 @@ public void Test4179686() throws ParseException { } } + @Test public void Test4244884() throws ParseException { RuleBasedCollator coll = (RuleBasedCollator)Collator.getInstance(Locale.US); coll = new RuleBasedCollator(coll.getRules() @@ -644,13 +677,14 @@ public void Test4244884() throws ParseException { for (int i = 1; i < testStrings.length; i++) { if (coll.compare(testStrings[i - 1], testStrings[i]) >= 0) { - errln("error: \"" + testStrings[i - 1] + fail("error: \"" + testStrings[i - 1] + "\" is greater than or equal to \"" + testStrings[i] + "\"."); } } } + @Test public void Test4179216() throws ParseException { // you can position a CollationElementIterator in the middle of // a contracting character sequence, yielding a bogus collation @@ -673,7 +707,7 @@ public void Test4179216() throws ParseException { int elt5 = CollationElementIterator.primaryOrder(iter.next()); if (elt4 != elt0 || elt5 != elt0) - errln("The collation elements at positions 0 (" + elt0 + "), 4 (" + fail("The collation elements at positions 0 (" + elt0 + "), 4 (" + elt4 + "), and 5 (" + elt5 + ") don't match."); // test that the "cat" combination works properly @@ -697,7 +731,7 @@ public void Test4179216() throws ParseException { if (elt14 != elt15 || elt14 != elt16 || elt14 != elt17 || elt14 != elt18 || elt14 != elt19) - errln("\"cat\" elements don't match: elt14 = " + elt14 + ", elt15 = " + fail("\"cat\" elements don't match: elt14 = " + elt14 + ", elt15 = " + elt15 + ", elt16 = " + elt16 + ", elt17 = " + elt17 + ", elt18 = " + elt18 + ", elt19 = " + elt19); @@ -735,14 +769,15 @@ public void Test4179216() throws ParseException { } for (int i = 0; i < nextElements.length; i++) { if (nextElements[i].equals(setOffsetElements[i])) { - logln(nextElements[i]); + System.out.println(nextElements[i]); } else { - errln("Error: next() yielded " + nextElements[i] + ", but setOffset() yielded " + fail("Error: next() yielded " + nextElements[i] + ", but setOffset() yielded " + setOffsetElements[i]); } } } + @Test public void Test4216006() throws Exception { // rule parser barfs on "<\u00e0=a\u0300", and on other cases // where the same token (after normalization) appears twice in a row @@ -769,6 +804,7 @@ public void Test4216006() throws Exception { compareArray(collator, tests); } + @Test public void Test4171974() { // test French accent ordering more thoroughly String[] frenchList = { @@ -800,10 +836,10 @@ public void Test4171974() { }; Collator french = Collator.getInstance(Locale.FRENCH); - logln("Testing French order..."); + System.out.println("Testing French order..."); checkListOrder(frenchList, french); - logln("Testing French order without decomposition..."); + System.out.println("Testing French order without decomposition..."); french.setDecomposition(Collator.NO_DECOMPOSITION); checkListOrder(frenchList, french); @@ -836,10 +872,10 @@ public void Test4171974() { }; Collator english = Collator.getInstance(Locale.ENGLISH); - logln("Testing English order..."); + System.out.println("Testing English order..."); checkListOrder(englishList, english); - logln("Testing English order without decomposition..."); + System.out.println("Testing English order without decomposition..."); english.setDecomposition(Collator.NO_DECOMPOSITION); checkListOrder(englishList, english); } @@ -849,35 +885,36 @@ private void checkListOrder(String[] sortedList, Collator c) { // passed-in list is already sorted into ascending order for (int i = 0; i < sortedList.length - 1; i++) { if (c.compare(sortedList[i], sortedList[i + 1]) >= 0) { - errln("List out of order at element #" + i + ": " - + prettify(sortedList[i]) + " >= " - + prettify(sortedList[i + 1])); + fail("List out of order at element #" + i + ": " + + TestUtils.prettify(sortedList[i]) + " >= " + + TestUtils.prettify(sortedList[i + 1])); } } } // CollationElementIterator set doesn't work propertly with next/prev + @Test public void Test4663220() { RuleBasedCollator collator = (RuleBasedCollator)Collator.getInstance(Locale.US); CharacterIterator stringIter = new StringCharacterIterator("fox"); CollationElementIterator iter = collator.getCollationElementIterator(stringIter); int[] elements_next = new int[3]; - logln("calling next:"); + System.out.println("calling next:"); for (int i = 0; i < 3; ++i) { - logln("[" + i + "] " + (elements_next[i] = iter.next())); + System.out.println("[" + i + "] " + (elements_next[i] = iter.next())); } int[] elements_fwd = new int[3]; - logln("calling set/next:"); + System.out.println("calling set/next:"); for (int i = 0; i < 3; ++i) { iter.setOffset(i); - logln("[" + i + "] " + (elements_fwd[i] = iter.next())); + System.out.println("[" + i + "] " + (elements_fwd[i] = iter.next())); } for (int i = 0; i < 3; ++i) { if (elements_next[i] != elements_fwd[i]) { - errln("mismatch at position " + i + + fail("mismatch at position " + i + ": " + elements_next[i] + " != " + elements_fwd[i]); } @@ -904,8 +941,8 @@ private void compareArray(Collator c, String[] tests) { int result = c.compare(tests[i], tests[i+2]); if (sign(result) != sign(expect)) { - errln( i/3 + ": compare(" + prettify(tests[i]) - + " , " + prettify(tests[i+2]) + fail( i/3 + ": compare(" + TestUtils.prettify(tests[i]) + + " , " + TestUtils.prettify(tests[i+2]) + ") got " + result + "; expected " + expect); } else @@ -916,11 +953,11 @@ private void compareArray(Collator c, String[] tests) { result = k1.compareTo(k2); if (sign(result) != sign(expect)) { - errln( i/3 + ": key(" + prettify(tests[i]) - + ").compareTo(key(" + prettify(tests[i+2]) + fail( i/3 + ": key(" + TestUtils.prettify(tests[i]) + + ").compareTo(key(" + TestUtils.prettify(tests[i+2]) + ")) got " + result + "; expected " + expect); - errln(" " + prettify(k1) + " vs. " + prettify(k2)); + fail(" " + TestUtils.prettifyCKey(k1) + " vs. " + TestUtils.prettifyCKey(k2)); } } } diff --git a/test/jdk/java/text/Collator/SpanishTest.java b/test/jdk/java/text/Collator/SpanishTest.java index fab4ef0d66b..3f5a9484426 100644 --- a/test/jdk/java/text/Collator/SpanishTest.java +++ b/test/jdk/java/text/Collator/SpanishTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,6 +25,7 @@ * @test * @library /java/text/testlib * @summary test Spanish Collation + * @run junit SpanishTest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -41,12 +42,12 @@ import java.util.Locale; import java.text.Collator; -// Quick dummy program for printing out test results -public class SpanishTest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new SpanishTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +// Quick dummy program for printing out test results +public class SpanishTest { /* * TestPrimary() @@ -92,13 +93,15 @@ public static void main(String[] args) throws Exception { -1, -1, 1, -1, -1 }; + @Test public void TestPrimary() { - doTest(myCollation, Collator.PRIMARY, + TestUtils.doCollatorTest(myCollation, Collator.PRIMARY, primarySourceData, primaryTargetData, primaryResults); } + @Test public void TestTertiary() { - doTest(myCollation, Collator.TERTIARY, + TestUtils.doCollatorTest(myCollation, Collator.TERTIARY, tertiarySourceData, tertiaryTargetData, tertiaryResults); } diff --git a/test/jdk/java/text/Collator/SurrogatesTest.java b/test/jdk/java/text/Collator/SurrogatesTest.java index 87df904e882..3825b31781f 100644 --- a/test/jdk/java/text/Collator/SurrogatesTest.java +++ b/test/jdk/java/text/Collator/SurrogatesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,17 +25,18 @@ * @test * @library /java/text/testlib * @summary test Supplementary Character Collation + * @run junit SurrogatesTest */ import java.text.Collator; import java.text.RuleBasedCollator; -// Quick dummy program for printing out test results -public class SurrogatesTest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new SurrogatesTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +// Quick dummy program for printing out test results +public class SurrogatesTest { /* * Data for TestPrimary() @@ -83,13 +84,15 @@ public static void main(String[] args) throws Exception { -1, 1, 1, 1, -1, -1, -1, -1, 1 }; + @Test public void TestPrimary() { - doTest(myCollation, Collator.PRIMARY, + TestUtils.doCollatorTest(myCollation, Collator.PRIMARY, primarySourceData, primaryTargetData, primaryResults); } + @Test public void TestTertiary() { - doTest(myCollation, Collator.TERTIARY, + TestUtils.doCollatorTest(myCollation, Collator.TERTIARY, tertiarySourceData, tertiaryTargetData, tertiaryResults); } @@ -108,7 +111,7 @@ private Collator getCollator() { + "&\ud800\udc0a < x, X" + "&A < \ud800\udc04\ud800\udc05"); } catch (Exception e) { - errln("Failed to create new RulebasedCollator object"); + fail("Failed to create new RulebasedCollator object"); return null; } } diff --git a/test/jdk/java/text/Collator/Test4401726.java b/test/jdk/java/text/Collator/Test4401726.java index 6f9e9ed945e..3c5b1dfe959 100644 --- a/test/jdk/java/text/Collator/Test4401726.java +++ b/test/jdk/java/text/Collator/Test4401726.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,6 +27,7 @@ * @author John O'Conner * @library /java/text/testlib * @summary Regression tests for Collation and associated classes + * @run junit Test4401726 */ @@ -34,12 +35,13 @@ import java.util.Locale; import java.util.Vector; -public class Test4401726 extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new Test4401726().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class Test4401726 { + @Test public void TestSetOffSet() { int[] expected = {0, -1, 65536}; @@ -60,7 +62,7 @@ public void TestSetOffSet() { actual[2] = iterator.next(); if (compareArray(expected, actual) == false) { - errln("Failed."); + fail("Failed."); } str = "a"; @@ -72,11 +74,11 @@ public void TestSetOffSet() { actual[2] = iterator.next(); if (compareArray(expected, actual) == false) { - errln("Failed."); + fail("Failed."); } } catch (ParseException e) { - errln("Unexpected ParseException: " + e); + fail("Unexpected ParseException: " + e); } diff --git a/test/jdk/java/text/Collator/ThaiTest.java b/test/jdk/java/text/Collator/ThaiTest.java index 7a961ed5968..f64fe12f9ea 100644 --- a/test/jdk/java/text/Collator/ThaiTest.java +++ b/test/jdk/java/text/Collator/ThaiTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @library /java/text/testlib * @summary test Thai Collation * @modules jdk.localedata + * @run junit ThaiTest */ /* * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. @@ -39,11 +40,11 @@ import java.text.Collator; import java.text.RuleBasedCollator; -public class ThaiTest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new ThaiTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class ThaiTest { /* * Data for TestPrimary() @@ -148,8 +149,9 @@ public static void main(String[] args) throws Exception { 0, 0, 0 }; + @Test public void TestPrimary() { - doTest(myCollation, Collator.PRIMARY, + TestUtils.doCollatorTest(myCollation, Collator.PRIMARY, primarySourceData, primaryTargetData, primaryResults); } diff --git a/test/jdk/java/text/Collator/TurkishTest.java b/test/jdk/java/text/Collator/TurkishTest.java index d8c078abb4d..1fb07bd5b0f 100644 --- a/test/jdk/java/text/Collator/TurkishTest.java +++ b/test/jdk/java/text/Collator/TurkishTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @library /java/text/testlib * @summary test Turkish Collation * @modules jdk.localedata + * @run junit TurkishTest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -42,12 +43,12 @@ import java.util.Locale; import java.text.Collator; -// Quick dummy program for printing out test results -public class TurkishTest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new TurkishTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +// Quick dummy program for printing out test results +public class TurkishTest { /* * Data for TestPrimary() @@ -105,13 +106,15 @@ public static void main(String[] args) throws Exception { -1, -1, -1, -1, 1, -1, -1, 1, -1, -1 }; + @Test public void TestPrimary() { - doTest(myCollation, Collator.PRIMARY, + TestUtils.doCollatorTest(myCollation, Collator.PRIMARY, primarySourceData, primaryTargetData, primaryResults); } + @Test public void TestTertiary() { - doTest(myCollation, Collator.TERTIARY, + TestUtils.doCollatorTest(myCollation, Collator.TERTIARY, tertiarySourceData, tertiaryTargetData, tertiaryResults); } diff --git a/test/jdk/java/text/Collator/VietnameseTest.java b/test/jdk/java/text/Collator/VietnameseTest.java index 6708622d096..fb6ecf4fa9f 100644 --- a/test/jdk/java/text/Collator/VietnameseTest.java +++ b/test/jdk/java/text/Collator/VietnameseTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,6 +27,7 @@ * @library /java/text/testlib * @summary test Vietnamese Collation * @modules jdk.localedata + * @run junit VietnameseTest */ /* @@ -44,12 +45,12 @@ import java.util.Locale; import java.text.Collator; -// Quick dummy program for printing out test results -public class VietnameseTest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new VietnameseTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +// Quick dummy program for printing out test results +public class VietnameseTest { private final static String testPS[] = { "a", @@ -346,17 +347,19 @@ public static void main(String[] args) throws Exception { "Z" }; + @Test public void TestPrimary() { - doTest(myCollation, Collator.PRIMARY, testPS, testPT, testPR); + TestUtils.doCollatorTest(myCollation, Collator.PRIMARY, testPS, testPT, testPR); } + @Test public void TestTertiary() { int testLength = testT.length; myCollation.setStrength(Collator.TERTIARY); for (int i = 0; i < testLength - 1; i++) { for (int j = i+1; j < testLength; j++) { - doTest(myCollation, testT[i], testT[j], -1); + TestUtils.doCollatorTest(myCollation, testT[i], testT[j], -1); } } } diff --git a/test/jdk/java/text/Format/ChoiceFormat/Bug4185732Test.java b/test/jdk/java/text/Format/ChoiceFormat/Bug4185732Test.java index f7d6bceebf8..51edac17d38 100644 --- a/test/jdk/java/text/Format/ChoiceFormat/Bug4185732Test.java +++ b/test/jdk/java/text/Format/ChoiceFormat/Bug4185732Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,10 +25,11 @@ * @test * @bug 4185732 * @library /java/text/testlib - * @build Bug4185732Test IntlTest HexDumpReader - * @run main Bug4185732Test - * @summary test that ChoiceFormat invariants are preserved across serialization + * @build Bug4185732Test HexDumpReader + * @run junit Bug4185732Test + * @summary test that ChoiceFormat invariants are preserved across serialization. */ + /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. @@ -67,54 +68,32 @@ import java.io.*; import java.text.ChoiceFormat; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + /** - * A Locale can never contains language codes of he, yi or id. + * A Locale can never contain language codes of he, yi or id. */ -public class Bug4185732Test extends IntlTest { - public static void main(String[] args) throws Exception { - if (args.length == 1 && args[0].equals("prepTest")) { - prepTest(); - } else { - new Bug4185732Test().run(args); - } - } - +public class Bug4185732Test { + @Test public void testIt() throws Exception { try { final ObjectInputStream in = new ObjectInputStream(HexDumpReader.getStreamFromHexDump("Bug4185732.ser.txt")); final ChoiceFormat loc = (ChoiceFormat)in.readObject(); if (loc.getFormats().length != loc.getLimits().length) { - errln("ChoiceFormat did not properly check stream"); + fail("ChoiceFormat did not properly check stream"); } else { //for some reason, the data file was VALID. This test //requires a corrupt data file the format and limit //arrays are of different length. - errln("Test data file was not properly created"); + fail("Test data file was not properly created"); } } catch (InvalidObjectException e) { //this is what we want to have happen } catch (Exception e) { - errln(e.toString()); - } - } - - /** - * Create a data file for this test. The data file must be corrupted by hand. - */ - private static void prepTest() { - try { - ObjectOutputStream out = new ObjectOutputStream( - new FileOutputStream("Bug4185732.ser")); - final double[] limits = {1,2,3,4,5,6,7}; - final String[] formats = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}; - final ChoiceFormat fmt = new ChoiceFormat(limits, formats); - out.writeObject(fmt); - out.close(); - System.out.println("You must invalidate the output file before running the test"); - System.out.println("by modifying the length of one of the array"); - } catch (Exception e) { - System.out.println(e); + fail(e.toString()); } } } diff --git a/test/jdk/java/text/Format/DateFormat/Bug4322313.java b/test/jdk/java/text/Format/DateFormat/Bug4322313.java index b6ddef99a1b..e99bf1ed6c8 100644 --- a/test/jdk/java/text/Format/DateFormat/Bug4322313.java +++ b/test/jdk/java/text/Format/DateFormat/Bug4322313.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,17 +24,22 @@ /** * @test * @bug 4322313 4833268 6302990 6304305 - * @library /java/text/testlib * @summary Make sure that new implementation for * SimpleDateFormat.parse('z' or 'Z') and format('z' or 'Z') work correctly. + * @run junit Bug4322313 */ import java.io.*; import java.text.*; import java.util.*; -public class Bug4322313 extends IntlTest { +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.fail; + +public class Bug4322313 { + + @Test public void Test4322313() { Locale savedLocale = Locale.getDefault(); TimeZone savedTimeZone = TimeZone.getDefault(); @@ -200,7 +205,7 @@ public void Test4322313() { ", got:" + date.getTime() + ", " + date); } else { /* - logln("\tParse Okay [Locale=" + + System.out.println("\tParse Okay [Locale=" + locale) + ", " + formats[j] + "/\"" + valids[k][0] + "\"] expected:" + valids[k][1] + @@ -252,7 +257,7 @@ public void Test4322313() { ", got:" + s + ", " + date); } else { /* - logln("\tFormat Okay [Locale=" + + System.out.println("\tFormat Okay [Locale=" + locale + ", " + formats[j] + "/\"" + valids[k][0] + "\"] expected:" + valids[k][2+j] + @@ -286,7 +291,7 @@ public void Test4322313() { invalids[k][1] + ", got: " + offset); } else { /* - logln("\tParse Okay [Locale=" + + System.out.println("\tParse Okay [Locale=" + locale + ", " + formats[j] + "/\"" + invalids[k][0] + "\"] correct offset: " + offset); @@ -322,7 +327,7 @@ public void Test4322313() { invalids[k][1] + ", got: " + offset); } else { /* - logln("\tParse Okay [Locale=" + + System.out.println("\tParse Okay [Locale=" + locale + ", " + formats[j] + "/\"" + invalids[k][0] + "\"] Expected exception occurred with an correct offset: " @@ -354,12 +359,9 @@ public void Test4322313() { Locale.setDefault(savedLocale); TimeZone.setDefault(savedTimeZone); if (err) { - errln("SimpleDateFormat.parse()/format() test failed"); + fail("SimpleDateFormat.parse()/format() test failed"); } } } - public static void main(String[] args) throws Exception { - new Bug4322313().run(args); - } } diff --git a/test/jdk/java/text/Format/DateFormat/DateFormatRegression.java b/test/jdk/java/text/Format/DateFormat/DateFormatRegression.java index fe763a341cb..c60a95d065d 100644 --- a/test/jdk/java/text/Format/DateFormat/DateFormatRegression.java +++ b/test/jdk/java/text/Format/DateFormat/DateFormatRegression.java @@ -25,6 +25,10 @@ import java.util.*; import java.io.*; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + /** * @test * @bug 4029195 4052408 4056591 4059917 4060212 4061287 4065240 4071441 4073003 @@ -32,55 +36,53 @@ * 4134203 4138203 4148168 4151631 4151706 4153860 4162071 4182066 4209272 4210209 * 4213086 4250359 4253490 4266432 4406615 4413980 8008577 8305853 * @library /java/text/testlib - * @run main/othervm -Djava.locale.providers=COMPAT,SPI DateFormatRegression + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI DateFormatRegression */ -public class DateFormatRegression extends IntlTest { - - public static void main(String[] args) throws Exception { - new DateFormatRegression().run(args); - } +public class DateFormatRegression { + @Test public void Test4029195() { @SuppressWarnings("deprecation") Date today = new Date(); - logln("today: " + today); + System.out.println("today: " + today); SimpleDateFormat sdf = (SimpleDateFormat)SimpleDateFormat.getDateInstance(); - logln("pattern: " + sdf.toPattern()); - logln("today: " + sdf.format(today)); + System.out.println("pattern: " + sdf.toPattern()); + System.out.println("today: " + sdf.format(today)); sdf.applyPattern("G yyyy DDD"); String todayS = sdf.format(today); - logln("today: " + todayS); + System.out.println("today: " + todayS); try { today = sdf.parse(todayS); - logln("today date: " + today); + System.out.println("today date: " + today); } catch(Exception e) { - logln("Error reparsing date: " + e.getMessage()); + System.out.println("Error reparsing date: " + e.getMessage()); } try { String rt = sdf.format(sdf.parse(todayS)); - logln("round trip: " + rt); - if (!rt.equals(todayS)) errln("Fail: Want " + todayS + " Got " + rt); + System.out.println("round trip: " + rt); + if (!rt.equals(todayS)) fail("Fail: Want " + todayS + " Got " + rt); } catch (ParseException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } } + @Test public void Test4052408() { DateFormat fmt = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.US); @SuppressWarnings("deprecation") Date date = new Date(97, Calendar.MAY, 3, 8, 55); String str; - logln(str = fmt.format(date)); + System.out.println(str = fmt.format(date)); if (!str.equals("5/3/97 8:55 AM")) - errln("Fail: Test broken; Want 5/3/97 8:55 AM Got " + str); + fail("Fail: Test broken; Want 5/3/97 8:55 AM Got " + str); Map expected = new HashMap<>(); expected.put(DateFormat.MONTH_FIELD, "5"); expected.put(DateFormat.DATE_FIELD, "3"); @@ -117,33 +119,34 @@ public void Test4052408() { char[] dst = new char[pos.getEndIndex() - pos.getBeginIndex()]; buf.getChars(pos.getBeginIndex(), pos.getEndIndex(), dst, 0); str = new String(dst); - log(i + ": " + fieldNames[i] + + System.out.println(i + ": " + fieldNames[i] + ", \"" + str + "\", " + pos.getBeginIndex() + ", " + pos.getEndIndex()); String exp = expected.get(i); if ((exp == null && str.length() == 0) || str.equals(exp)) - logln(" ok"); + System.out.println(" ok"); else { - logln(" expected " + exp); + System.out.println(" expected " + exp); pass = false; } } - if (!pass) errln("Fail: FieldPosition not set right by DateFormat"); + if (!pass) fail("Fail: FieldPosition not set right by DateFormat"); } /** * Verify the function of the [s|g]et2DigitYearStart() API. */ @SuppressWarnings("deprecation") + @Test public void Test4056591() { try { SimpleDateFormat fmt = new SimpleDateFormat("yyMMdd", Locale.US); Date start = new Date(1809-1900, Calendar.DECEMBER, 25); fmt.set2DigitYearStart(start); if (!fmt.get2DigitYearStart().equals(start)) - errln("get2DigitYearStart broken"); + fail("get2DigitYearStart broken"); Object[] DATA = { "091225", new Date(1809-1900, Calendar.DECEMBER, 25), "091224", new Date(1909-1900, Calendar.DECEMBER, 24), @@ -154,20 +157,21 @@ public void Test4056591() { String s = (String) DATA[i]; Date exp = (Date) DATA[i+1]; Date got = fmt.parse(s); - logln(s + " -> " + got + "; exp " + exp); - if (!got.equals(exp)) errln("set2DigitYearStart broken"); + System.out.println(s + " -> " + got + "; exp " + exp); + if (!got.equals(exp)) fail("set2DigitYearStart broken"); } } catch (ParseException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } } + @Test public void Test4059917() { Locale locale = Locale.getDefault(); if (!TestUtils.usesAsciiDigits(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -185,54 +189,55 @@ public void Test4059917() { void aux917( SimpleDateFormat fmt, String str ) { try { - logln( "==================" ); - logln( "testIt: pattern=" + fmt.toPattern() + + System.out.println( "==================" ); + System.out.println( "testIt: pattern=" + fmt.toPattern() + " string=" + str ); Object o; o = fmt.parseObject( str ); - logln( "Parsed object: " + o ); + System.out.println( "Parsed object: " + o ); String formatted = fmt.format( o ); - logln( "Formatted string: " + formatted ); - if (!formatted.equals(str)) errln("Fail: Want " + str + " Got " + formatted); + System.out.println( "Formatted string: " + formatted ); + if (!formatted.equals(str)) fail("Fail: Want " + str + " Got " + formatted); } catch (ParseException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } } + @Test public void Test4060212() { Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); try { String dateString = "1995-040.05:01:29"; - logln( "dateString= " + dateString ); - logln("Using yyyy-DDD.hh:mm:ss"); + System.out.println( "dateString= " + dateString ); + System.out.println("Using yyyy-DDD.hh:mm:ss"); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-DDD.hh:mm:ss"); ParsePosition pos = new ParsePosition(0); Date myDate = formatter.parse( dateString, pos ); String myString = DateFormat.getDateTimeInstance( DateFormat.FULL, DateFormat.LONG).format( myDate ); - logln( myString ); + System.out.println( myString ); Calendar cal = new GregorianCalendar(); cal.setTime(myDate); if (cal.get(Calendar.DAY_OF_YEAR) != 40) - errln("Fail: Got " + cal.get(Calendar.DAY_OF_YEAR) + + fail("Fail: Got " + cal.get(Calendar.DAY_OF_YEAR) + " Want 40"); - logln("Using yyyy-ddd.hh:mm:ss"); + System.out.println("Using yyyy-ddd.hh:mm:ss"); formatter = new SimpleDateFormat("yyyy-ddd.hh:mm:ss"); pos = new ParsePosition(0); myDate = formatter.parse( dateString, pos ); myString = DateFormat.getDateTimeInstance( DateFormat.FULL, DateFormat.LONG).format( myDate ); - logln( myString ); + System.out.println( myString ); cal.setTime(myDate); if (cal.get(Calendar.DAY_OF_YEAR) != 40) - errln("Fail: Got " + cal.get(Calendar.DAY_OF_YEAR) + + fail("Fail: Got " + cal.get(Calendar.DAY_OF_YEAR) + " Want 40"); } finally { @@ -240,24 +245,26 @@ public void Test4060212() { } } + @Test public void Test4061287() { SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); try { - logln(df.parse("35/01/1971").toString()); + System.out.println(df.parse("35/01/1971").toString()); } catch (ParseException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } df.setLenient(false); boolean ok = false; try { - logln(df.parse("35/01/1971").toString()); + System.out.println(df.parse("35/01/1971").toString()); } catch (ParseException e) {ok=true;} - if (!ok) errln("Fail: Lenient not working"); + if (!ok) fail("Fail: Lenient not working"); } @SuppressWarnings("deprecation") + @Test public void Test4065240() { Date curDate; DateFormat shortdate, fulldate; @@ -276,13 +283,13 @@ public void Test4065240() { format(curDate)); strFullDate = new String("The current date (long form) is " + fulldate.format(curDate)); - logln(strShortDate); - logln(strFullDate); + System.out.println(strShortDate); + System.out.println(strFullDate); // UPDATE THIS AS ZONE NAME RESOURCE FOR in de_DE is updated if (!strFullDate.endsWith("EST") && !strFullDate.endsWith("GMT-05:00")) { - errln("Fail: Want GMT-05:00"); + fail("Fail: Want GMT-05:00"); } } finally { @@ -301,6 +308,7 @@ public void Test4065240() { Currently this bug breaks MessageFormat.toPattern */ @SuppressWarnings("deprecation") + @Test public void Test4071441() { DateFormat fmtA = DateFormat.getInstance(); DateFormat fmtB = DateFormat.getInstance(); @@ -311,15 +319,15 @@ public void Test4071441() { calA.setTime(epoch); calB.setTime(epoch); if (!calA.equals(calB)) - errln("Fail: Can't complete test; Calendar instances unequal"); + fail("Fail: Can't complete test; Calendar instances unequal"); if (!fmtA.equals(fmtB)) - errln("Fail: DateFormat unequal when Calendars equal"); + fail("Fail: DateFormat unequal when Calendars equal"); calB.setTime(xmas); if (calA.equals(calB)) - errln("Fail: Can't complete test; Calendar instances equal"); + fail("Fail: Can't complete test; Calendar instances equal"); if (!fmtA.equals(fmtB)) - errln("Fail: DateFormat unequal when Calendars equivalent"); - logln("DateFormat.equals ok"); + fail("Fail: DateFormat unequal when Calendars equivalent"); + System.out.println("DateFormat.equals ok"); } /* The java.text.DateFormat.parse(String) method expects for the @@ -332,6 +340,7 @@ public void Test4071441() { Please extend the parsing method(s) to handle strings with four-digit year values (probably also applicable to various other locales. */ + @Test public void Test4073003() { try { DateFormat fmt = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US); @@ -342,18 +351,19 @@ public void Test4073003() { String s = fmt.format(d); String ss = fmt.format(dd); if (!d.equals(dd)) - errln("Fail: " + d + " != " + dd); + fail("Fail: " + d + " != " + dd); if (!s.equals(ss)) - errln("Fail: " + s + " != " + ss); - logln("Ok: " + s + " " + d); + fail("Fail: " + s + " != " + ss); + System.out.println("Ok: " + s + " " + d); } } catch (ParseException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } } + @Test public void Test4089106() { TimeZone def = TimeZone.getDefault(); try { @@ -361,13 +371,14 @@ public void Test4089106() { TimeZone.setDefault(customTz); SimpleDateFormat f = new SimpleDateFormat(); if (!f.getTimeZone().equals(customTz)) - errln("Fail: SimpleDateFormat should use TimeZone.getDefault()"); + fail("Fail: SimpleDateFormat should use TimeZone.getDefault()"); } finally { TimeZone.setDefault(def); } } + @Test public void Test4100302() { Locale[] locales = new Locale[] { Locale.CANADA, @@ -414,21 +425,21 @@ public void Test4100302() { if (!format.equals(ois.readObject())) { pass = false; - logln("DateFormat instance for locale " + + System.out.println("DateFormat instance for locale " + locales[i] + " is incorrectly serialized/deserialized."); } else { - logln("DateFormat instance for locale " + + System.out.println("DateFormat instance for locale " + locales[i] + " is OKAY."); } } - if (!pass) errln("Fail: DateFormat serialization/equality bug"); + if (!pass) fail("Fail: DateFormat serialization/equality bug"); } catch (IOException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } catch (ClassNotFoundException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } } @@ -437,6 +448,7 @@ public void Test4100302() { * Test whether DataFormat can be serialized/deserialized correctly * even if invalid/customized TimeZone is used. */ + @Test public void Test4413980() { TimeZone savedTimeZone = TimeZone.getDefault(); try { @@ -465,23 +477,23 @@ public void Test4413980() { if (!format.equals(ois.readObject())) { pass = false; - logln("DateFormat instance which uses TimeZone <" + + System.out.println("DateFormat instance which uses TimeZone <" + IDs[i] + "> is incorrectly serialized/deserialized."); } else { - logln("DateFormat instance which uses TimeZone <" + + System.out.println("DateFormat instance which uses TimeZone <" + IDs[i] + "> is correctly serialized/deserialized."); } } if (!pass) { - errln("Fail: DateFormat serialization/equality bug"); + fail("Fail: DateFormat serialization/equality bug"); } } catch (IOException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } catch (ClassNotFoundException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } finally { @@ -489,17 +501,18 @@ public void Test4413980() { } } + @Test public void Test4101483() { SimpleDateFormat sdf = new SimpleDateFormat("z", Locale.US); FieldPosition fp = new FieldPosition(DateFormat.TIMEZONE_FIELD); @SuppressWarnings("deprecation") Date d= new Date(9234567890L); StringBuffer buf = new StringBuffer(""); - logln(sdf.format(d, buf, fp).toString()); - logln(d + " => " + buf); - logln("beginIndex = " + fp.getBeginIndex()); - logln("endIndex = " + fp.getEndIndex()); - if (fp.getBeginIndex() == fp.getEndIndex()) errln("Fail: Empty field"); + System.out.println(sdf.format(d, buf, fp).toString()); + System.out.println(d + " => " + buf); + System.out.println("beginIndex = " + fp.getBeginIndex()); + System.out.println("endIndex = " + fp.getEndIndex()); + if (fp.getBeginIndex() == fp.getEndIndex()) fail("Fail: Empty field"); } /** @@ -510,6 +523,7 @@ public void Test4101483() { * NT; it would actually have failed on any non-US locale. Now it should * work on all locales. */ + @Test public void Test4103340() { // choose a date that is the FIRST of some month // and some arbitrary time @@ -519,30 +533,32 @@ public void Test4103340() { String s = d.toString(); String s2 = df.format(d); - logln("Date="+s); - logln("DF="+s2); + System.out.println("Date="+s); + System.out.println("DF="+s2); if (s.indexOf(s2.substring(0,2)) == -1) - errln("Months should match"); + fail("Months should match"); } + @Test public void Test4103341() { TimeZone saveZone =TimeZone.getDefault(); try { TimeZone.setDefault(TimeZone.getTimeZone("CST")); SimpleDateFormat simple = new SimpleDateFormat("MM/dd/yyyy HH:mm"); if (!simple.getTimeZone().equals(TimeZone.getDefault())) - errln("Fail: SimpleDateFormat not using default zone"); + fail("Fail: SimpleDateFormat not using default zone"); } finally { TimeZone.setDefault(saveZone); } } + @Test public void Test4104136() { SimpleDateFormat sdf = new SimpleDateFormat(); String pattern = "'time' hh:mm"; sdf.applyPattern(pattern); - logln("pattern: \"" + pattern + "\""); + System.out.println("pattern: \"" + pattern + "\""); @SuppressWarnings("deprecation") Object[] DATA = { @@ -557,14 +573,14 @@ public void Test4104136() { ParsePosition pos = new ParsePosition(0); Date d = sdf.parse(text, pos); - logln(" text: \"" + text + "\""); - logln(" index: " + pos.getIndex()); - logln(" result: " + d); + System.out.println(" text: \"" + text + "\""); + System.out.println(" index: " + pos.getIndex()); + System.out.println(" result: " + d); if (pos.getIndex() != finish.getIndex()) - errln("Fail: Expected pos " + finish.getIndex()); + fail("Fail: Expected pos " + finish.getIndex()); if (!((d == null && exp == null) || d.equals(exp))) - errln("Fail: Expected result " + exp); + fail("Fail: Expected result " + exp); } } @@ -574,27 +590,29 @@ public void Test4104136() { * StringIndexOutOfBoundsException during the second parse. However, * this is not seen. */ + @Test public void Test4104522() { SimpleDateFormat sdf = new SimpleDateFormat(); String pattern = "'time' hh:mm"; sdf.applyPattern(pattern); - logln("pattern: \"" + pattern + "\""); + System.out.println("pattern: \"" + pattern + "\""); // works correctly ParsePosition pp = new ParsePosition(0); String text = "time "; Date date = sdf.parse(text, pp); - logln(" text: \"" + text + "\"" + + System.out.println(" text: \"" + text + "\"" + " date: " + date); // works wrong pp = new ParsePosition(0); text = "time"; date = sdf.parse(text, pp); - logln(" text: \"" + text + "\"" + + System.out.println(" text: \"" + text + "\"" + " date: " + date); } + @Test public void Test4106807() { Date date; DateFormat df = DateFormat.getDateTimeInstance(); @@ -618,13 +636,13 @@ public void Test4106807() { try { format.setTimeZone(gmt); date = format.parse(dateString); - logln(df.format(date)); + System.out.println(df.format(date)); gc.setTime(date); - logln("" + gc.get(Calendar.ZONE_OFFSET)); - logln(format.format(date)); + System.out.println("" + gc.get(Calendar.ZONE_OFFSET)); + System.out.println(format.format(date)); } catch (ParseException e) { - logln("No way Jose"); + System.out.println("No way Jose"); } } } @@ -632,12 +650,13 @@ public void Test4106807() { /** * SimpleDateFormat won't parse "GMT" */ + @Test public void Test4134203() { String dateFormat = "MM/dd/yy HH:mm:ss zzz"; SimpleDateFormat fmt = new SimpleDateFormat(dateFormat); ParsePosition p0 = new ParsePosition(0); Date d = fmt.parse("01/22/92 04:52:00 GMT", p0); - logln(d.toString()); + System.out.println(d.toString()); // In the failure case an exception is thrown by parse(); // if no exception is thrown, the test passes. } @@ -645,12 +664,13 @@ public void Test4134203() { /** * Another format for GMT string parse */ + @Test public void Test4266432() { String dateFormat = "MM/dd HH:mm:ss zzz yyyy"; SimpleDateFormat fmt = new SimpleDateFormat(dateFormat); ParsePosition p0 = new ParsePosition(0); Date d = fmt.parse("01/22 04:52:00 GMT 1992", p0); - logln(d.toString()); + System.out.println(d.toString()); // In the failure case an exception is thrown by parse(); // if no exception is thrown, the test passes. } @@ -662,6 +682,7 @@ public void Test4266432() { * NOTE: Updated for fixed semantics as of Kestrel. See * 4253490 */ + @Test public void Test4148168() throws ParseException { SimpleDateFormat fmt = new SimpleDateFormat("", Locale.US); int ms = 456; @@ -677,7 +698,7 @@ public void Test4148168() throws ParseException { fmt.applyPattern(PAT[i]); String str = fmt.format(d); if (!str.equals(OUT[i])) { - errln("FAIL: " + ms + " ms x \"" + PAT[i] + "\" -> \"" + + fail("FAIL: " + ms + " ms x \"" + PAT[i] + "\" -> \"" + str + "\", exp \"" + OUT[i] + '"'); } } @@ -692,7 +713,7 @@ public void Test4148168() throws ParseException { cal.setTime(d); ms = cal.get(Calendar.MILLISECOND); if (ms != MS[i]) { - errln("FAIL: parse(\"" + IN[i] + "\" x \"s.S\") -> " + + fail("FAIL: parse(\"" + IN[i] + "\" x \"s.S\") -> " + ms + " ms, exp " + MS[i] + " ms"); } } @@ -701,17 +722,18 @@ public void Test4148168() throws ParseException { /** * SimpleDateFormat incorrect handling of 2 single quotes in format() */ + @Test public void Test4151631() { String pattern = "'TO_DATE('''dd'-'MM'-'yyyy HH:mm:ss''' , ''DD-MM-YYYY HH:MI:SS'')'"; - logln("pattern=" + pattern); + System.out.println("pattern=" + pattern); SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.US); @SuppressWarnings("deprecation") String result = format.format(new Date(1998-1900, Calendar.JUNE, 30, 13, 30, 0)); if (!result.equals("TO_DATE('30-06-1998 13:30:00' , 'DD-MM-YYYY HH:MI:SS')")) { - errln("Fail: result=" + result); + fail("Fail: result=" + result); } else { - logln("Pass: result=" + result); + System.out.println("Pass: result=" + result); } } @@ -720,15 +742,16 @@ public void Test4151631() { * CANNOT REPRODUCE THIS BUG ON 1.2FCS */ @SuppressWarnings("deprecation") + @Test public void Test4151706() { SimpleDateFormat fmt = new SimpleDateFormat("EEEE, dd-MMM-yy HH:mm:ss z", Locale.US); try { Date d = fmt.parse("Thursday, 31-Dec-98 23:00:00 GMT"); if (d.getTime() != Date.UTC(1998-1900, Calendar.DECEMBER, 31, 23, 0, 0)) - errln("Incorrect value: " + d); + fail("Incorrect value: " + d); } catch (Exception e) { - errln("Fail: " + e); + fail("Fail: " + e); } } @@ -737,6 +760,7 @@ public void Test4151706() { * This is actually a bug down in GregorianCalendar, but it was reported * as follows... */ + @Test public void Test4153860() throws ParseException { Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); @@ -751,7 +775,7 @@ public void Test4153860() throws ParseException { // Try to create a Date for February 4th Date d2 = sf.parse("1998.02-04 1"); if (!d1.equals(d2)) { - errln("Parse failed, got " + d2 + + fail("Parse failed, got " + d2 + ", expected " + d1); } } @@ -765,6 +789,7 @@ public void Test4153860() throws ParseException { * as "EST" or "CST", not Australian "EST" and "CST". */ @SuppressWarnings("deprecation") + @Test public void Test4406615() { Locale savedLocale = Locale.getDefault(); TimeZone savedTimeZone = TimeZone.getDefault(); @@ -784,13 +809,13 @@ public void Test4406615() { d1.getDate() != 31 || d1.getHours() != 21 || d1.getMinutes() != 0 || d2.getYear() != (2000-1900) || d2.getMonth() != 11 || d2.getDate() != 31 || d2.getHours() != 22 || d2.getMinutes() != 0) { - errln("Parse failed, d1 = " + d1 + ", d2 = " + d2); + fail("Parse failed, d1 = " + d1 + ", d2 = " + d2); } else { - logln("Parse passed"); + System.out.println("Parse passed"); } } catch (Exception e) { - errln("Parse failed, got Exception " + e); + fail("Parse failed, got Exception " + e); } finally { Locale.setDefault(savedLocale); @@ -802,6 +827,7 @@ public void Test4406615() { * Cannot reproduce this bug under 1.2 FCS -- it may be a convoluted duplicate * of some other bug that has been fixed. */ + @Test public void Test4162071() { String dateString = "Thu, 30-Jul-1999 11:51:14 GMT"; String format = "EEE', 'dd-MMM-yyyy HH:mm:ss z"; // RFC 822/1123 @@ -810,16 +836,17 @@ public void Test4162071() { try { Date x = df.parse(dateString); - logln("Parse format \"" + format + "\" ok"); - logln(dateString + " -> " + df.format(x)); + System.out.println("Parse format \"" + format + "\" ok"); + System.out.println(dateString + " -> " + df.format(x)); } catch (Exception e) { - errln("Parse format \"" + format + "\" failed."); + fail("Parse format \"" + format + "\" failed."); } } /** * DateFormat shouldn't parse year "-1" as a two-digit year (e.g., "-1" -> 1999). */ + @Test public void Test4182066() { Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); @@ -869,9 +896,9 @@ public void Test4182066() { } } if (pass) { - log(out.toString()); + System.out.println(out.toString()); } else { - err(out.toString()); + fail(out.toString()); } } finally { @@ -884,6 +911,7 @@ public void Test4182066() { * Bug 4209272 * DateFormat cannot parse Feb 29 2000 when setLenient(false) */ + @Test public void Test4210209() { String pattern = "MMM d, yyyy"; DateFormat fmt = new SimpleDateFormat(pattern, @@ -892,13 +920,13 @@ public void Test4210209() { @SuppressWarnings("deprecation") Date d = new Date(2000-1900, Calendar.FEBRUARY, 29); String s = fmt.format(d); - logln(d + " x " + pattern + " => " + s); + System.out.println(d + " x " + pattern + " => " + s); ParsePosition pos = new ParsePosition(0); d = fmt.parse(s, pos); - logln(d + " <= " + pattern + " x " + s); - logln("Parse pos = " + pos); + System.out.println(d + " <= " + pattern + " x " + s); + System.out.println("Parse pos = " + pos); if (pos.getErrorIndex() != -1) { - errln("FAIL"); + fail("FAIL"); } // The underlying bug is in GregorianCalendar. If the following lines @@ -908,12 +936,13 @@ public void Test4210209() { cal.clear(); cal.setLenient(false); cal.set(2000, Calendar.FEBRUARY, 29); // This should work! - logln(cal.getTime().toString()); + System.out.println(cal.getTime().toString()); } /** * DateFormat.getDateTimeInstance() allows illegal parameters. */ + @Test public void Test4213086() { int[] DATA = { // Style value, 0/1 for illegal/legal @@ -962,7 +991,7 @@ public void Test4213086() { e = ex; } if (got != DATA[i+1] || e != null) { - errln("FAIL: DateFormat." + DESC[j] + " style " + DATA[i] + " " + + fail("FAIL: DateFormat." + DESC[j] + " style " + DATA[i] + " " + (e != null ? e.toString() : GOT[got])); } } @@ -970,6 +999,7 @@ public void Test4213086() { } @SuppressWarnings("deprecation") + @Test public void Test4253490() throws ParseException { SimpleDateFormat fmt = new SimpleDateFormat("S", Locale.US); @@ -993,10 +1023,10 @@ public void Test4253490() throws ParseException { fmt.applyPattern(FORMAT_PAT[i]); String s = fmt.format(d); if (s.equals(FORMAT_TO[i])) { - logln(String.valueOf(FORMAT_MS) + " ms f* \"" + + System.out.println(String.valueOf(FORMAT_MS) + " ms f* \"" + FORMAT_PAT[i] + "\" -> \"" + s + '"'); } else { - errln("FAIL: " + FORMAT_MS + " ms f* \"" + + fail("FAIL: " + FORMAT_MS + " ms f* \"" + FORMAT_PAT[i] + "\" -> \"" + s + "\", expect \"" + FORMAT_TO[i] + '"'); } @@ -1008,10 +1038,10 @@ public void Test4253490() throws ParseException { cal.setTime(fmt.parse(PARSE_STR[i])); int ms = cal.get(Calendar.MILLISECOND); if (ms == PARSE_TO[i]) { - logln("\"" + PARSE_STR[i] + "\" p* \"" + + System.out.println("\"" + PARSE_STR[i] + "\" p* \"" + PARSE_PAT + "\" -> " + ms + " ms"); } else { - errln("FAIL: \"" + PARSE_STR[i] + "\" p* \"" + + fail("FAIL: \"" + PARSE_STR[i] + "\" p* \"" + PARSE_PAT + "\" -> " + ms + " ms, expect " + PARSE_TO[i] + " ms"); } @@ -1023,10 +1053,10 @@ public void Test4253490() throws ParseException { cal.setTime(fmt.parse(PARSE_STR[i])); int ms = cal.get(Calendar.MILLISECOND); if (ms == PARSE_TO[i]) { - logln("\"" + PARSE_STR[i] + "\" p* \"" + + System.out.println("\"" + PARSE_STR[i] + "\" p* \"" + PARSE_LPAT + "\" -> " + ms + " ms"); } else { - errln("FAIL: \"" + PARSE_STR[i] + "\" p* \"" + + fail("FAIL: \"" + PARSE_STR[i] + "\" p* \"" + PARSE_LPAT + "\" -> " + ms + " ms, expect " + PARSE_TO[i] + " ms"); } @@ -1036,6 +1066,7 @@ public void Test4253490() throws ParseException { /** * Bug in handling of time instance; introduces in fix for 4213086. */ + @Test public void Test4250359() { DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.US); @@ -1048,7 +1079,7 @@ public void Test4250359() { int i = s.indexOf("AM"); int j = s.indexOf("AM", i+1); if (i < 0 || j >= 0) { - errln("FAIL: getTimeInstance().format(d) => \"" + + fail("FAIL: getTimeInstance().format(d) => \"" + s + "\""); } } @@ -1057,6 +1088,7 @@ public void Test4250359() { * Test whether SimpleDataFormat (DateFormatSymbols) can format/parse * non-localized time zones. */ + @Test public void Test4261506() { Locale savedLocale = Locale.getDefault(); TimeZone savedTimeZone = TimeZone.getDefault(); @@ -1068,22 +1100,22 @@ public void Test4261506() { SimpleDateFormat fmt = new SimpleDateFormat("yy/MM/dd hh:ss zzz", Locale.JAPAN); @SuppressWarnings("deprecation") String result = fmt.format(new Date(1999 - 1900, 0, 1)); - logln("format()=>" + result); + System.out.println("format()=>" + result); if (!result.endsWith("PST")) { - errln("FAIL: SimpleDataFormat.format() did not retrun PST"); + fail("FAIL: SimpleDataFormat.format() did not retrun PST"); } Date d = null; try { d = fmt.parse("99/1/1 10:10 PST"); } catch (ParseException e) { - errln("FAIL: SimpleDataFormat.parse() could not parse PST"); + fail("FAIL: SimpleDataFormat.parse() could not parse PST"); } result = fmt.format(d); - logln("roundtrip:" + result); + System.out.println("roundtrip:" + result); if (!result.equals("99/01/01 10:10 PST")) { - errln("FAIL: SimpleDataFomat timezone roundtrip failed"); + fail("FAIL: SimpleDataFomat timezone roundtrip failed"); } Locale.setDefault(savedLocale); diff --git a/test/jdk/java/text/Format/DateFormat/DateFormatRoundTripTest.java b/test/jdk/java/text/Format/DateFormat/DateFormatRoundTripTest.java index 9bf3ac3835a..8850285b275 100644 --- a/test/jdk/java/text/Format/DateFormat/DateFormatRoundTripTest.java +++ b/test/jdk/java/text/Format/DateFormat/DateFormatRoundTripTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,14 +25,13 @@ * @test * @summary test Date Format (Round Trip) * @bug 8008577 - * @library /java/text/testlib - * @run main/othervm -Djava.locale.providers=COMPAT,SPI DateFormatRoundTripTest + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI DateFormatRoundTripTest */ import java.text.*; import java.util.*; -public class DateFormatRoundTripTest extends IntlTest { +public class DateFormatRoundTripTest { static Random RANDOM = null; @@ -107,15 +106,15 @@ public static void main(String[] args) throws Exception { List newArgs = new ArrayList<>(); for (int i=0; i Random using as seed."); - super.usage(); } static private class TestCase { @@ -310,8 +309,8 @@ private interface FormatFactory { public void TestDateFormatRoundTrip() { avail = DateFormat.getAvailableLocales(); - logln("DateFormat available locales: " + avail.length); - logln("Default TimeZone: " + + System.out.println("DateFormat available locales: " + avail.length); + System.out.println("Default TimeZone: " + (defaultZone = TimeZone.getDefault()).getID()); if (random || initialDate != null) { @@ -333,7 +332,7 @@ public void TestDateFormatRoundTrip() { * TimeZone must be set to tc.zone before this method is called. */ private void doTestInZone(TestCase tc) { - logln(escape(tc.toString())); + System.out.println(escape(tc.toString())); Locale save = Locale.getDefault(); try { if (locale != null) { @@ -368,10 +367,10 @@ private void loopedTest() { if (INFINITE) { // Special infinite loop test mode for finding hard to reproduce errors if (locale != null) { - logln("ENTERING INFINITE TEST LOOP, LOCALE " + locale.getDisplayName()); + System.out.println("ENTERING INFINITE TEST LOOP, LOCALE " + locale.getDisplayName()); for (;;) doTest(locale); } else { - logln("ENTERING INFINITE TEST LOOP, ALL LOCALES"); + System.out.println("ENTERING INFINITE TEST LOOP, ALL LOCALES"); for (;;) { for (int i=0; i0&&d[j].getTime()==d[j-1].getTime()?" d==":"") + (j>0&&s[j].equals(s[j-1])?" s==":"")); } - errln(escape(out.toString())); + throw new RuntimeException(escape(out.toString())); } } } catch (ParseException e) { - errln(e.toString()); + throw new RuntimeException(e.toString()); } } diff --git a/test/jdk/java/text/Format/DateFormat/DateFormatTest.java b/test/jdk/java/text/Format/DateFormat/DateFormatTest.java index 5be792d1cd7..9e8c8684dc9 100644 --- a/test/jdk/java/text/Format/DateFormat/DateFormatTest.java +++ b/test/jdk/java/text/Format/DateFormat/DateFormatTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,30 +26,31 @@ * @bug 4052223 4089987 4469904 4326988 4486735 8008577 8045998 8140571 * 8190748 8216969 * @summary test DateFormat and SimpleDateFormat. - * @library /java/text/testlib * @modules jdk.localedata - * @run main/othervm -Djava.locale.providers=COMPAT,SPI DateFormatTest + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI DateFormatTest */ import java.util.*; import java.text.*; import static java.util.GregorianCalendar.*; -public class DateFormatTest extends IntlTest +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeAll; + +import static org.junit.jupiter.api.Assertions.fail; + +public class DateFormatTest { - public static void main(String[] args) throws Exception { - Locale reservedLocale = Locale.getDefault(); - try { - Locale.setDefault(Locale.US); - new DateFormatTest().run(args); - } finally { - // restore the reserved locale - Locale.setDefault(reservedLocale); - } + + // Change JVM default Locale + @BeforeAll + static void initAll() { + Locale.setDefault(Locale.US); } // Test 4 digit year parsing with pattern "yy" @SuppressWarnings("deprecation") + @Test public void TestYearParsing() { String str = "7/Sep/2001"; @@ -58,17 +59,18 @@ public void TestYearParsing() SimpleDateFormat sdf = new SimpleDateFormat(pat, Locale.US); try { Date d = sdf.parse(str); - logln(str + " parses with " + pat + " to " + d); + System.out.println(str + " parses with " + pat + " to " + d); if (d.getTime() != exp.getTime()) { - errln("FAIL: Expected " + exp); + fail("FAIL: Expected " + exp); } } catch (ParseException e) { - errln(str + " parse fails with " + pat); + fail(str + " parse fails with " + pat); } } // Test written by Wally Wedel and emailed to me. + @Test public void TestWallyWedel() { /* @@ -91,11 +93,11 @@ public void TestWallyWedel() /* * How many ids do we have? */ - logln("Time Zone IDs size: " + ids.length); + System.out.println("Time Zone IDs size: " + ids.length); /* * Column headings (sort of) */ - logln("Ordinal ID offset(h:m) name"); + System.out.println("Ordinal ID offset(h:m) name"); /* * Loop through the tzs. */ @@ -136,19 +138,20 @@ public void TestWallyWedel() boolean ok = fmtDstOffset == null || fmtDstOffset.equals(dstOffset); if (ok) { - logln(i + " " + ids[i] + " " + dstOffset + + System.out.println(i + " " + ids[i] + " " + dstOffset + " " + fmtOffset + (fmtDstOffset != null ? " ok" : " ?")); } else { - errln(i + " " + ids[i] + " " + dstOffset + + fail(i + " " + ids[i] + " " + dstOffset + " " + fmtOffset + " *** FAIL ***"); } } } // Test equals + @Test public void TestEquals() { DateFormat fmtA = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL); @@ -156,12 +159,13 @@ public void TestEquals() DateFormat fmtB = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL); if (!fmtA.equals(fmtB)) { - errln("FAIL"); + fail("FAIL"); } } // Check out some specific parsing problem @SuppressWarnings("deprecation") + @Test public void TestTwoDigitYearDSTParse() { SimpleDateFormat fullFmt = @@ -181,12 +185,12 @@ public void TestTwoDigitYearDSTParse() try { TimeZone.setDefault(PST); Date d = fmt.parse(s); - logln(s + " P> " + fullFmt.format(d)); + System.out.println(s + " P> " + fullFmt.format(d)); if (d.getHours() != hour) { - errln("FAIL: Should parse to hour " + hour); + fail("FAIL: Should parse to hour " + hour); } } - catch (ParseException e) { errln("FAIL: " + e.getMessage()); } + catch (ParseException e) { fail("FAIL: " + e.getMessage()); } finally { TimeZone.setDefault(save); } @@ -234,6 +238,7 @@ static String escape(String s) /** * Bug 4089987 */ + @Test public void TestFieldPosition() { DateFormat[] dateFormats = { @@ -273,13 +278,13 @@ public void TestFieldPosition() continue; } df.setTimeZone(PST); - logln(" Pattern = " + ((SimpleDateFormat)df).toPattern()); - logln(" Result = " + df.format(someDate)); + System.out.println(" Pattern = " + ((SimpleDateFormat)df).toPattern()); + System.out.println(" Result = " + df.format(someDate)); for (int i = 0; i < fieldIDs.length; ++i) { String field = getFieldText(df, fieldIDs[i], someDate); if (!field.equals(expected[exp])) { - errln("FAIL: field #" + i + " " + fieldNames[i] + " = \"" + + fail("FAIL: field #" + i + " " + fieldNames[i] + " = \"" + escape(field) + "\", expected \"" + escape(expected[exp]) + "\""); } ++exp; @@ -298,6 +303,7 @@ static String getFieldText(DateFormat df, int field, Date date) // Test parsing of partial strings @SuppressWarnings("deprecation") + @Test public void TestPartialParse994() { SimpleDateFormat f = new SimpleDateFormat(); @@ -312,34 +318,35 @@ public void TestPartialParse994() void tryPat994(SimpleDateFormat format, String pat, String str, Date expected) { - logln("Pattern \"" + pat + "\" String \"" + str + "\""); + System.out.println("Pattern \"" + pat + "\" String \"" + str + "\""); try { format.applyPattern(pat); Date date = format.parse(str); String f = format.format(date); - logln(" parse(" + str + ") -> " + date.toString()); - logln(" format -> " + f); + System.out.println(" parse(" + str + ") -> " + date.toString()); + System.out.println(" format -> " + f); if (expected == null || !date.equals(expected)) { - errln("FAIL: Expected " + expected); + fail("FAIL: Expected " + expected); } if (!f.equals(str)) { - errln("FAIL: Expected " + str); + fail("FAIL: Expected " + str); } } catch(ParseException e) { - logln("ParseException: " + e.getMessage()); + System.out.println("ParseException: " + e.getMessage()); if (expected != null) { - errln("FAIL: Expected " + expected); + fail("FAIL: Expected " + expected); } } catch(Exception e) { - errln("*** Exception:"); + fail("*** Exception:"); e.printStackTrace(); } } // Test pattern with runs things together + @Test public void TestRunTogetherPattern985() { String format = "yyyyMMddHHmmssSSSzzzz"; @@ -350,7 +357,7 @@ public void TestRunTogetherPattern985() Date date1 = new Date(); now = formatter.format(date1); - logln(now); + System.out.println(now); ParsePosition pos = new ParsePosition(0); @@ -361,15 +368,16 @@ public void TestRunTogetherPattern985() then = formatter.format(date2); } - logln(then); + System.out.println(then); if (!date2.equals(date1)) { - errln("FAIL"); + fail("FAIL"); } } // Test patterns which run numbers together @SuppressWarnings("deprecation") + @Test public void TestRunTogetherPattern917() { SimpleDateFormat fmt; @@ -386,7 +394,7 @@ public void TestRunTogetherPattern917() } void _testIt917( SimpleDateFormat fmt, String str, Date expected ) { - logln( "pattern=" + fmt.toPattern() + " string=" + str ); + System.out.println( "pattern=" + fmt.toPattern() + " string=" + str ); Object o; try { @@ -395,27 +403,28 @@ void _testIt917( SimpleDateFormat fmt, String str, Date expected ) e.printStackTrace(); return; } - logln( "Parsed object: " + o ); + System.out.println( "Parsed object: " + o ); if (!o.equals(expected)) { - errln("FAIL: Expected " + expected); + fail("FAIL: Expected " + expected); } String formatted = fmt.format( o ); - logln( "Formatted string: " + formatted ); + System.out.println( "Formatted string: " + formatted ); if (!formatted.equals(str)) { - errln("FAIL: Expected " + str); + fail("FAIL: Expected " + str); } } // Test Czech month formatting -- this can cause a problem because the June and // July month names share a common prefix. @SuppressWarnings("deprecation") + @Test public void TestCzechMonths459() { // Use Czech, which has month names with shared prefixes for June and July DateFormat fmt = DateFormat.getDateInstance(DateFormat.FULL, new Locale("cs", "", "")); //((SimpleDateFormat)fmt).applyPattern("MMMM d yyyy"); - logln("Pattern " + ((SimpleDateFormat)fmt).toPattern()); + System.out.println("Pattern " + ((SimpleDateFormat)fmt).toPattern()); Date june = new Date(97, Calendar.JUNE, 15); Date july = new Date(97, Calendar.JULY, 15); @@ -424,31 +433,32 @@ public void TestCzechMonths459() String julyStr = fmt.format(july); try { - logln("format(June 15 1997) = " + juneStr); + System.out.println("format(June 15 1997) = " + juneStr); Date d = fmt.parse(juneStr); String s = fmt.format(d); int month = d.getMonth(); - logln(" -> parse -> " + s + " (month = " + month + ")"); + System.out.println(" -> parse -> " + s + " (month = " + month + ")"); if (month != JUNE) { - errln("FAIL: Month should be June"); + fail("FAIL: Month should be June"); } - logln("format(July 15 1997) = " + julyStr); + System.out.println("format(July 15 1997) = " + julyStr); d = fmt.parse(julyStr); s = fmt.format(d); month = d.getMonth(); - logln(" -> parse -> " + s + " (month = " + month + ")"); + System.out.println(" -> parse -> " + s + " (month = " + month + ")"); if (month != JULY) { - errln("FAIL: Month should be July"); + fail("FAIL: Month should be July"); } } catch (ParseException e) { - errln("Exception: " + e); + fail("Exception: " + e); } } // Test big D (day of year) versus little d (day of month) @SuppressWarnings("deprecation") + @Test public void TestLetterDPattern212() { String dateString = "1995-040.05:01:29"; @@ -457,32 +467,33 @@ public void TestLetterDPattern212() Date expLittleD = new Date(95, 0, 1, 5, 1, 29); Date expBigD = new Date(expLittleD.getTime() + 39*24*3600000L); // 39 days expLittleD = expBigD; // Expect the same, with default lenient parsing - logln( "dateString= " + dateString ); + System.out.println( "dateString= " + dateString ); SimpleDateFormat formatter = new SimpleDateFormat(bigD); ParsePosition pos = new ParsePosition(0); Date myDate = formatter.parse( dateString, pos ); - logln("Using " + bigD + " -> " + myDate); + System.out.println("Using " + bigD + " -> " + myDate); if (myDate.getTime() != expBigD.getTime()) { - errln("FAIL: Expected " + expBigD + " got " + myDate); + fail("FAIL: Expected " + expBigD + " got " + myDate); } formatter = new SimpleDateFormat(littleD); pos = new ParsePosition(0); myDate = formatter.parse( dateString, pos ); - logln("Using " + littleD + " -> " + myDate); + System.out.println("Using " + littleD + " -> " + myDate); if (myDate.getTime() != expLittleD.getTime()) { - errln("FAIL: Expected " + expLittleD + " got " + myDate); + fail("FAIL: Expected " + expLittleD + " got " + myDate); } } // Test the 'G' day of year pattern @SuppressWarnings("deprecation") + @Test public void TestDayOfYearPattern195() { Date today = new Date(); Date expected = new Date(today.getYear(), today.getMonth(), today.getDate()); - logln("Test Date: " + today); + System.out.println("Test Date: " + today); SimpleDateFormat sdf = (SimpleDateFormat)SimpleDateFormat.getDateInstance(); @@ -496,29 +507,30 @@ void tryPattern(SimpleDateFormat sdf, Date d, String pattern, Date expected) if (pattern != null) { sdf.applyPattern(pattern); } - logln("pattern: " + sdf.toPattern()); + System.out.println("pattern: " + sdf.toPattern()); String formatResult = sdf.format(d); - logln(" format -> " + formatResult); + System.out.println(" format -> " + formatResult); try { Date d2 = sdf.parse(formatResult); - logln(" parse(" + formatResult + ") -> " + d2); + System.out.println(" parse(" + formatResult + ") -> " + d2); if (d2.getTime() != expected.getTime()) { - errln("FAIL: Expected " + expected); + fail("FAIL: Expected " + expected); } String format2 = sdf.format(d2); - logln(" format -> " + format2); + System.out.println(" format -> " + format2); if (!formatResult.equals(format2)) { - errln("FAIL: Round trip drift"); + fail("FAIL: Round trip drift"); } } catch(Exception e) { - errln("Error: " + e.getMessage()); + fail("Error: " + e.getMessage()); } } // Test a pattern with single quotes @SuppressWarnings("deprecation") + @Test public void TestQuotePattern161() { // This pattern used to end in " zzz" but that makes this test zone-dependent @@ -526,9 +538,9 @@ public void TestQuotePattern161() Date currentTime_1 = new Date(97, Calendar.AUGUST, 13, 10, 42, 28); String dateString = formatter.format(currentTime_1); String exp = "08/13/1997 at 10:42:28 AM "; - logln("format(" + currentTime_1 + ") = " + dateString); + System.out.println("format(" + currentTime_1 + ") = " + dateString); if (!dateString.regionMatches(0, exp, 0, exp.length())) { - errln("FAIL: Expected " + exp); + fail("FAIL: Expected " + exp); } } @@ -540,6 +552,7 @@ public void TestQuotePattern161() * 1 line that should be correct is off by 100 years. (In this day * and age, no one would assume that 1/1/00 is Jan 1 1900.) **/ + @Test public void TestBadInput135() { int looks[] = { DateFormat.SHORT, DateFormat.MEDIUM, @@ -560,22 +573,22 @@ public void TestBadInput135() try { Date when = df.parse(text); if ( when == null ){ - errln(prefix + + fail(prefix + "SHOULD NOT HAPPEN: parse returned null."); continue; } String format = full.format(when); - logln(prefix + "OK: " + format); + System.out.println(prefix + "OK: " + format); // Only match the start -- not the zone, which could vary if (!format.regionMatches(0, expected, 0, expected.length())) { - errln("FAIL: Expected " + expected); + fail("FAIL: Expected " + expected); } } catch ( ParseException e ){ //errln(prefix + e); // This is expected. } catch ( StringIndexOutOfBoundsException e ){ - errln(prefix + "SHOULD NOT HAPPEN: " + e); + fail(prefix + "SHOULD NOT HAPPEN: " + e); } } } @@ -610,6 +623,7 @@ public void TestBadInput135() }; // More testing of the parsing of bad input @SuppressWarnings("UnusedAssignment") + @Test public void TestBadInput135a() { SimpleDateFormat dateParse = new SimpleDateFormat(); @@ -620,12 +634,12 @@ public void TestBadInput135a() dateParse.applyPattern("d MMMM, yyyy"); dateParse.setTimeZone(TimeZone.getDefault()); s = "not parseable"; - logln("Trying to parse \"" + s + "\" with " + dateParse.toPattern()); + System.out.println("Trying to parse \"" + s + "\" with " + dateParse.toPattern()); try { date = dateParse.parse(s); - errln("FAIL: Expected exception during parse"); + fail("FAIL: Expected exception during parse"); } catch (Exception ex) { - logln("Exception during parse: " + ex); // This is expected + System.out.println("Exception during parse: " + ex); // This is expected } for (int i=0; i " + d.toString()); if (d.getTime() != expected.getTime()) { - errln("FAIL: Expected " + expected); + fail("FAIL: Expected " + expected); } } catch (ParseException e) { - errln("FAIL: Got exception"); + fail("FAIL: Got exception"); } } // Test behavior of DateFormat with applied time zone + @Test public void TestDateFormatZone061() { Date date; @@ -732,28 +748,29 @@ public void TestDateFormatZone061() // 25-Mar-97 00:00:00 GMT date = new Date( 859248000000L ); - logln( "Date 1997/3/25 00:00 GMT: " + date ); + System.out.println( "Date 1997/3/25 00:00 GMT: " + date ); formatter = new SimpleDateFormat("dd-MMM-yyyyy HH:mm", Locale.UK); formatter.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); String temp = formatter.format( date ); - logln( "Formatted in GMT to: " + temp ); + System.out.println( "Formatted in GMT to: " + temp ); /* Parse date string */ try { Date tempDate = formatter.parse( temp ); - logln( "Parsed to: " + tempDate ); + System.out.println( "Parsed to: " + tempDate ); if (tempDate.getTime() != date.getTime()) { - errln("FAIL: Expected " + date); + fail("FAIL: Expected " + date); } } catch( Throwable t ) { - errln( "Date Formatter throws: " + + fail( "Date Formatter throws: " + t.toString() ); } } // Make sure DateFormat uses the correct zone. + @Test public void TestDateFormatZone146() { TimeZone saveDefault = TimeZone.getDefault(); @@ -767,9 +784,9 @@ public void TestDateFormatZone146() TimeZone testdefault = TimeZone.getDefault(); String testtimezone = testdefault.getID(); if (testtimezone.equals("GMT")) { - logln("Test timezone = " + testtimezone); + System.out.println("Test timezone = " + testtimezone); } else { - errln("Test timezone should be GMT, not " + testtimezone); + fail("Test timezone should be GMT, not " + testtimezone); } // now try to use the default GMT time zone @@ -799,9 +816,9 @@ public void TestDateFormatZone146() DateFormat fmt = new SimpleDateFormat(DATA[i+2], Locale.ENGLISH); fmt.setCalendar(greenwichcalendar); String result = fmt.format(greenwichdate); - logln(DATA[i] + result); + System.out.println(DATA[i] + result); if (!result.equals(DATA[i+1])) { - errln("FAIL: Expected " + DATA[i+1] + fail("FAIL: Expected " + DATA[i+1] + ", got " + result); } } @@ -812,6 +829,7 @@ public void TestDateFormatZone146() } /* HS : Commented out for now, need to be changed not to use hardcoded results. + @Test public void TestLocaleDateFormat() // Bug 495 { Date testDate = new Date (97, Calendar.SEPTEMBER, 15); @@ -821,13 +839,13 @@ public void TestLocaleDateFormat() // Bug 495 DateFormat.FULL, Locale.US); String expectedFRENCH = "lundi 15 septembre 1997 00 h 00 GMT-07:00"; String expectedUS = "Monday, September 15, 1997 12:00:00 o'clock AM PDT"; - logln("Date set to : " + testDate); + System.out.println("Date set to : " + testDate); String out = dfFrench.format(testDate); - logln("Date Formated with French Locale " + out); - if (!out.equals(expectedFRENCH)) errln("FAIL: Expected " + expectedFRENCH); + System.out.println("Date Formated with French Locale " + out); + if (!out.equals(expectedFRENCH)) fail("FAIL: Expected " + expectedFRENCH); out = dfUS.format(testDate); - logln("Date Formated with US Locale " + out); - if (!out.equals(expectedUS)) errln("FAIL: Expected " + expectedUS); + System.out.println("Date Formated with US Locale " + out); + if (!out.equals(expectedUS)) fail("FAIL: Expected " + expectedUS); } */ /** @@ -835,13 +853,14 @@ public void TestLocaleDateFormat() // Bug 495 */ /* test commented out pending API-change approval + @Test public void Test2YearStartDate() throws ParseException { // create a SimpleDateFormat to test with; dump out if it's not a SimpleDateFormat DateFormat test = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US); if (!(test instanceof SimpleDateFormat)) { - errln("DateFormat.getInstance() didn't return an instance of SimpleDateFormat!"); + fail("DateFormat.getInstance() didn't return an instance of SimpleDateFormat!"); return; } @@ -861,7 +880,7 @@ public void Test2YearStartDate() throws ParseException cal.setTime(date); if (cal.get(Calendar.YEAR) != 1900 || cal.get(Calendar.MONTH) != 0 || cal.get(Calendar.DATE) != 1) - errln("SimpleDateFormat.get2DigitStartDate() returned " + (cal.get(Calendar.MONTH) + fail("SimpleDateFormat.get2DigitStartDate() returned " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + "/" + cal.get(Calendar.YEAR) + " instead of 1/1/1900."); @@ -869,19 +888,19 @@ public void Test2YearStartDate() throws ParseException date = sdf.parse(testString1); cal.setTime(date); if (cal.get(Calendar.YEAR) != 1967) - errln("Parsing \"3/10/67\" with 2-digit start date set to 1/1/1900 yielded a year of " + fail("Parsing \"3/10/67\" with 2-digit start date set to 1/1/1900 yielded a year of " + cal.get(Calendar.YEAR) + " instead of 1967."); if (cal.get(Calendar.MONTH) != 2 || cal.get(Calendar.DATE) != 10) - errln("Parsing \"3/10/67\" with 2-digit start date set to 1/1/1900 failed: got " + + fail("Parsing \"3/10/67\" with 2-digit start date set to 1/1/1900 failed: got " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + " instead of 3/10."); date = sdf.parse(testString2); cal.setTime(date); if (cal.get(Calendar.YEAR) != 1943) - errln("Parsing \"3/16/43\" with 2-digit start date set to 1/1/1900 yielded a year of " + fail("Parsing \"3/16/43\" with 2-digit start date set to 1/1/1900 yielded a year of " + cal.get(Calendar.YEAR) + " instead of 1943."); if (cal.get(Calendar.MONTH) != 2 || cal.get(Calendar.DATE) != 16) - errln("Parsing \"3/16/43\" with 2-digit start date set to 1/1/1900 failed: got " + + fail("Parsing \"3/16/43\" with 2-digit start date set to 1/1/1900 failed: got " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + " instead of 3/16."); @@ -891,19 +910,19 @@ public void Test2YearStartDate() throws ParseException date = sdf.parse(testString1); cal.setTime(date); if (cal.get(Calendar.YEAR) != 2067) - errln("Parsing \"3/10/67\" with 2-digit start date set to 1/1/2000 yielded a year of " + fail("Parsing \"3/10/67\" with 2-digit start date set to 1/1/2000 yielded a year of " + cal.get(Calendar.YEAR) + " instead of 2067."); if (cal.get(Calendar.MONTH) != 2 || cal.get(Calendar.DATE) != 10) - errln("Parsing \"3/10/67\" with 2-digit start date set to 1/1/2000 failed: got " + + fail("Parsing \"3/10/67\" with 2-digit start date set to 1/1/2000 failed: got " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + " instead of 3/10."); date = sdf.parse(testString2); cal.setTime(date); if (cal.get(Calendar.YEAR) != 2043) - errln("Parsing \"3/16/43\" with 2-digit start date set to 1/1/2000 yielded a year of " + fail("Parsing \"3/16/43\" with 2-digit start date set to 1/1/2000 yielded a year of " + cal.get(Calendar.YEAR) + " instead of 1943."); if (cal.get(Calendar.MONTH) != 2 || cal.get(Calendar.DATE) != 16) - errln("Parsing \"3/16/43\" with 2-digit start date set to 1/1/2000 failed: got " + + fail("Parsing \"3/16/43\" with 2-digit start date set to 1/1/2000 failed: got " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + " instead of 3/16."); @@ -913,19 +932,19 @@ public void Test2YearStartDate() throws ParseException date = sdf.parse(testString1); cal.setTime(date); if (cal.get(Calendar.YEAR) != 1967) - errln("Parsing \"3/10/67\" with 2-digit start date set to 1/1/1950 yielded a year of " + fail("Parsing \"3/10/67\" with 2-digit start date set to 1/1/1950 yielded a year of " + cal.get(Calendar.YEAR) + " instead of 1967."); if (cal.get(Calendar.MONTH) != 2 || cal.get(Calendar.DATE) != 10) - errln("Parsing \"3/10/67\" with 2-digit start date set to 1/1/1950 failed: got " + + fail("Parsing \"3/10/67\" with 2-digit start date set to 1/1/1950 failed: got " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + " instead of 3/10."); date = sdf.parse(testString2); cal.setTime(date); if (cal.get(Calendar.YEAR) != 2043) - errln("Parsing \"3/16/43\" with 2-digit start date set to 1/1/1950 yielded a year of " + fail("Parsing \"3/16/43\" with 2-digit start date set to 1/1/1950 yielded a year of " + cal.get(Calendar.YEAR) + " instead of 1943."); if (cal.get(Calendar.MONTH) != 2 || cal.get(Calendar.DATE) != 16) - errln("Parsing \"3/16/43\" with 2-digit start date set to 1/1/1950 failed: got " + + fail("Parsing \"3/16/43\" with 2-digit start date set to 1/1/1950 failed: got " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + " instead of 3/16."); @@ -935,19 +954,19 @@ public void Test2YearStartDate() throws ParseException date = sdf.parse(testString2); cal.setTime(date); if (cal.get(Calendar.YEAR) != 2043) - errln("Parsing \"3/16/43\" with 2-digit start date set to 6/1/1943 yielded a year of " + fail("Parsing \"3/16/43\" with 2-digit start date set to 6/1/1943 yielded a year of " + cal.get(Calendar.YEAR) + " instead of 2043."); if (cal.get(Calendar.MONTH) != 2 || cal.get(Calendar.DATE) != 16) - errln("Parsing \"3/16/43\" with 2-digit start date set to 6/1/1943 failed: got " + + fail("Parsing \"3/16/43\" with 2-digit start date set to 6/1/1943 failed: got " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + " instead of 3/16."); date = sdf.parse(testString3); cal.setTime(date); if (cal.get(Calendar.YEAR) != 1943) - errln("Parsing \"7/21/43\" with 2-digit start date set to 6/1/1943 yielded a year of " + fail("Parsing \"7/21/43\" with 2-digit start date set to 6/1/1943 yielded a year of " + cal.get(Calendar.YEAR) + " instead of 1943."); if (cal.get(Calendar.MONTH) != 6 || cal.get(Calendar.DATE) != 21) - errln("Parsing \"7/21/43\" with 2-digit start date set to 6/1/1943 failed: got " + + fail("Parsing \"7/21/43\" with 2-digit start date set to 6/1/1943 failed: got " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + " instead of 7/21."); @@ -957,7 +976,7 @@ public void Test2YearStartDate() throws ParseException cal.setTime(date); if (cal.get(Calendar.YEAR) != 1943 || cal.get(Calendar.MONTH) != 5 || cal.get(Calendar.DATE) != 1) - errln("SimpleDateFormat.get2DigitStartDate() returned " + (cal.get(Calendar.MONTH) + fail("SimpleDateFormat.get2DigitStartDate() returned " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + "/" + cal.get(Calendar.YEAR) + " instead of 6/1/1943."); } @@ -967,6 +986,7 @@ public void Test2YearStartDate() throws ParseException * ParsePosition.errorIndex tests. */ @SuppressWarnings("deprecation") + @Test public void Test4052223() { String str = "7/SOS/2001"; @@ -975,17 +995,18 @@ public void Test4052223() SimpleDateFormat sdf = new SimpleDateFormat(pat); ParsePosition pos = new ParsePosition(0); Date d = sdf.parse(str, pos); - logln(str + " parses with " + pat + " to " + d); + System.out.println(str + " parses with " + pat + " to " + d); if (d == null && pos.getErrorIndex() == 2) { - logln("Expected null returned, failed at : " + pos.getErrorIndex()); + System.out.println("Expected null returned, failed at : " + pos.getErrorIndex()); } else { - errln("Failed, parse " + str + " got : " + d + ", index=" + pos.getErrorIndex()); + fail("Failed, parse " + str + " got : " + d + ", index=" + pos.getErrorIndex()); } } /** * Bug4469904 -- th_TH date format doesn't use Thai B.E. */ + @Test public void TestBuddhistEraBugId4469904() { String era = "\u0e1e.\u0e28."; Locale loc = new Locale("th", "TH"); @@ -996,7 +1017,7 @@ public void TestBuddhistEraBugId4469904() { String output = df.format(date); int index = output.indexOf(era); if (index == -1) { - errln("Test4469904: Failed. Buddhist Era abbrev not present."); + fail("Test4469904: Failed. Buddhist Era abbrev not present."); } } @@ -1004,6 +1025,7 @@ public void TestBuddhistEraBugId4469904() { * 4326988: API: SimpleDateFormat throws NullPointerException when parsing with null pattern */ @SuppressWarnings("UnusedAssignment") + @Test public void Test4326988() { String[] wrongPatterns = { "hh o''clock", @@ -1021,28 +1043,28 @@ public void Test4326988() { // Check NullPointerException try { SimpleDateFormat fmt = new SimpleDateFormat(null); - errln("SimpleDateFormat() doesn't throw NPE with null pattern"); + fail("SimpleDateFormat() doesn't throw NPE with null pattern"); } catch (NullPointerException e) { // Okay } try { Locale loc = null; SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd", loc); - errln("SimpleDateFormat() doesn't throw NPE with null locale"); + fail("SimpleDateFormat() doesn't throw NPE with null locale"); } catch (NullPointerException e) { // Okay } try { DateFormatSymbols symbols = null; SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd", symbols); - errln("SimpleDateFormat() doesn't throw NPE with null DateFormatSymbols"); + fail("SimpleDateFormat() doesn't throw NPE with null DateFormatSymbols"); } catch (NullPointerException e) { // Okay } try { SimpleDateFormat fmt = new SimpleDateFormat(); fmt.applyPattern(null); - errln("applyPattern() doesn't throw NPE with null pattern"); + fail("applyPattern() doesn't throw NPE with null pattern"); } catch (NullPointerException e) { // Okay } @@ -1051,7 +1073,7 @@ public void Test4326988() { for (int i = 0; i < wrongPatterns.length; i++) { try { SimpleDateFormat fmt = new SimpleDateFormat(wrongPatterns[i]); - errln("SimpleDateFormat(\"" + wrongPatterns[i] + "\")" + + fail("SimpleDateFormat(\"" + wrongPatterns[i] + "\")" + " doesn't throw an IllegalArgumentException"); } catch (IllegalArgumentException e) { // Okay @@ -1059,7 +1081,7 @@ public void Test4326988() { try { SimpleDateFormat fmt = new SimpleDateFormat(wrongPatterns[i], DateFormatSymbols.getInstance()); - errln("SimpleDateFormat(\"" + wrongPatterns[i] + "\", DateFormatSymbols) doesn't " + + fail("SimpleDateFormat(\"" + wrongPatterns[i] + "\", DateFormatSymbols) doesn't " + "throw an IllegalArgumentException"); } catch (IllegalArgumentException e) { // Okay @@ -1067,7 +1089,7 @@ public void Test4326988() { try { SimpleDateFormat fmt = new SimpleDateFormat(wrongPatterns[i], Locale.US); - errln("SimpleDateFormat(\"" + wrongPatterns[i] + + fail("SimpleDateFormat(\"" + wrongPatterns[i] + "\", Locale) doesn't throw an IllegalArgumentException"); } catch (IllegalArgumentException e) { // Okay @@ -1075,7 +1097,7 @@ public void Test4326988() { try { SimpleDateFormat fmt = new SimpleDateFormat(); fmt.applyPattern(wrongPatterns[i]); - errln("SimpleDateFormat.applyPattern(\"" + wrongPatterns[i] + + fail("SimpleDateFormat.applyPattern(\"" + wrongPatterns[i] + "\") doesn't throw an IllegalArgumentException"); } catch (IllegalArgumentException e) { // Okay @@ -1100,6 +1122,7 @@ public void Test4326988() { * Another round trip test */ @SuppressWarnings("deprecation") + @Test public void Test4486735() throws Exception { TimeZone initialTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); @@ -1109,7 +1132,7 @@ public void Test4486735() throws Exception { // Round to minutes. Some FULL formats don't have seconds. long time = System.currentTimeMillis()/60000 * 60000; Date date = new Date(time); - logln("the test date: " + date); + System.out.println("the test date: " + date); try { for (int z = 0; z < zones.length; z++) { @@ -1120,7 +1143,7 @@ public void Test4486735() throws Exception { DateFormat.FULL, loc); String s = df.format(date); - logln(s); + System.out.println(s); Date parsedDate = df.parse(s); long parsedTime = parsedDate.getTime(); if (time != parsedTime) { @@ -1133,7 +1156,7 @@ public void Test4486735() throws Exception { continue; } } - errln("round trip conversion failed: timezone="+zones[z]+ + fail("round trip conversion failed: timezone="+zones[z]+ ", locale=" + loc + ", expected=" + time + ", got=" + parsedTime); } @@ -1191,13 +1214,13 @@ public void Test4486735() throws Exception { SimpleDateFormat sdf = new SimpleDateFormat(pat); String s = sdf.format(new Date(2001-1900, Calendar.JANUARY, 1)); if (!expected.equals(s)) { - errln("wrong format result: expected="+expected+", got="+s); + fail("wrong format result: expected="+expected+", got="+s); } Date longday = sdf.parse(s); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(longday); if (cal.get(YEAR) != 2001) { - errln("wrong parse result: expected=2001, got=" + cal.get(YEAR)); + fail("wrong parse result: expected=2001, got=" + cal.get(YEAR)); } } catch (Exception e) { throw e; @@ -1207,6 +1230,7 @@ public void Test4486735() throws Exception { } } + @Test public void Test8216969() throws Exception { Locale locale = new Locale("ru"); String format = "\u0434\u0435\u043a"; diff --git a/test/jdk/java/text/Format/DateFormat/IntlTestDateFormat.java b/test/jdk/java/text/Format/DateFormat/IntlTestDateFormat.java index bc37d4f7fba..ebac773bd7e 100644 --- a/test/jdk/java/text/Format/DateFormat/IntlTestDateFormat.java +++ b/test/jdk/java/text/Format/DateFormat/IntlTestDateFormat.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,8 +25,7 @@ * @test * @summary test International Date Format * @bug 8008577 - * @library /java/text/testlib - * @run main/othervm -Djava.locale.providers=COMPAT,SPI IntlTestDateFormat + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI IntlTestDateFormat * @key randomness */ /* @@ -44,7 +43,11 @@ import java.text.*; import java.util.*; -public class IntlTestDateFormat extends IntlTest { +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class IntlTestDateFormat { // Values in milliseconds (== Date) private static final long ONESECOND = 1000; private static final long ONEMINUTE = 60 * ONESECOND; @@ -62,10 +65,7 @@ public class IntlTestDateFormat extends IntlTest { private String fTestName = new String("getInstance"); private int fLimit = 3; // How many iterations it should take to reach convergence - public static void main(String[] args) throws Exception { - new IntlTestDateFormat().run(args); - } - + @Test public void TestLocale() { localeTest(Locale.getDefault(), "Default Locale"); } @@ -85,7 +85,7 @@ public void localeTest(final Locale locale, final String localeName) { fFormat = DateFormat.getTimeInstance(timeStyle, locale); } catch(StringIndexOutOfBoundsException e) { - errln("FAIL: localeTest time getTimeInstance exception"); + fail("FAIL: localeTest time getTimeInstance exception"); throw e; } TestFormat(); @@ -99,7 +99,7 @@ public void localeTest(final Locale locale, final String localeName) { fFormat = DateFormat.getDateInstance(dateStyle, locale); } catch(StringIndexOutOfBoundsException e) { - errln("FAIL: localeTest date getTimeInstance exception"); + fail("FAIL: localeTest date getTimeInstance exception"); throw e; } TestFormat(); @@ -112,7 +112,7 @@ public void localeTest(final Locale locale, final String localeName) { fFormat = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale); } catch(StringIndexOutOfBoundsException e) { - errln("FAIL: localeTest date/time getDateTimeInstance exception"); + fail("FAIL: localeTest date/time getDateTimeInstance exception"); throw e; } TestFormat(); @@ -120,9 +120,10 @@ public void localeTest(final Locale locale, final String localeName) { } } + @Test public void TestFormat() { if (fFormat == null) { - errln("FAIL: DateFormat creation failed"); + fail("FAIL: DateFormat creation failed"); return; } // logln("TestFormat: " + fTestName); @@ -142,13 +143,13 @@ public void TestFormat() { private void describeTest() { if (fFormat == null) { - errln("FAIL: no DateFormat"); + fail("FAIL: no DateFormat"); return; } // Assume it's a SimpleDateFormat and get some info SimpleDateFormat s = (SimpleDateFormat) fFormat; - logln(fTestName + " Pattern " + s.toPattern()); + System.out.println(fTestName + " Pattern " + s.toPattern()); } private void tryDate(Date theDate) { @@ -169,7 +170,7 @@ private void tryDate(Date theDate) { } catch (ParseException e) { describeTest(); - errln("********** FAIL: Parse of " + string[i-1] + " failed."); + fail("********** FAIL: Parse of " + string[i-1] + " failed."); dump = true; break; } @@ -180,14 +181,14 @@ private void tryDate(Date theDate) { if (dateMatch == 0 && date[i] == date[i-1]) dateMatch = i; else if (dateMatch > 0 && date[i] != date[i-1]) { describeTest(); - errln("********** FAIL: Date mismatch after match."); + fail("********** FAIL: Date mismatch after match."); dump = true; break; } if (stringMatch == 0 && string[i] == string[i-1]) stringMatch = i; else if (stringMatch > 0 && string[i] != string[i-1]) { describeTest(); - errln("********** FAIL: String mismatch after match."); + fail("********** FAIL: String mismatch after match."); dump = true; break; } @@ -198,13 +199,13 @@ else if (stringMatch > 0 && string[i] != string[i-1]) { if (stringMatch > fLimit || dateMatch > fLimit) { describeTest(); - errln("********** FAIL: No string and/or date match within " + fLimit + " iterations."); + fail("********** FAIL: No string and/or date match within " + fLimit + " iterations."); dump = true; } if (dump) { for (int k=0; k<=i; ++k) { - logln("" + k + ": " + date[k] + " F> " + string[k] + " P> "); + System.out.println("" + k + ": " + date[k] + " F> " + string[k] + " P> "); } } } @@ -235,34 +236,36 @@ private double randDouble() { return rand.nextDouble(); } + @Test public void TestAvailableLocales() { final Locale[] locales = DateFormat.getAvailableLocales(); long count = locales.length; - logln("" + count + " available locales"); + System.out.println("" + count + " available locales"); if (locales != null && count != 0) { StringBuffer all = new StringBuffer(); for (int i=0; i subsitution failed. result = " + tempBuffer.toString()); - logln("Formatted with extra params : " + tempBuffer); + fail("Formatted with arguments > subsitution failed. result = " + tempBuffer.toString()); + System.out.println("Formatted with extra params : " + tempBuffer); //This statement gives an exception while formatting... //If we use pattern[1] for the message with param, //we get an NullPointerException in MessageFormat.java(617) @@ -103,28 +104,30 @@ public void Test4074764() { //in applyPattern() when the pattern does not //contain any param. } catch (Exception foo) { - errln("Exception when formatting with no params."); + fail("Exception when formatting with no params."); } } /* @bug 4058973 * MessageFormat.toPattern has weird rounding behavior. */ + @Test public void Test4058973() { MessageFormat fmt = new MessageFormat("{0,choice,0#no files|1#one file|1< {0,number,integer} files}"); String pat = fmt.toPattern(); if (!pat.equals("{0,choice,0.0#no files|1.0#one file|1.0< {0,number,integer} files}")) { - errln("MessageFormat.toPattern failed"); + fail("MessageFormat.toPattern failed"); } } /* @bug 4031438 * More robust message formats. */ + @Test public void Test4031438() { Locale locale = Locale.getDefault(); if (!TestUtils.usesAsciiDigits(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -134,91 +137,94 @@ public void Test4031438() { MessageFormat messageFormatter = new MessageFormat(""); try { - logln("Apply with pattern : " + pattern1); + System.out.println("Apply with pattern : " + pattern1); messageFormatter.applyPattern(pattern1); Object[] params = {7}; String tempBuffer = messageFormatter.format(params); if (!tempBuffer.equals("Impossible {1} has occurred -- status code is 7 and message is {2}.")) - errln("Tests arguments < substitution failed. Formatted text=" + + fail("Tests arguments < substitution failed. Formatted text=" + "<" + tempBuffer + ">"); - logln("Formatted with 7 : " + tempBuffer); + System.out.println("Formatted with 7 : " + tempBuffer); ParsePosition status = new ParsePosition(0); Object[] objs = messageFormatter.parse(tempBuffer, status); if (objs[params.length] != null) - errln("Parse failed with more than expected arguments"); + fail("Parse failed with more than expected arguments"); for (int i = 0; i < objs.length; i++) { if (objs[i] != null && !objs[i].toString().equals(params[i].toString())) { - errln("Parse failed on object " + objs[i] + " at index : " + i); + fail("Parse failed on object " + objs[i] + " at index : " + i); } } tempBuffer = messageFormatter.format(null); if (!tempBuffer.equals("Impossible {1} has occurred -- status code is {0} and message is {2}.")) - errln("Tests with no arguments failed"); - logln("Formatted with null : " + tempBuffer); - logln("Apply with pattern : " + pattern2); + fail("Tests with no arguments failed"); + System.out.println("Formatted with null : " + tempBuffer); + System.out.println("Apply with pattern : " + pattern2); messageFormatter.applyPattern(pattern2); tempBuffer = messageFormatter.format(params); if (!tempBuffer.equals("Double ' Quotes 7 test and quoted {1} test plus other {2} stuff.")) - errln("quote format test (w/ params) failed."); - logln("Formatted with params : " + tempBuffer); + fail("quote format test (w/ params) failed."); + System.out.println("Formatted with params : " + tempBuffer); tempBuffer = messageFormatter.format(null); if (!tempBuffer.equals("Double ' Quotes {0} test and quoted {1} test plus other {2} stuff.")) - errln("quote format test (w/ null) failed."); - logln("Formatted with null : " + tempBuffer); - logln("toPattern : " + messageFormatter.toPattern()); + fail("quote format test (w/ null) failed."); + System.out.println("Formatted with null : " + tempBuffer); + System.out.println("toPattern : " + messageFormatter.toPattern()); } catch (Exception foo) { - errln("Exception when formatting in bug 4031438. "+foo.getMessage()); + fail("Exception when formatting in bug 4031438. "+foo.getMessage()); } } + @Test public void Test4052223() { ParsePosition pos = new ParsePosition(0); if (pos.getErrorIndex() != -1) { - errln("ParsePosition.getErrorIndex initialization failed."); + fail("ParsePosition.getErrorIndex initialization failed."); } MessageFormat fmt = new MessageFormat("There are {0} apples growing on the {1} tree."); String str = new String("There is one apple growing on the peach tree."); Object[] objs = fmt.parse(str, pos); - logln("unparsable string , should fail at " + pos.getErrorIndex()); + System.out.println("unparsable string , should fail at " + pos.getErrorIndex()); if (pos.getErrorIndex() == -1) - errln("Bug 4052223 failed : parsing string " + str); + fail("Bug 4052223 failed : parsing string " + str); pos.setErrorIndex(4); if (pos.getErrorIndex() != 4) - errln("setErrorIndex failed, got " + pos.getErrorIndex() + " instead of 4"); + fail("setErrorIndex failed, got " + pos.getErrorIndex() + " instead of 4"); ChoiceFormat f = new ChoiceFormat( "-1#are negative|0#are no or fraction|1#is one|1.0 " + + fail("Fail: Pattern \"" + DATA[i] + "\" x "+j+" -> " + out + "; want \"" + DATA[i+1+j] + '"'); } String pat = cf.toPattern(); String pat2 = new ChoiceFormat(pat).toPattern(); if (!pat.equals(pat2)) - errln("Fail: Pattern \"" + DATA[i] + "\" x toPattern -> \"" + pat + '"'); + fail("Fail: Pattern \"" + DATA[i] + "\" x toPattern -> \"" + pat + '"'); else - logln("Ok: Pattern \"" + DATA[i] + "\" x toPattern -> \"" + pat + '"'); + System.out.println("Ok: Pattern \"" + DATA[i] + "\" x toPattern -> \"" + pat + '"'); } catch (IllegalArgumentException e) { - errln("Fail: Pattern \"" + DATA[i] + "\" -> " + e); + fail("Fail: Pattern \"" + DATA[i] + "\" -> " + e); } } } @@ -587,17 +607,18 @@ public void TestChoicePatternQuote() { * MessageFormat.equals(null) throws a NullPointerException. The JLS states * that it should return false. */ + @Test public void Test4112104() { MessageFormat format = new MessageFormat(""); try { // This should NOT throw an exception if (format.equals(null)) { // It also should return false - errln("MessageFormat.equals(null) returns false"); + fail("MessageFormat.equals(null) returns false"); } } catch (NullPointerException e) { - errln("MessageFormat.equals(null) throws " + e); + fail("MessageFormat.equals(null) throws " + e); } } @@ -605,15 +626,17 @@ public void Test4112104() { * @bug 4169959 * MessageFormat does not format null objects. CANNOT REPRODUCE THIS BUG. */ + @Test public void Test4169959() { // This works - logln(MessageFormat.format( "This will {0}", "work")); + System.out.println(MessageFormat.format( "This will {0}", "work")); // This fails - logln(MessageFormat.format( "This will {0}", + System.out.println(MessageFormat.format( "This will {0}", new Object[]{ null } ) ); } + @Test public void test4232154() { boolean gotException = false; try { @@ -632,6 +655,7 @@ public void test4232154() { } } + @Test public void test4293229() { MessageFormat format = new MessageFormat("'''{'0}'' '''{0}'''"); Object[] args = { null }; @@ -647,6 +671,7 @@ public void test4293229() { * @bug 8187551 * test MessageFormat.setFormat() method to throw AIOOBE on invalid index. */ + @Test public void test8187551() { //invalid cases ("pattern", "invalid format element index") String[][] invalidCases = {{"The disk \"{1}\" contains {0}.", "2"}, diff --git a/test/jdk/java/text/Format/MessageFormat/MessageTest.java b/test/jdk/java/text/Format/MessageFormat/MessageTest.java index a7542689563..674ce1d3152 100644 --- a/test/jdk/java/text/Format/MessageFormat/MessageTest.java +++ b/test/jdk/java/text/Format/MessageFormat/MessageTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,8 +23,8 @@ /* * @test - * @library /java/text/testlib * @summary test MessageFormat + * @run junit MessageTest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -43,13 +43,14 @@ import java.io.*; import java.text.*; -public class MessageTest extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new MessageTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class MessageTest { + @Test public void TestMSGPatternTest() { Object[] testArgs = { 1D, 3456D, @@ -71,12 +72,12 @@ public void TestMSGPatternTest() { Locale save = Locale.getDefault(); try { Locale.setDefault(Locale.US); - logln(""); - logln( i + " Pat in: " + testCases[i]); + System.out.println(""); + System.out.println( i + " Pat in: " + testCases[i]); MessageFormat form = new MessageFormat(testCases[i]); - logln( i + " Pat out: " + form.toPattern()); + System.out.println( i + " Pat out: " + form.toPattern()); String result = form.format(testArgs); - logln( i + " Result: " + result); + System.out.println( i + " Result: " + result); Object[] values = form.parse(result); for (int j = 0; j < testArgs.length; ++j) { Object testArg = testArgs[j]; @@ -86,8 +87,8 @@ public void TestMSGPatternTest() { } if ((testArg == null && value != null) || (testArg != null && !testArg.equals(value))) { - logln( i + " " + j + " old: " + testArg); - logln( i + " " + j + " new: " + value); + System.out.println( i + " " + j + " old: " + testArg); + System.out.println( i + " " + j + " new: " + value); } } } diff --git a/test/jdk/java/text/Format/MessageFormat/bug4492719.java b/test/jdk/java/text/Format/MessageFormat/bug4492719.java index 6a1d2184ffe..3243b3c8ee2 100644 --- a/test/jdk/java/text/Format/MessageFormat/bug4492719.java +++ b/test/jdk/java/text/Format/MessageFormat/bug4492719.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,27 +25,35 @@ * @test * * @bug 4492719 - * @library /java/text/testlib * @summary Confirm that Message.parse() interprets time zone which uses "GMT+/-" format correctly and doesn't throw ParseException. + * @run junit/othervm bug4492719 */ import java.util.*; import java.text.*; -public class bug4492719 extends IntlTest { +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeAll; - public static void main(String[] args) throws Exception { +import static org.junit.jupiter.api.Assertions.fail; + +public class bug4492719 { + + // MessageFormat.parse() should be able to interpret a time zone + // that uses "GMT+/-". + @Test + public void testParse() throws Exception { Locale savedLocale = Locale.getDefault(); TimeZone savedTimeZone = TimeZone.getDefault(); MessageFormat mf; boolean err =false; String[] formats = { - "short", "medium", "long", "full" + "short", "medium", "long", "full" }; String[] timezones = { - "America/Los_Angeles", "GMT", "GMT+09:00", "GMT-8:00", - "GMT+123", "GMT-1234", "GMT+2", "GMT-13" + "America/Los_Angeles", "GMT", "GMT+09:00", "GMT-8:00", + "GMT+123", "GMT-1234", "GMT+2", "GMT-13" }; String text; @@ -58,14 +66,14 @@ public static void main(String[] args) throws Exception { for (int j = 0; j < formats.length; j++) { mf = new MessageFormat("{0,time," + formats[j] + "} - time"); text = MessageFormat.format("{0,time," + formats[j] + "} - time", - new Object [] { new Date(123456789012L)}); + new Object [] { new Date(123456789012L)}); Object[] objs = mf.parse(text); } } } catch (ParseException e) { err = true; System.err.println("Invalid ParseException occurred : " + - e.getMessage()); + e.getMessage()); System.err.println(" TimeZone=" + TimeZone.getDefault()); } finally { diff --git a/test/jdk/java/text/Format/NumberFormat/BigDecimalFormat.java b/test/jdk/java/text/Format/NumberFormat/BigDecimalFormat.java index 2803bc8228e..ddb713929b4 100644 --- a/test/jdk/java/text/Format/NumberFormat/BigDecimalFormat.java +++ b/test/jdk/java/text/Format/NumberFormat/BigDecimalFormat.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,8 +25,7 @@ * @test * @bug 4018937 8008577 * @summary Confirm that methods which are newly added to support BigDecimal and BigInteger work as expected. - * @library /java/text/testlib - * @run main/othervm -Djava.locale.providers=COMPAT,SPI BigDecimalFormat + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI BigDecimalFormat */ import java.math.BigDecimal; @@ -34,11 +33,11 @@ import java.text.*; import java.util.*; -public class BigDecimalFormat extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new BigDecimalFormat().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class BigDecimalFormat { static final String nonsep_int = "123456789012345678901234567890123456789012345678901234567890" + @@ -998,7 +997,7 @@ void test_Format_in_MessageFormat() { ; if (!expected.equals(mf.format(testArgs))) { - errln("Wrong format.\n got:\n" + mf.format(testArgs) + + fail("Wrong format.\n got:\n" + mf.format(testArgs) + " expected:\n" + expected); } } @@ -1014,7 +1013,7 @@ private void setDigits(NumberFormat nf, private void checkFormat(String orig, StringBuffer got, String expected, int multiplier) { if (!expected.equals(new String(got))) { - errln("Formatting... failed." + + fail("Formatting... failed." + "\n original: " + orig + "\n multiplier: " + multiplier + "\n formatted: " + got + @@ -1027,14 +1026,14 @@ private void checkFieldPosition(String orig, FieldPosition fp, int begin, int position; if ((position = fp.getBeginIndex()) != begin) { - errln("Formatting... wrong Begin index returned for " + + fail("Formatting... wrong Begin index returned for " + fp.getFieldAttribute() + "." + "\n original: " + orig + "\n got: " + position + "\n expected: " + begin + "\n"); } if ((position = fp.getEndIndex()) != end) { - errln("Formatting... wrong End index returned for " + + fail("Formatting... wrong End index returned for " + fp.getFieldAttribute() + "." + "\n original: " + orig + "\n got: " + position + diff --git a/test/jdk/java/text/Format/NumberFormat/BigDecimalParse.java b/test/jdk/java/text/Format/NumberFormat/BigDecimalParse.java index 972cfa2851f..c878165c5ba 100644 --- a/test/jdk/java/text/Format/NumberFormat/BigDecimalParse.java +++ b/test/jdk/java/text/Format/NumberFormat/BigDecimalParse.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,27 +25,27 @@ * @test * @bug 4018937 8008577 * @summary Confirm that methods which are newly added to support BigDecimal and BigInteger work as expected. - * @library /java/text/testlib - * @run main/othervm -Djava.locale.providers=COMPAT,SPI BigDecimalParse + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI BigDecimalParse */ import java.math.BigDecimal; import java.text.*; import java.util.*; -public class BigDecimalParse extends IntlTest { +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeAll; - public static void main(String[] args) throws Exception { - Locale loc = Locale.getDefault(); - try { - Locale.setDefault(Locale.US); - new BigDecimalParse().run(args); - } finally { - // restore the reserved locale - Locale.setDefault(loc); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class BigDecimalParse { + + // Change JVM default Locale + @BeforeAll + static void initAll() { + Locale.setDefault(Locale.US); } + static final String nonsep_int = "123456789012345678901234567890123456789012345678901234567890" + "123456789012345678901234567890123456789012345678901234567890" + @@ -108,7 +108,8 @@ public static void main(String[] args) throws Exception { /** * Test for normal big numbers which have the fraction part */ - void test_Parse_in_DecimalFormat_BigDecimal() { + @Test + public void test_Parse_in_DecimalFormat_BigDecimal() { df = new DecimalFormat(); df.setParseBigDecimal(true); @@ -150,7 +151,8 @@ void test_Parse_in_DecimalFormat_BigDecimal() { /** * Test for normal big numbers which have the fraction part with multiplier */ - void test_Parse_in_DecimalFormat_BigDecimal_usingMultiplier() { + @Test + public void test_Parse_in_DecimalFormat_BigDecimal_usingMultiplier() { df = new DecimalFormat(); df.setParseBigDecimal(true); @@ -192,7 +194,8 @@ void test_Parse_in_DecimalFormat_BigDecimal_usingMultiplier() { /** * Test for division by zero (BigDecimal) */ - void test_Parse_in_DecimalFormat_BigDecimal_DivisionByZero() { + @Test + public void test_Parse_in_DecimalFormat_BigDecimal_DivisionByZero() { df = new DecimalFormat(); df.setParseBigDecimal(true); df.setMultiplier(0); @@ -213,7 +216,8 @@ void test_Parse_in_DecimalFormat_BigDecimal_DivisionByZero() { /** * Test for division by zero (Double) */ - void test_Parse_in_DecimalFormat_Double_DivisionByZero() { + @Test + public void test_Parse_in_DecimalFormat_Double_DivisionByZero() { df = new DecimalFormat(); df.setParseBigDecimal(false); df.setMultiplier(0); @@ -250,7 +254,8 @@ void test_Parse_in_DecimalFormat_Double_DivisionByZero() { /** * Test for division by zero (Long) */ - void test_Parse_in_DecimalFormat_Long_DivisionByZero() { + @Test + public void test_Parse_in_DecimalFormat_Long_DivisionByZero() { df = new DecimalFormat(); df.setParseBigDecimal(false); df.setMultiplier(0); @@ -271,7 +276,8 @@ void test_Parse_in_DecimalFormat_Long_DivisionByZero() { /** * Test for normal big numbers which don't have the fraction part */ - void test_Parse_in_DecimalFormat_BigInteger() { + @Test + public void test_Parse_in_DecimalFormat_BigInteger() { df = new DecimalFormat(); df.setParseBigDecimal(true); @@ -296,7 +302,8 @@ void test_Parse_in_DecimalFormat_BigInteger() { * Test for normal big numbers which don't have the fraction part with * multiplier */ - void test_Parse_in_DecimalFormat_BigInteger_usingMultiplier() { + @Test + public void test_Parse_in_DecimalFormat_BigInteger_usingMultiplier() { df = new DecimalFormat(); df.setParseBigDecimal(true); @@ -337,7 +344,8 @@ void test_Parse_in_DecimalFormat_BigInteger_usingMultiplier() { * Double.POSITIVE_INFINITY * Double.NEGATIVE_INFINITY */ - void test_Parse_in_DecimalFormat_SpecialNumber() { + @Test + public void test_Parse_in_DecimalFormat_SpecialNumber() { df = new DecimalFormat(); df.setParseBigDecimal(true); @@ -378,7 +386,8 @@ void test_Parse_in_DecimalFormat_SpecialNumber() { /** * Test for special numbers */ - void test_Parse_in_DecimalFormat_Other() { + @Test + public void test_Parse_in_DecimalFormat_Other() { df = new DecimalFormat(); df.setParseBigDecimal(true); @@ -472,7 +481,8 @@ void test_Parse_in_DecimalFormat_Other() { /** * Test for MessageFormat: setParseIntegerOnly(false) */ - void test_Parse_in_MessageFormat_NotParseIntegerOnly() { + @Test + public void test_Parse_in_MessageFormat_NotParseIntegerOnly() { for (int i=0; i < patterns.length; i++) { pp = new ParsePosition(0); Object[] parsed = null; @@ -487,19 +497,19 @@ void test_Parse_in_MessageFormat_NotParseIntegerOnly() { parsed = mf.parse(from[i], pp); if (pp.getErrorIndex() != -1) { - errln("Case" + (i+1) + + fail("Case" + (i+1) + ": getErrorIndex() returns wrong value. expected:-1, got:"+ pp.getErrorIndex() + " for " + from[i]); } if (pp.getIndex() != parsePosition1[i]) { - errln("Case" + (i+1) + + fail("Case" + (i+1) + ": getIndex() returns wrong value. expected:" + parsePosition1[i] + ", got:"+ pp.getIndex() + " for " + from[i]); } } catch(Exception e) { - errln("Unexpected exception: " + e.getMessage()); + fail("Unexpected exception: " + e.getMessage()); } checkType(from[i], getType(new BigDecimal(expected1[i])), @@ -558,7 +568,8 @@ void test_Parse_in_MessageFormat_NotParseIntegerOnly() { /** * Test for MessageFormat: setParseIntegerOnly(true) */ - void test_Parse_in_MessageFormat_ParseIntegerOnly() { + @Test + public void test_Parse_in_MessageFormat_ParseIntegerOnly() { for (int i=0; i < patterns.length; i++) { pp = new ParsePosition(0); Object[] parsed = null; @@ -574,20 +585,20 @@ void test_Parse_in_MessageFormat_ParseIntegerOnly() { parsed = mf.parse(from[i], pp); if (pp.getErrorIndex() != parsePosition2[i][0]) { - errln("Case" + (i+1) + + fail("Case" + (i+1) + ": getErrorIndex() returns wrong value. expected:" + parsePosition2[i][0] + ", got:"+ pp.getErrorIndex() + " for " + from[i]); } if (pp.getIndex() != parsePosition2[i][1]) { - errln("Case" + (i+1) + + fail("Case" + (i+1) + ": getIndex() returns wrong value. expected:" + parsePosition2[i][1] + ", got:"+ pp.getIndex() + " for " + from[i]); } } catch(Exception e) { - errln("Unexpected exception: " + e.getMessage()); + fail("Unexpected exception: " + e.getMessage()); } if (parsePosition2[i][0] == -1) { @@ -624,7 +635,8 @@ void test_Parse_in_MessageFormat_ParseIntegerOnly() { /** * Test for DecimalFormat: setParseIntegerOnly(true) */ - void test_Parse_in_DecimalFormat_ParseIntegerOnly() { + @Test + public void test_Parse_in_DecimalFormat_ParseIntegerOnly() { DecimalFormat df = (DecimalFormat)NumberFormat.getIntegerInstance(); df.setParseBigDecimal(true); @@ -636,20 +648,20 @@ void test_Parse_in_DecimalFormat_ParseIntegerOnly() { parsed = df.parse(from3[i], pp); if (pp.getErrorIndex() != parsePosition3[i][0]) { - errln("Case" + (i+1) + + fail("Case" + (i+1) + ": getErrorIndex() returns wrong value. expected:" + parsePosition3[i][0] + ", got:"+ pp.getErrorIndex() + " for " + from3[i]); } if (pp.getIndex() != parsePosition3[i][1]) { - errln("Case" + (i+1) + + fail("Case" + (i+1) + ": getIndex() returns wrong value. expected:" + parsePosition3[i][1] + ", got:"+ pp.getIndex() + " for " + from3[i]); } } catch(Exception e) { - errln("Unexpected exception: " + e.getMessage()); + fail("Unexpected exception: " + e.getMessage()); } if (parsePosition3[i][0] == -1) { @@ -667,7 +679,7 @@ protected void check(String from, Number to) { } catch(Exception e) { exceptionOccurred = true; - errln(e.getMessage()); + fail(e.getMessage()); } if (!exceptionOccurred) { checkParse(from, to, parsed); @@ -678,7 +690,7 @@ protected void check(String from, Number to) { private void checkParse(String orig, Number expected, Number got) { if (!expected.equals(got)) { - errln("Parsing... failed." + + fail("Parsing... failed." + "\n original: " + orig + "\n parsed: " + got + "\n expected: " + expected + "\n"); @@ -687,7 +699,7 @@ private void checkParse(String orig, Number expected, Number got) { private void checkType(String orig, String expected, String got) { if (!expected.equals(got)) { - errln("Parsing... unexpected Class returned." + + fail("Parsing... unexpected Class returned." + "\n original: " + orig + "\n got: " + got + "\n expected: " + expected + "\n"); @@ -696,7 +708,7 @@ private void checkType(String orig, String expected, String got) { private void checkParsePosition(String orig, int expected, int got) { if (expected != got) { - errln("Parsing... wrong ParsePosition returned." + + fail("Parsing... wrong ParsePosition returned." + "\n original: " + orig + "\n got: " + got + "\n expected: " + expected + "\n"); diff --git a/test/jdk/java/text/Format/NumberFormat/Bug4838107.java b/test/jdk/java/text/Format/NumberFormat/Bug4838107.java index 8d6d2c25a62..e38642460a5 100644 --- a/test/jdk/java/text/Format/NumberFormat/Bug4838107.java +++ b/test/jdk/java/text/Format/NumberFormat/Bug4838107.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,6 @@ * @summary Confirm that DecimalFormat can format a number with a negative * exponent number correctly. Tests also involve using a DecimalFormat * with a custom pattern or a custom minus sign. - * @library /java/text/testlib * @run junit/othervm -Djava.locale.providers=COMPAT,SPI Bug4838107 */ @@ -40,6 +39,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -57,7 +57,7 @@ * parsing using the same DecimalFormat instance will not change the * Number's value anymore. */ -public class Bug4838107 extends IntlTest { +public class Bug4838107 { // Save JVM default Locale private static final Locale savedLocale = Locale.getDefault(); diff --git a/test/jdk/java/text/Format/NumberFormat/DFSExponential.java b/test/jdk/java/text/Format/NumberFormat/DFSExponential.java index 898fb3feccb..8ad22872ae8 100644 --- a/test/jdk/java/text/Format/NumberFormat/DFSExponential.java +++ b/test/jdk/java/text/Format/NumberFormat/DFSExponential.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,21 +24,21 @@ /** * @test * @bug 4068067 - * @library /java/text/testlib * @summary test NumberFormat with exponential separator symbols. It also tests the new * public methods in DecimalFormatSymbols, setExponentSeparator() and * getExponentSeparator() + * @run junit DFSExponential */ import java.util.*; import java.text.*; -public class DFSExponential extends IntlTest -{ +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; - public static void main(String[] args) throws Exception { - new DFSExponential().run(args); - } +public class DFSExponential +{ public void DFSExponenTest() throws Exception { @@ -55,30 +55,30 @@ public void DFSExponenTest() throws Exception { int ival = 0, ilval = 0; - logln("Default exponent separator: "+sym.getExponentSeparator()); + System.out.println("Default exponent separator: "+sym.getExponentSeparator()); try { sym.setExponentSeparator("x10^"); } catch (NullPointerException e){ - errln("null String was passed to set an exponent separator symbol"); + fail("null String was passed to set an exponent separator symbol"); throw new RuntimeException("Test Malfunction: null String was passed to set an exponent separator symbol" ); } - logln("Current exponent separator: "+sym.getExponentSeparator()); + System.out.println("Current exponent separator: "+sym.getExponentSeparator()); for (int p=0; p "+s); + System.out.println(" " + val[v]+" --> "+s); if(valFormat[p][v].equals(s)){ - logln(": Passed"); + System.out.println(": Passed"); }else{ - errln(" Failed: Should be formatted as "+valFormat[p][v]+ "but got "+s); + fail(" Failed: Should be formatted as "+valFormat[p][v]+ "but got "+s); throw new RuntimeException(" Failed: Should be formatted as "+valFormat[p][v]+ "but got "+s); } } diff --git a/test/jdk/java/text/Format/NumberFormat/DFSSerialization.java b/test/jdk/java/text/Format/NumberFormat/DFSSerialization.java index 78bd1389786..7e27a7ac265 100644 --- a/test/jdk/java/text/Format/NumberFormat/DFSSerialization.java +++ b/test/jdk/java/text/Format/NumberFormat/DFSSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,8 +25,8 @@ * @test * @bug 4068067 * @library /java/text/testlib - * @build DFSSerialization IntlTest HexDumpReader - * @run main DFSSerialization + * @build DFSSerialization HexDumpReader + * @run junit DFSSerialization * @summary Three different tests are done. * 1. read from the object created using jdk1.4.2 * 2. create a valid DecimalFormatSymbols object with current JDK, then read the object @@ -43,10 +43,11 @@ import java.text.DecimalFormatSymbols; import java.util.Locale; -public class DFSSerialization extends IntlTest{ - public static void main(String[] args) throws Exception { - new DFSSerialization().run(args); - } +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class DFSSerialization{ public void TestDFSSerialization(){ /* * 1. read from the object created using jdk1.4.2 @@ -56,9 +57,9 @@ public void TestDFSSerialization(){ if (dfs142 != null){ if (dfs142.getExponentSeparator().equals("E") && dfs142.getCurrencySymbol().equals("*SpecialCurrencySymbol*")){ System.out.println("\n Deserialization of JDK1.4.2 Object from the current JDK: Passed."); - logln(" Deserialization of JDK1.4.2 Object from the current JDK: Passed."); + System.out.println(" Deserialization of JDK1.4.2 Object from the current JDK: Passed."); } else { - errln(" Deserialization of JDK1.4.2 Object from the current JDK was Failed:" + fail(" Deserialization of JDK1.4.2 Object from the current JDK was Failed:" +dfs142.getCurrencySymbol()+" "+dfs142.getExponentSeparator()); /* * logically should not throw this exception as errln throws exception @@ -79,9 +80,9 @@ public void TestDFSSerialization(){ if (dfsValid.getExponentSeparator().equals("*SpecialExponentSeparator*") && dfsValid.getCurrencySymbol().equals("*SpecialCurrencySymbol*")){ System.out.println(" Deserialization of current JDK Object from the current JDK: Passed."); - logln(" Deserialization of current JDK Object from the current JDK: Passed."); + System.out.println(" Deserialization of current JDK Object from the current JDK: Passed."); } else { - errln(" Deserialization of current JDK Object from the current JDK was Failed:" + fail(" Deserialization of current JDK Object from the current JDK was Failed:" +dfsValid.getCurrencySymbol()+" "+dfsValid.getExponentSeparator()); /* * logically should not throw this exception as errln throws exception @@ -102,11 +103,11 @@ public void TestDFSSerialization(){ } catch (NullPointerException npe){ npePassed = true; System.out.println(" Trying to set exponent separator with null: Passed."); - logln(" Trying to set exponent separator with null: Passed."); + System.out.println(" Trying to set exponent separator with null: Passed."); } if (!npePassed){ System.out.println(" Trying to set exponent separator with null:Failed."); - errln(" Trying to set exponent separator with null:Failed."); + fail(" Trying to set exponent separator with null:Failed."); /* * logically should not throw this exception as errln throws exception * if not thrown yet - but in case errln got changed @@ -124,7 +125,7 @@ private DecimalFormatSymbols readTestObject(File inputFile){ DecimalFormatSymbols dfs = (DecimalFormatSymbols)p.readObject(); return dfs; } catch (Exception e) { - errln("Test Malfunction in DFSSerialization: Exception while reading the object"); + fail("Test Malfunction in DFSSerialization: Exception while reading the object"); /* * logically should not throw this exception as errln throws exception * if not thrown yet - but in case errln got changed @@ -137,8 +138,8 @@ private File createTestObject(String objectName, String expString){ DecimalFormatSymbols dfs= new DecimalFormatSymbols(); dfs.setExponentSeparator(expString); dfs.setCurrencySymbol("*SpecialCurrencySymbol*"); - logln(" The special exponent separator is set : " + dfs.getExponentSeparator()); - logln(" The special currency symbol is set : " + dfs.getCurrencySymbol()); + System.out.println(" The special exponent separator is set : " + dfs.getExponentSeparator()); + System.out.println(" The special currency symbol is set : " + dfs.getCurrencySymbol()); // 6345659: create a test object in the test.class dir where test user has a write permission. File file = new File(System.getProperty("test.class", "."), objectName); @@ -148,7 +149,7 @@ private File createTestObject(String objectName, String expString){ //System.out.println(" The special currency symbol is set : " + dfs.getCurrencySymbol()); return file; } catch (Exception e){ - errln("Test Malfunction in DFSSerialization: Exception while creating an object"); + fail("Test Malfunction in DFSSerialization: Exception while creating an object"); /* * logically should not throw this exception as errln throws exception * if not thrown yet - but in case errln got changed diff --git a/test/jdk/java/text/Format/NumberFormat/IntlTestDecimalFormatAPI.java b/test/jdk/java/text/Format/NumberFormat/IntlTestDecimalFormatAPI.java index fcda5b863b4..8234ae8a163 100644 --- a/test/jdk/java/text/Format/NumberFormat/IntlTestDecimalFormatAPI.java +++ b/test/jdk/java/text/Format/NumberFormat/IntlTestDecimalFormatAPI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,8 +23,8 @@ /* * @test - * @library /java/text/testlib * @summary test International Decimal Format API + * @run junit IntlTestDecimalFormatAPI */ /* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved @@ -41,23 +41,24 @@ import java.text.*; import java.util.*; -public class IntlTestDecimalFormatAPI extends IntlTest -{ - public static void main(String[] args) throws Exception { - new IntlTestDecimalFormatAPI().run(args); - } +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.fail; + +public class IntlTestDecimalFormatAPI +{ // This test checks various generic API methods in DecimalFormat to achieve 100% API coverage. + @Test public void TestAPI() { Locale reservedLocale = Locale.getDefault(); try { - logln("DecimalFormat API test---"); logln(""); + System.out.println("DecimalFormat API test---"); System.out.println(""); Locale.setDefault(Locale.ENGLISH); // ======= Test constructors - logln("Testing DecimalFormat constructors"); + System.out.println("Testing DecimalFormat constructors"); DecimalFormat def = new DecimalFormat(); @@ -67,7 +68,7 @@ public void TestAPI() pat = new DecimalFormat(pattern); } catch (IllegalArgumentException e) { - errln("ERROR: Could not create DecimalFormat (pattern)"); + fail("ERROR: Could not create DecimalFormat (pattern)"); } DecimalFormatSymbols symbols = @@ -77,16 +78,16 @@ public void TestAPI() // ======= Test clone(), assignment, and equality - logln("Testing clone() and equality operators"); + System.out.println("Testing clone() and equality operators"); Format clone = (Format) def.clone(); if( ! def.equals(clone)) { - errln("ERROR: Clone() failed"); + fail("ERROR: Clone() failed"); } // ======= Test various format() methods - logln("Testing various format() methods"); + System.out.println("Testing various format() methods"); // final double d = -10456.0037; // this appears as // -10456.003700000001 on NT @@ -94,7 +95,7 @@ public void TestAPI() // -1.0456003700000002E-4 on NT final double d = -10456.00370000000000; // this works! final long l = 100000000; - logln("" + d + " is the double value"); + System.out.println("" + d + " is the double value"); StringBuffer res1 = new StringBuffer(); StringBuffer res2 = new StringBuffer(); @@ -106,20 +107,20 @@ public void TestAPI() FieldPosition pos4 = new FieldPosition(0); res1 = def.format(d, res1, pos1); - logln("" + d + " formatted to " + res1); + System.out.println("" + d + " formatted to " + res1); res2 = pat.format(l, res2, pos2); - logln("" + l + " formatted to " + res2); + System.out.println("" + l + " formatted to " + res2); res3 = cust1.format(d, res3, pos3); - logln("" + d + " formatted to " + res3); + System.out.println("" + d + " formatted to " + res3); res4 = cust1.format(l, res4, pos4); - logln("" + l + " formatted to " + res4); + System.out.println("" + l + " formatted to " + res4); // ======= Test parse() - logln("Testing parse()"); + System.out.println("Testing parse()"); String text = new String("-10,456.0037"); ParsePosition pos = new ParsePosition(0); @@ -127,109 +128,109 @@ public void TestAPI() pat.applyPattern(patt); double d2 = pat.parse(text, pos).doubleValue(); if(d2 != d) { - errln("ERROR: Roundtrip failed (via parse(" + + fail("ERROR: Roundtrip failed (via parse(" + d2 + " != " + d + ")) for " + text); } - logln(text + " parsed into " + (long) d2); + System.out.println(text + " parsed into " + (long) d2); // ======= Test getters and setters - logln("Testing getters and setters"); + System.out.println("Testing getters and setters"); final DecimalFormatSymbols syms = pat.getDecimalFormatSymbols(); def.setDecimalFormatSymbols(syms); if(!pat.getDecimalFormatSymbols().equals( def.getDecimalFormatSymbols())) { - errln("ERROR: set DecimalFormatSymbols() failed"); + fail("ERROR: set DecimalFormatSymbols() failed"); } String posPrefix; pat.setPositivePrefix("+"); posPrefix = pat.getPositivePrefix(); - logln("Positive prefix (should be +): " + posPrefix); + System.out.println("Positive prefix (should be +): " + posPrefix); if(posPrefix != "+") { - errln("ERROR: setPositivePrefix() failed"); + fail("ERROR: setPositivePrefix() failed"); } String negPrefix; pat.setNegativePrefix("-"); negPrefix = pat.getNegativePrefix(); - logln("Negative prefix (should be -): " + negPrefix); + System.out.println("Negative prefix (should be -): " + negPrefix); if(negPrefix != "-") { - errln("ERROR: setNegativePrefix() failed"); + fail("ERROR: setNegativePrefix() failed"); } String posSuffix; pat.setPositiveSuffix("_"); posSuffix = pat.getPositiveSuffix(); - logln("Positive suffix (should be _): " + posSuffix); + System.out.println("Positive suffix (should be _): " + posSuffix); if(posSuffix != "_") { - errln("ERROR: setPositiveSuffix() failed"); + fail("ERROR: setPositiveSuffix() failed"); } String negSuffix; pat.setNegativeSuffix("~"); negSuffix = pat.getNegativeSuffix(); - logln("Negative suffix (should be ~): " + negSuffix); + System.out.println("Negative suffix (should be ~): " + negSuffix); if(negSuffix != "~") { - errln("ERROR: setNegativeSuffix() failed"); + fail("ERROR: setNegativeSuffix() failed"); } long multiplier = 0; pat.setMultiplier(8); multiplier = pat.getMultiplier(); - logln("Multiplier (should be 8): " + multiplier); + System.out.println("Multiplier (should be 8): " + multiplier); if(multiplier != 8) { - errln("ERROR: setMultiplier() failed"); + fail("ERROR: setMultiplier() failed"); } int groupingSize = 0; pat.setGroupingSize(2); groupingSize = pat.getGroupingSize(); - logln("Grouping size (should be 2): " + (long) groupingSize); + System.out.println("Grouping size (should be 2): " + (long) groupingSize); if(groupingSize != 2) { - errln("ERROR: setGroupingSize() failed"); + fail("ERROR: setGroupingSize() failed"); } pat.setDecimalSeparatorAlwaysShown(true); boolean tf = pat.isDecimalSeparatorAlwaysShown(); - logln("DecimalSeparatorIsAlwaysShown (should be true) is " + + System.out.println("DecimalSeparatorIsAlwaysShown (should be true) is " + (tf ? "true" : "false")); if(tf != true) { - errln("ERROR: setDecimalSeparatorAlwaysShown() failed"); + fail("ERROR: setDecimalSeparatorAlwaysShown() failed"); } String funkyPat; funkyPat = pat.toPattern(); - logln("Pattern is " + funkyPat); + System.out.println("Pattern is " + funkyPat); String locPat; locPat = pat.toLocalizedPattern(); - logln("Localized pattern is " + locPat); + System.out.println("Localized pattern is " + locPat); // ======= Test applyPattern() - logln("Testing applyPattern()"); + System.out.println("Testing applyPattern()"); String p1 = new String("#,##0.0#;(#,##0.0#)"); - logln("Applying pattern " + p1); + System.out.println("Applying pattern " + p1); pat.applyPattern(p1); String s2; s2 = pat.toPattern(); - logln("Extracted pattern is " + s2); + System.out.println("Extracted pattern is " + s2); if( ! s2.equals(p1) ) { - errln("ERROR: toPattern() result did not match " + + fail("ERROR: toPattern() result did not match " + "pattern applied"); } String p2 = new String("#,##0.0# FF;(#,##0.0# FF)"); - logln("Applying pattern " + p2); + System.out.println("Applying pattern " + p2); pat.applyLocalizedPattern(p2); String s3; s3 = pat.toLocalizedPattern(); - logln("Extracted pattern is " + s3); + System.out.println("Extracted pattern is " + s3); if( ! s3.equals(p2) ) { - errln("ERROR: toLocalizedPattern() result did not match " + + fail("ERROR: toLocalizedPattern() result did not match " + "pattern applied"); } diff --git a/test/jdk/java/text/Format/NumberFormat/IntlTestDecimalFormatSymbols.java b/test/jdk/java/text/Format/NumberFormat/IntlTestDecimalFormatSymbols.java index cd19fee1e35..ba09d888bca 100644 --- a/test/jdk/java/text/Format/NumberFormat/IntlTestDecimalFormatSymbols.java +++ b/test/jdk/java/text/Format/NumberFormat/IntlTestDecimalFormatSymbols.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,8 +23,9 @@ /* * @test - * @library /java/text/testlib + * @bug 8282625 * @summary test International Decimal Format Symbols + * @run junit IntlTestDecimalFormatSymbols */ /* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved @@ -41,13 +42,14 @@ import java.text.*; import java.util.*; -public class IntlTestDecimalFormatSymbols extends IntlTest -{ - public static void main(String[] args) throws Exception { - new IntlTestDecimalFormatSymbols().run(args); - } +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.fail; + +public class IntlTestDecimalFormatSymbols +{ // Test the API of DecimalFormatSymbols; primarily a simple get/set set. + @Test public void TestSymbols() { DecimalFormatSymbols fr = new DecimalFormatSymbols(Locale.FRENCH); @@ -55,7 +57,7 @@ public void TestSymbols() DecimalFormatSymbols en = new DecimalFormatSymbols(Locale.ENGLISH); if(en.equals(fr)) { - errln("ERROR: English DecimalFormatSymbols equal to French"); + fail("ERROR: English DecimalFormatSymbols equal to French"); } // just do some VERY basic tests to make sure that get/set work @@ -63,63 +65,63 @@ public void TestSymbols() char zero = en.getZeroDigit(); fr.setZeroDigit(zero); if(fr.getZeroDigit() != en.getZeroDigit()) { - errln("ERROR: get/set ZeroDigit failed"); + fail("ERROR: get/set ZeroDigit failed"); } char group = en.getGroupingSeparator(); fr.setGroupingSeparator(group); if(fr.getGroupingSeparator() != en.getGroupingSeparator()) { - errln("ERROR: get/set GroupingSeparator failed"); + fail("ERROR: get/set GroupingSeparator failed"); } char decimal = en.getDecimalSeparator(); fr.setDecimalSeparator(decimal); if(fr.getDecimalSeparator() != en.getDecimalSeparator()) { - errln("ERROR: get/set DecimalSeparator failed"); + fail("ERROR: get/set DecimalSeparator failed"); } char perMill = en.getPerMill(); fr.setPerMill(perMill); if(fr.getPerMill() != en.getPerMill()) { - errln("ERROR: get/set PerMill failed"); + fail("ERROR: get/set PerMill failed"); } char percent = en.getPercent(); fr.setPercent(percent); if(fr.getPercent() != en.getPercent()) { - errln("ERROR: get/set Percent failed"); + fail("ERROR: get/set Percent failed"); } char digit = en.getDigit(); fr.setDigit(digit); if(fr.getPercent() != en.getPercent()) { - errln("ERROR: get/set Percent failed"); + fail("ERROR: get/set Percent failed"); } char patternSeparator = en.getPatternSeparator(); fr.setPatternSeparator(patternSeparator); if(fr.getPatternSeparator() != en.getPatternSeparator()) { - errln("ERROR: get/set PatternSeparator failed"); + fail("ERROR: get/set PatternSeparator failed"); } String infinity = en.getInfinity(); fr.setInfinity(infinity); String infinity2 = fr.getInfinity(); if(! infinity.equals(infinity2)) { - errln("ERROR: get/set Infinity failed"); + fail("ERROR: get/set Infinity failed"); } String nan = en.getNaN(); fr.setNaN(nan); String nan2 = fr.getNaN(); if(! nan.equals(nan2)) { - errln("ERROR: get/set NaN failed"); + fail("ERROR: get/set NaN failed"); } char minusSign = en.getMinusSign(); fr.setMinusSign(minusSign); if(fr.getMinusSign() != en.getMinusSign()) { - errln("ERROR: get/set MinusSign failed"); + fail("ERROR: get/set MinusSign failed"); } // char exponential = en.getExponentialSymbol(); @@ -133,7 +135,7 @@ public void TestSymbols() en = (DecimalFormatSymbols) fr.clone(); if(! en.equals(fr)) { - errln("ERROR: Clone failed"); + fail("ERROR: Clone failed"); } } } diff --git a/test/jdk/java/text/Format/NumberFormat/IntlTestNumberFormatAPI.java b/test/jdk/java/text/Format/NumberFormat/IntlTestNumberFormatAPI.java index 011db2bdea3..73b2a2d3d1a 100644 --- a/test/jdk/java/text/Format/NumberFormat/IntlTestNumberFormatAPI.java +++ b/test/jdk/java/text/Format/NumberFormat/IntlTestNumberFormatAPI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,9 +23,9 @@ /* * @test - * @library /java/text/testlib * @summary test International Number Format API * @modules jdk.localedata + * @run junit IntlTestNumberFormatAPI */ /* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved @@ -42,23 +42,24 @@ import java.text.*; import java.util.*; -public class IntlTestNumberFormatAPI extends IntlTest -{ - public static void main(String[] args) throws Exception { - new IntlTestNumberFormatAPI().run(args); - } +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.fail; + +public class IntlTestNumberFormatAPI +{ // This test checks various generic API methods in DecimalFormat to achieve 100% API coverage. + @Test public void TestAPI() { Locale reservedLocale = Locale.getDefault(); try { - logln("NumberFormat API test---"); logln(""); + System.out.println("NumberFormat API test---"); System.out.println(""); Locale.setDefault(Locale.ENGLISH); // ======= Test constructors - logln("Testing NumberFormat constructors"); + System.out.println("Testing NumberFormat constructors"); NumberFormat def = NumberFormat.getInstance(); @@ -76,15 +77,15 @@ public void TestAPI() // ======= Test equality - logln("Testing equality operator"); + System.out.println("Testing equality operator"); if( per_fr.equals(cur_fr) ) { - errln("ERROR: == failed"); + fail("ERROR: == failed"); } // ======= Test various format() methods - logln("Testing various format() methods"); + System.out.println("Testing various format() methods"); // final double d = -10456.0037; // this appears as // -10456.003700000001 on NT @@ -105,27 +106,27 @@ public void TestAPI() FieldPosition pos4 = new FieldPosition(0); res1 = cur_fr.format(d); - logln( "" + d + " formatted to " + res1); + System.out.println( "" + d + " formatted to " + res1); res2 = cur_fr.format(l); - logln("" + l + " formatted to " + res2); + System.out.println("" + l + " formatted to " + res2); res3 = cur_fr.format(d, res3, pos1); - logln( "" + d + " formatted to " + res3); + System.out.println( "" + d + " formatted to " + res3); res4 = cur_fr.format(l, res4, pos2); - logln("" + l + " formatted to " + res4); + System.out.println("" + l + " formatted to " + res4); res5 = cur_fr.format(d, res5, pos3); - logln("" + d + " formatted to " + res5); + System.out.println("" + d + " formatted to " + res5); res6 = cur_fr.format(l, res6, pos4); - logln("" + l + " formatted to " + res6); + System.out.println("" + l + " formatted to " + res6); // ======= Test parse() - logln("Testing parse()"); + System.out.println("Testing parse()"); // String text = new String("-10,456.0037"); String text = new String("-10456,0037"); @@ -133,70 +134,70 @@ public void TestAPI() ParsePosition pos01 = new ParsePosition(0); double d1 = ((Number)fr.parseObject(text, pos)).doubleValue(); if(d1 != d) { - errln("ERROR: Roundtrip failed (via parse()) for " + text); + fail("ERROR: Roundtrip failed (via parse()) for " + text); } - logln(text + " parsed into " + d1); + System.out.println(text + " parsed into " + d1); double d2 = fr.parse(text, pos01).doubleValue(); if(d2 != d) { - errln("ERROR: Roundtrip failed (via parse()) for " + text); + fail("ERROR: Roundtrip failed (via parse()) for " + text); } - logln(text + " parsed into " + d2); + System.out.println(text + " parsed into " + d2); double d3 = 0; try { d3 = fr.parse(text).doubleValue(); } catch (ParseException e) { - errln("ERROR: parse() failed"); + fail("ERROR: parse() failed"); } if(d3 != d) { - errln("ERROR: Roundtrip failed (via parse()) for " + text); + fail("ERROR: Roundtrip failed (via parse()) for " + text); } - logln(text + " parsed into " + d3); + System.out.println(text + " parsed into " + d3); // ======= Test getters and setters - logln("Testing getters and setters"); + System.out.println("Testing getters and setters"); final Locale[] locales = NumberFormat.getAvailableLocales(); long count = locales.length; - logln("Got " + count + " locales" ); + System.out.println("Got " + count + " locales" ); for(int i = 0; i < count; i++) { String name; name = locales[i].getDisplayName(); - logln(name); + System.out.println(name); } fr.setParseIntegerOnly( def.isParseIntegerOnly() ); if(fr.isParseIntegerOnly() != def.isParseIntegerOnly() ) { - errln("ERROR: setParseIntegerOnly() failed"); + fail("ERROR: setParseIntegerOnly() failed"); } fr.setGroupingUsed( def.isGroupingUsed() ); if(fr.isGroupingUsed() != def.isGroupingUsed() ) { - errln("ERROR: setGroupingUsed() failed"); + fail("ERROR: setGroupingUsed() failed"); } fr.setMaximumIntegerDigits( def.getMaximumIntegerDigits() ); if(fr.getMaximumIntegerDigits() != def.getMaximumIntegerDigits() ) { - errln("ERROR: setMaximumIntegerDigits() failed"); + fail("ERROR: setMaximumIntegerDigits() failed"); } fr.setMinimumIntegerDigits( def.getMinimumIntegerDigits() ); if(fr.getMinimumIntegerDigits() != def.getMinimumIntegerDigits() ) { - errln("ERROR: setMinimumIntegerDigits() failed"); + fail("ERROR: setMinimumIntegerDigits() failed"); } fr.setMaximumFractionDigits( def.getMaximumFractionDigits() ); if(fr.getMaximumFractionDigits() != def.getMaximumFractionDigits() ) { - errln("ERROR: setMaximumFractionDigits() failed"); + fail("ERROR: setMaximumFractionDigits() failed"); } fr.setMinimumFractionDigits( def.getMinimumFractionDigits() ); if(fr.getMinimumFractionDigits() != def.getMinimumFractionDigits() ) { - errln("ERROR: setMinimumFractionDigits() failed"); + fail("ERROR: setMinimumFractionDigits() failed"); } // ======= Test getStaticClassID() diff --git a/test/jdk/java/text/Format/NumberFormat/NumberRegression.java b/test/jdk/java/text/Format/NumberFormat/NumberRegression.java index 037efa827b8..be1648a7ee4 100644 --- a/test/jdk/java/text/Format/NumberFormat/NumberRegression.java +++ b/test/jdk/java/text/Format/NumberFormat/NumberRegression.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,11 +32,11 @@ * 4217661 4243011 4243108 4330377 4233840 4241880 4833877 8008577 8227313 * @summary Regression tests for NumberFormat and associated classes * @library /java/text/testlib - * @build IntlTest HexDumpReader TestUtils + * @build HexDumpReader TestUtils * @modules java.base/sun.util.resources * jdk.localedata * @compile -XDignore.symbol.file NumberRegression.java - * @run main/othervm -Djava.locale.providers=COMPAT,SPI NumberRegression + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI NumberRegression */ /* @@ -58,23 +58,24 @@ import java.math.BigInteger; import sun.util.resources.LocaleData; -public class NumberRegression extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new NumberRegression().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class NumberRegression { /** * NumberFormat.equals comparing with null should always return false. */ + @Test public void Test4075713(){ try { MyNumberFormatTest tmp = new MyNumberFormatTest(); if (!tmp.equals(null)) - logln("NumberFormat.equals passed"); + System.out.println("NumberFormat.equals passed"); } catch (NullPointerException e) { - errln("(new MyNumberFormatTest()).equals(null) throws unexpected exception"); + fail("(new MyNumberFormatTest()).equals(null) throws unexpected exception"); } } @@ -82,6 +83,7 @@ public void Test4075713(){ * NumberFormat.equals comparing two obj equal even the setGroupingUsed * flag is different. */ + @Test public void Test4074620() { MyNumberFormatTest nf1 = new MyNumberFormatTest(); @@ -90,8 +92,8 @@ public void Test4074620() { nf1.setGroupingUsed(false); nf2.setGroupingUsed(true); - if (nf1.equals(nf2)) errln("Test for bug 4074620 failed"); - else logln("Test for bug 4074620 passed."); + if (nf1.equals(nf2)) fail("Test for bug 4074620 failed"); + else System.out.println("Test for bug 4074620 passed."); return; } @@ -100,10 +102,11 @@ public void Test4074620() { * DecimalFormat.format() incorrectly uses maxFractionDigits setting. */ + @Test public void Test4088161 (){ Locale locale = Locale.getDefault(); if (!TestUtils.usesAsciiDigits(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -113,39 +116,41 @@ public void Test4088161 (){ df.setMaximumFractionDigits(16); StringBuffer sBuf1 = new StringBuffer(""); FieldPosition fp1 = new FieldPosition(0); - logln("d = " + d); - logln("maxFractionDigits = " + df.getMaximumFractionDigits()); - logln(" format(d) = '" + df.format(d, sBuf1, fp1) + "'"); + System.out.println("d = " + d); + System.out.println("maxFractionDigits = " + df.getMaximumFractionDigits()); + System.out.println(" format(d) = '" + df.format(d, sBuf1, fp1) + "'"); df.setMaximumFractionDigits(17); StringBuffer sBuf2 = new StringBuffer(""); FieldPosition fp2 = new FieldPosition(0); - logln("maxFractionDigits = " + df.getMaximumFractionDigits()); + System.out.println("maxFractionDigits = " + df.getMaximumFractionDigits()); df.format(d, sBuf2, fp2); String expected = "100"; if (!sBuf2.toString().equals(expected)) - errln(" format(d) = '" + sBuf2 + "'"); + fail(" format(d) = '" + sBuf2 + "'"); } /** * DecimalFormatSymbols should be cloned in the ctor DecimalFormat. * DecimalFormat(String, DecimalFormatSymbols). */ + @Test public void Test4087245 (){ DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(); DecimalFormat df = new DecimalFormat("#,##0.0", symbols); long n = 123; StringBuffer buf1 = new StringBuffer(); StringBuffer buf2 = new StringBuffer(); - logln("format(" + n + ") = " + + System.out.println("format(" + n + ") = " + df.format(n, buf1, new FieldPosition(0))); symbols.setDecimalSeparator('p'); // change value of field - logln("format(" + n + ") = " + + System.out.println("format(" + n + ") = " + df.format(n, buf2, new FieldPosition(0))); if (!buf1.toString().equals(buf2.toString())) - errln("Test for bug 4087245 failed"); + fail("Test for bug 4087245 failed"); } /** * DecimalFormat.format() incorrectly formats 0.0 */ + @Test public void Test4087535 () { DecimalFormat df = new DecimalFormat(); @@ -155,31 +160,33 @@ public void Test4087535 () String buffer = new String(); buffer = df.format(n); if (buffer.length() == 0) - errln(n + ": '" + buffer + "'"); + fail(n + ": '" + buffer + "'"); n = 0.1; buffer = df.format(n); if (buffer.length() == 0) - errln(n + ": '" + buffer + "'"); + fail(n + ": '" + buffer + "'"); } /** * DecimalFormat.format fails when groupingSize is set to 0. */ + @Test public void Test4088503 (){ DecimalFormat df = new DecimalFormat(); df.setGroupingSize(0); StringBuffer sBuf = new StringBuffer(""); FieldPosition fp = new FieldPosition(0); try { - logln(df.format(123, sBuf, fp).toString()); + System.out.println(df.format(123, sBuf, fp).toString()); } catch (Exception foo) { - errln("Test for bug 4088503 failed."); + fail("Test for bug 4088503 failed."); } } /** * NumberFormat.getCurrencyInstance is wrong. */ + @Test public void Test4066646 () { float returnfloat = 0.0f; assignFloatValue(2.04f); @@ -190,42 +197,45 @@ public void Test4066646 () { public float assignFloatValue(float returnfloat) { - logln(" VALUE " + returnfloat); + System.out.println(" VALUE " + returnfloat); NumberFormat nfcommon = NumberFormat.getCurrencyInstance(Locale.US); nfcommon.setGroupingUsed(false); String stringValue = nfcommon.format(returnfloat).substring(1); if (Float.valueOf(stringValue).floatValue() != returnfloat) - errln(" DISPLAYVALUE " + stringValue); + fail(" DISPLAYVALUE " + stringValue); return returnfloat; } // End Of assignFloatValue() /** * DecimalFormat throws exception when parsing "0" */ + @Test public void Test4059870() { DecimalFormat format = new DecimalFormat("00"); try { - logln(format.parse("0").toString()); - } catch (Exception e) { errln("Test for bug 4059870 failed : " + e); } + System.out.println(format.parse("0").toString()); + } catch (Exception e) { fail("Test for bug 4059870 failed : " + e); } } /** * DecimalFormatSymbol.equals should always return false when * comparing with null. */ + @Test public void Test4083018 (){ DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(); try { if (!dfs.equals(null)) - logln("Test Passed!"); + System.out.println("Test Passed!"); } catch (Exception foo) { - errln("Test for bug 4083018 failed => Message : " + foo.getMessage()); + fail("Test for bug 4083018 failed => Message : " + foo.getMessage()); } } /** * DecimalFormat does not round up correctly. */ + @Test public void Test4071492 (){ Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); @@ -233,10 +243,10 @@ public void Test4071492 (){ NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(4); String out = nf.format(x); - logln("0.00159999 formats with 4 fractional digits to " + out); + System.out.println("0.00159999 formats with 4 fractional digits to " + out); String expected = "0.0016"; if (!out.equals(expected)) - errln("FAIL: Expected " + expected); + fail("FAIL: Expected " + expected); Locale.setDefault(savedLocale); } @@ -244,33 +254,34 @@ public void Test4071492 (){ * A space as a group separator for localized pattern causes * wrong format. WorkAround : use non-breaking space. */ + @Test public void Test4086575() { NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE); - logln("nf toPattern1: " + ((DecimalFormat)nf).toPattern()); - logln("nf toLocPattern1: " + ((DecimalFormat)nf).toLocalizedPattern()); + System.out.println("nf toPattern1: " + ((DecimalFormat)nf).toPattern()); + System.out.println("nf toLocPattern1: " + ((DecimalFormat)nf).toLocalizedPattern()); // No group separator - logln("...applyLocalizedPattern ###,00;(###,00) "); + System.out.println("...applyLocalizedPattern ###,00;(###,00) "); ((DecimalFormat)nf).applyLocalizedPattern("###,00;(###,00)"); - logln("nf toPattern2: " + ((DecimalFormat)nf).toPattern()); - logln("nf toLocPattern2: " + ((DecimalFormat)nf).toLocalizedPattern()); + System.out.println("nf toPattern2: " + ((DecimalFormat)nf).toPattern()); + System.out.println("nf toLocPattern2: " + ((DecimalFormat)nf).toLocalizedPattern()); - logln("nf: " + nf.format(1234)); // 1234,00 - logln("nf: " + nf.format(-1234)); // (1234,00) + System.out.println("nf: " + nf.format(1234)); // 1234,00 + System.out.println("nf: " + nf.format(-1234)); // (1234,00) // Space as group separator - logln("...applyLocalizedPattern # ###,00;(# ###,00) "); + System.out.println("...applyLocalizedPattern # ###,00;(# ###,00) "); ((DecimalFormat)nf).applyLocalizedPattern("#\u00a0###,00;(#\u00a0###,00)"); - logln("nf toPattern2: " + ((DecimalFormat)nf).toPattern()); - logln("nf toLocPattern2: " + ((DecimalFormat)nf).toLocalizedPattern()); + System.out.println("nf toPattern2: " + ((DecimalFormat)nf).toPattern()); + System.out.println("nf toLocPattern2: " + ((DecimalFormat)nf).toLocalizedPattern()); String buffer = nf.format(1234); if (!buffer.equals("1\u00a0234,00")) - errln("nf : " + buffer); // Expect 1 234,00 + fail("nf : " + buffer); // Expect 1 234,00 buffer = nf.format(-1234); if (!buffer.equals("(1\u00a0234,00)")) - errln("nf : " + buffer); // Expect (1 234,00) + fail("nf : " + buffer); // Expect (1 234,00) // Erroneously prints: // 1234,00 , @@ -280,16 +291,17 @@ public void Test4086575() { /** * DecimalFormat.parse returns wrong value */ + @Test public void Test4068693() { Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); - logln("----- Test Application -----"); + System.out.println("----- Test Application -----"); ParsePosition pos; DecimalFormat df = new DecimalFormat(); Double d = (Double)df.parse("123.55456", pos=new ParsePosition(0)); if (!d.toString().equals("123.55456")) { - errln("Result -> " + d); + fail("Result -> " + d); } Locale.setDefault(savedLocale); } @@ -298,53 +310,56 @@ public void Test4068693() * null pointer thrown when accessing a deserialized DecimalFormat * object. */ + @Test public void Test4069754() { try { myformat it = new myformat(); - logln(it.Now()); + System.out.println(it.Now()); FileOutputStream ostream = new FileOutputStream("t.tmp"); ObjectOutputStream p = new ObjectOutputStream(ostream); p.writeObject(it); ostream.close(); - logln("Saved ok."); + System.out.println("Saved ok."); FileInputStream istream = new FileInputStream("t.tmp"); ObjectInputStream p2 = new ObjectInputStream(istream); myformat it2 = (myformat)p2.readObject(); - logln(it2.Now()); + System.out.println(it2.Now()); istream.close(); - logln("Loaded ok."); + System.out.println("Loaded ok."); } catch (Exception foo) { - errln("Test for bug 4069754 or 4057878 failed => Exception: " + foo.getMessage()); + fail("Test for bug 4069754 or 4057878 failed => Exception: " + foo.getMessage()); } } /** * DecimalFormat.applyPattern(String) allows illegal patterns */ + @Test public void Test4087251 (){ DecimalFormat df = new DecimalFormat(); try { df.applyPattern("#.#.#"); - logln("toPattern() returns \"" + df.toPattern() + "\""); - errln("applyPattern(\"#.#.#\") doesn't throw IllegalArgumentException"); + System.out.println("toPattern() returns \"" + df.toPattern() + "\""); + fail("applyPattern(\"#.#.#\") doesn't throw IllegalArgumentException"); } catch (IllegalArgumentException e) { - logln("Caught Illegal Argument Error !"); + System.out.println("Caught Illegal Argument Error !"); } // Second test; added 5/11/98 when reported to fail on 1.2b3 try { df.applyPattern("#0.0#0#0"); - logln("toPattern() returns \"" + df.toPattern() + "\""); - errln("applyPattern(\"#0.0#0#0\") doesn't throw IllegalArgumentException"); + System.out.println("toPattern() returns \"" + df.toPattern() + "\""); + fail("applyPattern(\"#0.0#0#0\") doesn't throw IllegalArgumentException"); } catch (IllegalArgumentException e) { - logln("Ok - IllegalArgumentException for #0.0#0#0"); + System.out.println("Ok - IllegalArgumentException for #0.0#0#0"); } } /** * DecimalFormat.format() loses precision */ + @Test public void Test4090489 (){ Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); @@ -355,11 +370,11 @@ public void Test4090489 (){ BigDecimal bd = new BigDecimal(d); StringBuffer sb = new StringBuffer(""); FieldPosition fp = new FieldPosition(0); - logln("d = " + d); - logln("BigDecimal.toString(): " + bd.toString()); + System.out.println("d = " + d); + System.out.println("BigDecimal.toString(): " + bd.toString()); df.format(d, sb, fp); if (!sb.toString().equals("10000000.0000000100")) { - errln("DecimalFormat.format(): " + sb.toString()); + fail("DecimalFormat.format(): " + sb.toString()); } Locale.setDefault(savedLocale); } @@ -367,10 +382,11 @@ public void Test4090489 (){ /** * DecimalFormat.format() loses precision */ + @Test public void Test4090504 () { double d = 1; - logln("d = " + d); + System.out.println("d = " + d); DecimalFormat df = new DecimalFormat(); StringBuffer sb; FieldPosition fp; @@ -379,16 +395,17 @@ public void Test4090504 () df.setMaximumFractionDigits(i); sb = new StringBuffer(""); fp = new FieldPosition(0); - logln(" getMaximumFractionDigits() = " + i); - logln(" formated: " + df.format(d, sb, fp)); + System.out.println(" getMaximumFractionDigits() = " + i); + System.out.println(" formated: " + df.format(d, sb, fp)); } } catch (Exception foo) { - errln("Bug 4090504 regression test failed. Message : " + foo.getMessage()); + fail("Bug 4090504 regression test failed. Message : " + foo.getMessage()); } } /** * DecimalFormat.parse(String str, ParsePosition pp) loses precision */ + @Test public void Test4095713 () { Locale savedLocale = Locale.getDefault(); @@ -397,15 +414,16 @@ public void Test4095713 () String str = "0.1234"; Double d1 = 0.1234; Double d2 = (Double) df.parse(str, new ParsePosition(0)); - logln(d1.toString()); + System.out.println(d1.toString()); if (d2.doubleValue() != d1.doubleValue()) - errln("Bug 4095713 test failed, new double value : " + d2); + fail("Bug 4095713 test failed, new double value : " + d2); Locale.setDefault(savedLocale); } /** * DecimalFormat.parse() fails when multiplier is not set to 1 */ + @Test public void Test4092561 () { Locale savedLocale = Locale.getDefault(); @@ -413,32 +431,32 @@ public void Test4092561 () DecimalFormat df = new DecimalFormat(); String str = Long.toString(Long.MIN_VALUE); - logln("Long.MIN_VALUE : " + df.parse(str, new ParsePosition(0)).toString()); + System.out.println("Long.MIN_VALUE : " + df.parse(str, new ParsePosition(0)).toString()); df.setMultiplier(100); Number num = df.parse(str, new ParsePosition(0)); if (num.doubleValue() != -9.223372036854776E16) { - errln("Bug 4092561 test failed when multiplier is not set to 1. Expected: -9.223372036854776E16, got: " + num.doubleValue()); + fail("Bug 4092561 test failed when multiplier is not set to 1. Expected: -9.223372036854776E16, got: " + num.doubleValue()); } df.setMultiplier(-100); num = df.parse(str, new ParsePosition(0)); if (num.doubleValue() != 9.223372036854776E16) { - errln("Bug 4092561 test failed when multiplier is not set to 1. Expected: 9.223372036854776E16, got: " + num.doubleValue()); + fail("Bug 4092561 test failed when multiplier is not set to 1. Expected: 9.223372036854776E16, got: " + num.doubleValue()); } str = Long.toString(Long.MAX_VALUE); - logln("Long.MAX_VALUE : " + df.parse(str, new ParsePosition(0)).toString()); + System.out.println("Long.MAX_VALUE : " + df.parse(str, new ParsePosition(0)).toString()); df.setMultiplier(100); num = df.parse(str, new ParsePosition(0)); if (num.doubleValue() != 9.223372036854776E16) { - errln("Bug 4092561 test failed when multiplier is not set to 1. Expected: 9.223372036854776E16, got: " + num.doubleValue()); + fail("Bug 4092561 test failed when multiplier is not set to 1. Expected: 9.223372036854776E16, got: " + num.doubleValue()); } df.setMultiplier(-100); num = df.parse(str, new ParsePosition(0)); if (num.doubleValue() != -9.223372036854776E16) { - errln("Bug 4092561 test failed when multiplier is not set to 1. Expected: -9.223372036854776E16, got: " + num.doubleValue()); + fail("Bug 4092561 test failed when multiplier is not set to 1. Expected: -9.223372036854776E16, got: " + num.doubleValue()); } Locale.setDefault(savedLocale); @@ -447,6 +465,7 @@ public void Test4092561 () /** * DecimalFormat: Negative format ignored. */ + @Test public void Test4092480 () { DecimalFormat dfFoo = new DecimalFormat("000"); @@ -454,28 +473,28 @@ public void Test4092480 () try { dfFoo.applyPattern("0000;-000"); if (!dfFoo.toPattern().equals("#0000")) - errln("dfFoo.toPattern : " + dfFoo.toPattern()); - logln(dfFoo.format(42)); - logln(dfFoo.format(-42)); + fail("dfFoo.toPattern : " + dfFoo.toPattern()); + System.out.println(dfFoo.format(42)); + System.out.println(dfFoo.format(-42)); dfFoo.applyPattern("000;-000"); if (!dfFoo.toPattern().equals("#000")) - errln("dfFoo.toPattern : " + dfFoo.toPattern()); - logln(dfFoo.format(42)); - logln(dfFoo.format(-42)); + fail("dfFoo.toPattern : " + dfFoo.toPattern()); + System.out.println(dfFoo.format(42)); + System.out.println(dfFoo.format(-42)); dfFoo.applyPattern("000;-0000"); if (!dfFoo.toPattern().equals("#000")) - errln("dfFoo.toPattern : " + dfFoo.toPattern()); - logln(dfFoo.format(42)); - logln(dfFoo.format(-42)); + fail("dfFoo.toPattern : " + dfFoo.toPattern()); + System.out.println(dfFoo.format(42)); + System.out.println(dfFoo.format(-42)); dfFoo.applyPattern("0000;-000"); if (!dfFoo.toPattern().equals("#0000")) - errln("dfFoo.toPattern : " + dfFoo.toPattern()); - logln(dfFoo.format(42)); - logln(dfFoo.format(-42)); + fail("dfFoo.toPattern : " + dfFoo.toPattern()); + System.out.println(dfFoo.format(42)); + System.out.println(dfFoo.format(-42)); } catch (Exception foo) { - errln("Message " + foo.getMessage()); + fail("Message " + foo.getMessage()); } } /** @@ -486,6 +505,7 @@ public void Test4092480 () * never contain the monetary separator! Decimal separator in pattern is * interpreted as monetary separator if currency symbol is seen! */ + @Test public void Test4087244 () { Locale de = new Locale("pt", "PT"); DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(de); @@ -496,7 +516,7 @@ public void Test4087244 () { char monSep = sym.getMonetaryDecimalSeparator(); char zero = sym.getZeroDigit(); if (decSep == monSep) { - errln("ERROR in test: want decimal sep != monetary sep"); + fail("ERROR in test: want decimal sep != monetary sep"); } else { df.setMinimumIntegerDigits(1); df.setMinimumFractionDigits(2); @@ -504,10 +524,10 @@ public void Test4087244 () { String monStr = "1" + monSep + "23"; String decStr = "1" + decSep + "23"; if (str.indexOf(monStr) >= 0 && str.indexOf(decStr) < 0) { - logln("OK: 1.23 -> \"" + str + "\" contains \"" + + System.out.println("OK: 1.23 -> \"" + str + "\" contains \"" + monStr + "\" and not \"" + decStr + '"'); } else { - errln("FAIL: 1.23 -> \"" + str + "\", should contain \"" + + fail("FAIL: 1.23 -> \"" + str + "\", should contain \"" + monStr + "\" and not \"" + decStr + '"'); } @@ -516,6 +536,7 @@ public void Test4087244 () { /** * Number format data rounding errors for locale FR */ + @Test public void Test4070798 () { NumberFormat formatter; String tempString; @@ -533,9 +554,9 @@ public void Test4070798 () { tempString = formatter.format (-5789.9876); if (tempString.equals(expectedDefault)) { - logln ("Bug 4070798 default test passed."); + System.out.println("Bug 4070798 default test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedDefault + " Received " + tempString ); } @@ -545,9 +566,9 @@ public void Test4070798 () { tempString = formatter.format( 5789.9876 ); if (tempString.equals(expectedCurrency) ) { - logln ("Bug 4070798 currency test assed."); + System.out.println("Bug 4070798 currency test assed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedCurrency + " Received " + tempString ); } @@ -557,9 +578,9 @@ public void Test4070798 () { tempString = formatter.format (-5789.9876); if (tempString.equals(expectedPercent) ) { - logln ("Bug 4070798 percentage test passed."); + System.out.println("Bug 4070798 percentage test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedPercent + " Received " + tempString ); } @@ -567,6 +588,7 @@ public void Test4070798 () { /** * Data rounding errors for French (Canada) locale */ + @Test public void Test4071005 () { NumberFormat formatter; @@ -584,9 +606,9 @@ public void Test4071005 () { formatter = NumberFormat.getNumberInstance(Locale.CANADA_FRENCH); tempString = formatter.format (-5789.9876); if (tempString.equals(expectedDefault)) { - logln ("Bug 4071005 default test passed."); + System.out.println("Bug 4071005 default test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedDefault + " Received " + tempString ); } @@ -595,9 +617,9 @@ public void Test4071005 () { tempString = formatter.format( 5789.9876 ) ; if (tempString.equals(expectedCurrency) ) { - logln ("Bug 4071005 currency test passed."); + System.out.println("Bug 4071005 currency test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedCurrency + " Received " + tempString ); } @@ -605,9 +627,9 @@ public void Test4071005 () { tempString = formatter.format (-5789.9876); if (tempString.equals(expectedPercent) ) { - logln ("Bug 4071005 percentage test passed."); + System.out.println("Bug 4071005 percentage test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedPercent + " Received " + tempString ); } @@ -616,6 +638,7 @@ public void Test4071005 () { /** * Data rounding errors for German (Germany) locale */ + @Test public void Test4071014 () { NumberFormat formatter; String tempString; @@ -632,9 +655,9 @@ public void Test4071014 () { tempString = formatter.format (-5789.9876); if (tempString.equals(expectedDefault)) { - logln ("Bug 4071014 default test passed."); + System.out.println("Bug 4071014 default test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedDefault + " Received " + tempString ); } @@ -643,9 +666,9 @@ public void Test4071014 () { tempString = formatter.format( 5789.9876 ) ; if (tempString.equals(expectedCurrency) ) { - logln ("Bug 4071014 currency test passed."); + System.out.println("Bug 4071014 currency test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedCurrency + " Received " + tempString ); } @@ -654,9 +677,9 @@ public void Test4071014 () { tempString = formatter.format (-5789.9876); if (tempString.equals(expectedPercent) ) { - logln ("Bug 4071014 percentage test passed."); + System.out.println("Bug 4071014 percentage test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedPercent + " Received " + tempString ); } @@ -665,6 +688,7 @@ public void Test4071014 () { /** * Data rounding errors for Italian locale number formats */ + @Test public void Test4071859 () { NumberFormat formatter; String tempString; @@ -681,9 +705,9 @@ public void Test4071859 () { tempString = formatter.format (-5789.9876); if (tempString.equals(expectedDefault)) { - logln ("Bug 4071859 default test passed."); + System.out.println("Bug 4071859 default test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedDefault + " Received " + tempString ); } @@ -692,9 +716,9 @@ public void Test4071859 () { tempString = formatter.format( -5789.9876 ) ; if (tempString.equals(expectedCurrency) ) { - logln ("Bug 4071859 currency test passed."); + System.out.println("Bug 4071859 currency test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedCurrency + " Received " + tempString ); } @@ -703,9 +727,9 @@ public void Test4071859 () { tempString = formatter.format (-5789.9876); if (tempString.equals(expectedPercent) ) { - logln ("Bug 4071859 percentage test passed."); + System.out.println("Bug 4071859 percentage test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedPercent + " Received " + tempString ); } @@ -715,6 +739,7 @@ public void Test4071859 () { /* bug 4071859 * Test rounding for nearest even. */ + @Test public void Test4093610() { Locale savedLocale = Locale.getDefault(); @@ -739,20 +764,21 @@ public void Test4093610() void roundingTest(DecimalFormat df, double x, String expected) { String out = df.format(x); - logln("" + x + " formats with 1 fractional digits to " + out); - if (!out.equals(expected)) errln("FAIL: Expected " + expected); + System.out.println("" + x + " formats with 1 fractional digits to " + out); + if (!out.equals(expected)) fail("FAIL: Expected " + expected); } /** * Tests the setMaximumFractionDigits limit. */ + @Test public void Test4098741() { try { NumberFormat fmt = NumberFormat.getPercentInstance(); fmt.setMaximumFractionDigits(20); - logln(fmt.format(.001)); + System.out.println(fmt.format(.001)); } catch (Exception foo) { - errln("Bug 4098471 failed with exception thrown : " + foo.getMessage()); + fail("Bug 4098471 failed with exception thrown : " + foo.getMessage()); } } /** @@ -760,19 +786,20 @@ public void Test4098741() * Fix comment : HShih A31 Part1 will not be fixed and javadoc needs to be updated. * Part2 has been fixed. */ + @Test public void Test4074454() { Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); try { DecimalFormat fmt = new DecimalFormat("#,#00.00;-#.#"); - logln("Inconsistent negative pattern is fine."); + System.out.println("Inconsistent negative pattern is fine."); DecimalFormat newFmt = new DecimalFormat("#,#00.00 p''ieces;-#,#00.00 p''ieces"); String tempString = newFmt.format(3456.78); if (!tempString.equals("3,456.78 p'ieces")) - errln("Failed! 3,456.78 p'ieces expected, but got : " + tempString); + fail("Failed! 3,456.78 p'ieces expected, but got : " + tempString); } catch (Exception foo) { - errln("An exception was thrown for any inconsistent negative pattern."); + fail("An exception was thrown for any inconsistent negative pattern."); } Locale.setDefault(savedLocale); } @@ -796,46 +823,50 @@ public void Test4074454() * Otherwise, an IllegalArgumentException will be thrown when formatting * "January 35". See GregorianCalendar class javadoc for more details. */ + @Test public void Test4099404() { try { DecimalFormat fmt = new DecimalFormat("000.0#0"); - errln("Bug 4099404 failed applying illegal pattern \"000.0#0\""); + fail("Bug 4099404 failed applying illegal pattern \"000.0#0\""); } catch (Exception foo) { - logln("Bug 4099404 pattern \"000.0#0\" passed"); + System.out.println("Bug 4099404 pattern \"000.0#0\" passed"); } try { DecimalFormat fmt = new DecimalFormat("0#0.000"); - errln("Bug 4099404 failed applying illegal pattern \"0#0.000\""); + fail("Bug 4099404 failed applying illegal pattern \"0#0.000\""); } catch (Exception foo) { - logln("Bug 4099404 pattern \"0#0.000\" passed"); + System.out.println("Bug 4099404 pattern \"0#0.000\" passed"); } } /** * DecimalFormat.applyPattern doesn't set minimum integer digits */ + @Test public void Test4101481() { DecimalFormat sdf = new DecimalFormat("#,##0"); if (sdf.getMinimumIntegerDigits() != 1) - errln("Minimum integer digits : " + sdf.getMinimumIntegerDigits()); + fail("Minimum integer digits : " + sdf.getMinimumIntegerDigits()); } /** * Tests ParsePosition.setErrorPosition() and ParsePosition.getErrorPosition(). */ + @Test public void Test4052223() { try { DecimalFormat fmt = new DecimalFormat("#,#00.00"); Number num = fmt.parse("abc3"); - errln("Bug 4052223 failed : can't parse string \"a\". Got " + num); + fail("Bug 4052223 failed : can't parse string \"a\". Got " + num); } catch (ParseException foo) { - logln("Caught expected ParseException : " + foo.getMessage() + " at index : " + foo.getErrorOffset()); + System.out.println("Caught expected ParseException : " + foo.getMessage() + " at index : " + foo.getErrorOffset()); } } /** * API tests for API addition request A9. */ + @Test public void Test4061302() { DecimalFormatSymbols fmt = DecimalFormatSymbols.getInstance(); @@ -845,9 +876,9 @@ public void Test4061302() if (currency.equals("") || intlCurrency.equals("") || monDecSeparator == 0) { - errln("getCurrencySymbols failed, got empty string."); + fail("getCurrencySymbols failed, got empty string."); } - logln("Before set ==> Currency : " + currency + " Intl Currency : " + intlCurrency + " Monetary Decimal Separator : " + monDecSeparator); + System.out.println("Before set ==> Currency : " + currency + " Intl Currency : " + intlCurrency + " Monetary Decimal Separator : " + monDecSeparator); fmt.setCurrencySymbol("XYZ"); fmt.setInternationalCurrencySymbol("ABC"); fmt.setMonetaryDecimalSeparator('*'); @@ -857,14 +888,15 @@ public void Test4061302() if (!currency.equals("XYZ") || !intlCurrency.equals("ABC") || monDecSeparator != '*') { - errln("setCurrencySymbols failed."); + fail("setCurrencySymbols failed."); } - logln("After set ==> Currency : " + currency + " Intl Currency : " + intlCurrency + " Monetary Decimal Separator : " + monDecSeparator); + System.out.println("After set ==> Currency : " + currency + " Intl Currency : " + intlCurrency + " Monetary Decimal Separator : " + monDecSeparator); } /** * API tests for API addition request A23. FieldPosition.getBeginIndex and * FieldPosition.getEndIndex. */ + @Test public void Test4062486() { DecimalFormat fmt = new DecimalFormat("#,##0.00"); @@ -873,16 +905,17 @@ public void Test4062486() Double num = 1234.5; fmt.format(num, formatted, field); if (field.getBeginIndex() != 0 && field.getEndIndex() != 5) - errln("Format 1234.5 failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex()); + fail("Format 1234.5 failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex()); field.setBeginIndex(7); field.setEndIndex(4); if (field.getBeginIndex() != 7 && field.getEndIndex() != 4) - errln("Set begin/end field indexes failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex()); + fail("Set begin/end field indexes failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex()); } /** * DecimalFormat.parse incorrectly works with a group separator. */ + @Test public void Test4108738() { @@ -891,16 +924,17 @@ public void Test4108738() String text = "1.222,111"; Number num = df.parse(text,new ParsePosition(0)); if (!num.toString().equals("1.222")) - errln("\"" + text + "\" is parsed as " + num); + fail("\"" + text + "\" is parsed as " + num); text = "1.222x111"; num = df.parse(text,new ParsePosition(0)); if (!num.toString().equals("1.222")) - errln("\"" + text + "\" is parsed as " + num); + fail("\"" + text + "\" is parsed as " + num); } /** * DecimalFormat.format() incorrectly formats negative doubles. */ + @Test public void Test4106658() { Locale savedLocale = Locale.getDefault(); @@ -909,15 +943,15 @@ public void Test4106658() double d1 = -0.0; double d2 = -0.0001; StringBuffer buffer = new StringBuffer(); - logln("pattern: \"" + df.toPattern() + "\""); + System.out.println("pattern: \"" + df.toPattern() + "\""); df.format(d1, buffer, new FieldPosition(0)); if (!buffer.toString().equals("-0")) { // Corrected; see 4147706 - errln(d1 + " is formatted as " + buffer); + fail(d1 + " is formatted as " + buffer); } buffer.setLength(0); df.format(d2, buffer, new FieldPosition(0)); if (!buffer.toString().equals("-0")) { // Corrected; see 4147706 - errln(d2 + " is formatted as " + buffer); + fail(d2 + " is formatted as " + buffer); } Locale.setDefault(savedLocale); } @@ -925,40 +959,43 @@ public void Test4106658() /** * DecimalFormat.parse returns 0 if string parameter is incorrect. */ + @Test public void Test4106662() { DecimalFormat df = new DecimalFormat(); String text = "x"; ParsePosition pos1 = new ParsePosition(0), pos2 = new ParsePosition(0); - logln("pattern: \"" + df.toPattern() + "\""); + System.out.println("pattern: \"" + df.toPattern() + "\""); Number num = df.parse(text, pos1); if (num != null) { - errln("Test Failed: \"" + text + "\" is parsed as " + num); + fail("Test Failed: \"" + text + "\" is parsed as " + num); } df = null; df = new DecimalFormat("$###.00"); num = df.parse("$", pos2); if (num != null){ - errln("Test Failed: \"$\" is parsed as " + num); + fail("Test Failed: \"$\" is parsed as " + num); } } /** * NumberFormat.parse doesn't return null */ + @Test public void Test4114639() { NumberFormat format = NumberFormat.getInstance(); String text = "time 10:x"; ParsePosition pos = new ParsePosition(8); Number result = format.parse(text, pos); - if (result != null) errln("Should return null but got : " + result); // Should be null; it isn't + if (result != null) fail("Should return null but got : " + result); // Should be null; it isn't } /** * DecimalFormat.format(long n) fails if n * multiplier > MAX_LONG. */ + @Test public void Test4106664() { DecimalFormat df = new DecimalFormat(); @@ -968,13 +1005,14 @@ public void Test4106664() bigN = bigN.multiply(BigInteger.valueOf(m)); df.setMultiplier(m); df.setGroupingUsed(false); - logln("formated: " + + System.out.println("formated: " + df.format(n, new StringBuffer(), new FieldPosition(0))); - logln("expected: " + bigN.toString()); + System.out.println("expected: " + bigN.toString()); } /** * DecimalFormat.format incorrectly formats -0.0. */ + @Test public void Test4106667() { Locale savedLocale = Locale.getDefault(); @@ -982,11 +1020,11 @@ public void Test4106667() DecimalFormat df = new DecimalFormat(); df.setPositivePrefix("+"); double d = -0.0; - logln("pattern: \"" + df.toPattern() + "\""); + System.out.println("pattern: \"" + df.toPattern() + "\""); StringBuffer buffer = new StringBuffer(); df.format(d, buffer, new FieldPosition(0)); if (!buffer.toString().equals("-0")) { // Corrected; see 4147706 - errln(d + " is formatted as " + buffer); + fail(d + " is formatted as " + buffer); } Locale.setDefault(savedLocale); } @@ -994,13 +1032,14 @@ public void Test4106667() /** * DecimalFormat.setMaximumIntegerDigits() works incorrectly. */ + @Test public void Test4110936() { NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumIntegerDigits(128); - logln("setMaximumIntegerDigits(128)"); + System.out.println("setMaximumIntegerDigits(128)"); if (nf.getMaximumIntegerDigits() != 128) - errln("getMaximumIntegerDigits() returns " + + fail("getMaximumIntegerDigits() returns " + nf.getMaximumIntegerDigits()); } @@ -1011,6 +1050,7 @@ public void Test4110936() * 2) Make sure we get the same results using the generic symbol or a * hard-coded one. */ + @Test public void Test4122840() { Locale[] locales = NumberFormat.getAvailableLocales(); @@ -1027,7 +1067,7 @@ public void Test4122840() String pattern = numPatterns[1]; if (pattern.indexOf("\u00A4") == -1 ) { - errln("Currency format for " + locales[i] + + fail("Currency format for " + locales[i] + " does not contain generic currency symbol:" + pattern ); } @@ -1058,7 +1098,7 @@ public void Test4122840() String result2 = fmt2.format(1.111); if (!result1.equals(result2)) { - errln("Results for " + locales[i] + " differ: " + + fail("Results for " + locales[i] + " differ: " + result1 + " vs " + result2); } } @@ -1067,23 +1107,24 @@ public void Test4122840() /** * DecimalFormat.format() delivers wrong string. */ + @Test public void Test4125885() { Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); double rate = 12.34; DecimalFormat formatDec = new DecimalFormat ("000.00"); - logln("toPattern: " + formatDec.toPattern()); + System.out.println("toPattern: " + formatDec.toPattern()); String rateString= formatDec.format(rate); if (!rateString.equals("012.34")) - errln("result : " + rateString + " expected : 012.34"); + fail("result : " + rateString + " expected : 012.34"); rate = 0.1234; formatDec = null; formatDec = new DecimalFormat ("+000.00%;-000.00%"); - logln("toPattern: " + formatDec.toPattern()); + System.out.println("toPattern: " + formatDec.toPattern()); rateString= formatDec.format(rate); if (!rateString.equals("+012.34%")) - errln("result : " + rateString + " expected : +012.34%"); + fail("result : " + rateString + " expected : +012.34%"); Locale.setDefault(savedLocale); } @@ -1091,16 +1132,17 @@ public void Test4125885() ** * DecimalFormat produces extra zeros when formatting numbers. */ + @Test public void Test4134034() { Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); DecimalFormat nf = new DecimalFormat("##,###,###.00"); String f = nf.format(9.02); - if (f.equals("9.02")) logln(f + " ok"); else errln("9.02 -> " + f + "; want 9.02"); + if (f.equals("9.02")) System.out.println(f + " ok"); else fail("9.02 -> " + f + "; want 9.02"); f = nf.format(0); - if (f.equals(".00")) logln(f + " ok"); else errln("0 -> " + f + "; want .00"); + if (f.equals(".00")) System.out.println(f + " ok"); else fail("0 -> " + f + "; want .00"); Locale.setDefault(savedLocale); } @@ -1128,6 +1170,7 @@ public void Test4134034() { * Value 1.2 Format #0.0# Result '1.2' * Value 1.2 Format #0.00 Result '1.20' */ + @Test public void Test4134300() { Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); @@ -1142,11 +1185,11 @@ public void Test4134300() { for (int i=0; i " + s); + fail("Fail: Format empty pattern x 123.456 => " + s); s = f.format(-123.456); if (!s.equals("-123.456")) - errln("Fail: Format empty pattern x -123.456 => " + s); + fail("Fail: Format empty pattern x -123.456 => " + s); } } /** * BigDecimal numbers get their fractions truncated by NumberFormat. */ + @Test public void Test4141750() { try { String str = "12345.67"; @@ -1188,11 +1233,11 @@ public void Test4141750() { NumberFormat nf = NumberFormat.getInstance(Locale.US); String sd = nf.format(bd); if (!sd.endsWith("67")) { - errln("Fail: " + str + " x format -> " + sd); + fail("Fail: " + str + " x format -> " + sd); } } catch (Exception e) { - errln(e.toString()); + fail(e.toString()); e.printStackTrace(); } } @@ -1201,6 +1246,7 @@ public void Test4141750() { * DecimalFormat toPattern() doesn't quote special characters or handle * single quotes. */ + @Test public void Test4145457() { try { DecimalFormat nf = (DecimalFormat)NumberFormat.getInstance(); @@ -1223,25 +1269,25 @@ public void Test4145457() { double val2 = nf.parse(out2).doubleValue(); if (!pat.equals(pat2)) - errln("Fail with \"" + PATS[i] + "\": Patterns should concur, \"" + + fail("Fail with \"" + PATS[i] + "\": Patterns should concur, \"" + pat + "\" vs. \"" + pat2 + "\""); else - logln("Ok \"" + PATS[i] + "\" toPattern() -> \"" + pat + '"'); + System.out.println("Ok \"" + PATS[i] + "\" toPattern() -> \"" + pat + '"'); if (val == val2 && out.equals(out2)) { - logln("Ok " + pi + " x \"" + PATS[i] + "\" -> \"" + + System.out.println("Ok " + pi + " x \"" + PATS[i] + "\" -> \"" + out + "\" -> " + val + " -> \"" + out2 + "\" -> " + val2); } else { - errln("Fail " + pi + " x \"" + PATS[i] + "\" -> \"" + + fail("Fail " + pi + " x \"" + PATS[i] + "\" -> \"" + out + "\" -> " + val + " -> \"" + out2 + "\" -> " + val2); } } } catch (ParseException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } } @@ -1251,19 +1297,20 @@ public void Test4145457() { * CANNOT REPRODUCE * This bug is a duplicate of 4139344, which is a duplicate of 4134300 */ + @Test public void Test4147295() { DecimalFormat sdf = new DecimalFormat(); String pattern = "#,###"; - logln("Applying pattern \"" + pattern + "\""); + System.out.println("Applying pattern \"" + pattern + "\""); sdf.applyPattern(pattern); int minIntDig = sdf.getMinimumIntegerDigits(); if (minIntDig != 0) { - errln("Test failed"); - errln(" Minimum integer digits : " + minIntDig); - errln(" new pattern: " + sdf.toPattern()); + fail("Test failed" + + "\n Minimum integer digits : " + minIntDig + + "\n new pattern: " + sdf.toPattern()); } else { - logln("Test passed"); - logln(" Minimum integer digits : " + minIntDig); + System.out.println("Test passed"); + System.out.println(" Minimum integer digits : " + minIntDig); } } @@ -1271,6 +1318,7 @@ public void Test4147295() { * DecimalFormat formats -0.0 as +0.0 * See also older related bug 4106658, 4106667 */ + @Test public void Test4147706() { DecimalFormat df = new DecimalFormat("#,##0.0##"); df.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.ENGLISH)); @@ -1279,39 +1327,41 @@ public void Test4147706() { StringBuffer f1 = df.format(d1, new StringBuffer(), new FieldPosition(0)); StringBuffer f2 = df.format(d2, new StringBuffer(), new FieldPosition(0)); if (!f1.toString().equals("-0.0")) { - errln(d1 + " x \"" + df.toPattern() + "\" is formatted as \"" + f1 + '"'); + fail(d1 + " x \"" + df.toPattern() + "\" is formatted as \"" + f1 + '"'); } if (!f2.toString().equals("-0.0")) { - errln(d2 + " x \"" + df.toPattern() + "\" is formatted as \"" + f2 + '"'); + fail(d2 + " x \"" + df.toPattern() + "\" is formatted as \"" + f2 + '"'); } } /** * NumberFormat cannot format Double.MAX_VALUE */ + @Test public void Test4162198() { double dbl = Double.MAX_VALUE; NumberFormat f = NumberFormat.getInstance(); f.setMaximumFractionDigits(Integer.MAX_VALUE); f.setMaximumIntegerDigits(Integer.MAX_VALUE); String s = f.format(dbl); - logln("The number " + dbl + " formatted to " + s); + System.out.println("The number " + dbl + " formatted to " + s); Number n = null; try { n = f.parse(s); } catch (java.text.ParseException e) { - errln("Caught a ParseException:"); + fail("Caught a ParseException:"); e.printStackTrace(); } - logln("The string " + s + " parsed as " + n); + System.out.println("The string " + s + " parsed as " + n); if (n.doubleValue() != dbl) { - errln("Round trip failure"); + fail("Round trip failure"); } } /** * NumberFormat does not parse negative zero. */ + @Test public void Test4162852() throws ParseException { for (int i=0; i<2; ++i) { NumberFormat f = (i == 0) ? NumberFormat.getInstance() @@ -1319,12 +1369,12 @@ public void Test4162852() throws ParseException { double d = -0.0; String s = f.format(d); double e = f.parse(s).doubleValue(); - logln("" + + System.out.println("" + d + " -> " + '"' + s + '"' + " -> " + e); if (e != 0.0 || 1.0/e > 0.0) { - logln("Failed to parse negative zero"); + System.out.println("Failed to parse negative zero"); } } } @@ -1332,6 +1382,7 @@ public void Test4162852() throws ParseException { /** * NumberFormat truncates data */ + @Test public void Test4167494() throws Exception { NumberFormat fmt = NumberFormat.getInstance(Locale.US); @@ -1340,9 +1391,9 @@ public void Test4167494() throws Exception { double b = fmt.parse(s).doubleValue(); boolean match = a == b; if (match) { - logln("" + a + " -> \"" + s + "\" -> " + b + " ok"); + System.out.println("" + a + " -> \"" + s + "\" -> " + b + " ok"); } else { - errln("" + a + " -> \"" + s + "\" -> " + b + " FAIL"); + fail("" + a + " -> \"" + s + "\" -> " + b + " FAIL"); } // We don't test Double.MIN_VALUE because the locale data for the US @@ -1355,9 +1406,9 @@ public void Test4167494() throws Exception { b = fmt.parse(s).doubleValue(); match = a == b; if (match) { - logln("" + a + " -> \"" + s + "\" -> " + b + " ok"); + System.out.println("" + a + " -> \"" + s + "\" -> " + b + " ok"); } else { - errln("" + a + " -> \"" + s + "\" -> " + b + " FAIL"); + fail("" + a + " -> \"" + s + "\" -> " + b + " FAIL"); } } } @@ -1365,6 +1416,7 @@ public void Test4167494() throws Exception { /** * DecimalFormat.parse() fails when ParseIntegerOnly set to true */ + @Test public void Test4170798() { Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); @@ -1373,7 +1425,7 @@ public void Test4170798() { Number n = df.parse("-0.0", new ParsePosition(0)); if (!(n instanceof Long || n instanceof Integer) || n.intValue() != 0) { - errln("FAIL: parse(\"-0.0\") returns " + + fail("FAIL: parse(\"-0.0\") returns " + n + " (" + n.getClass().getName() + ')'); } Locale.setDefault(savedLocale); @@ -1382,6 +1434,7 @@ public void Test4170798() { /** * toPattern only puts the first grouping separator in. */ + @Test public void Test4176114() { String[] DATA = { "00", "#00", @@ -1398,7 +1451,7 @@ public void Test4176114() { DecimalFormat df = new DecimalFormat(DATA[i]); String s = df.toPattern(); if (!s.equals(DATA[i+1])) { - errln("FAIL: " + DATA[i] + " -> " + s + ", want " + DATA[i+1]); + fail("FAIL: " + DATA[i] + " -> " + s + ", want " + DATA[i+1]); } } } @@ -1406,6 +1459,7 @@ public void Test4176114() { /** * DecimalFormat is incorrectly rounding numbers like 1.2501 to 1.2 */ + @Test public void Test4179818() { String DATA[] = { // Input Pattern Expected output @@ -1422,14 +1476,15 @@ public void Test4179818() { fmt.applyPattern(pat); String out = fmt.format(in); if (out.equals(exp)) { - logln("Ok: " + in + " x " + pat + " = " + out); + System.out.println("Ok: " + in + " x " + pat + " = " + out); } else { - errln("FAIL: " + in + " x " + pat + " = " + out + + fail("FAIL: " + in + " x " + pat + " = " + out + ", expected " + exp); } } } + @Test public void Test4185761() throws IOException, ClassNotFoundException { /* Code used to write out the initial files, which are * then edited manually: @@ -1456,13 +1511,13 @@ public void Test4185761() throws IOException, ClassNotFoundException { ObjectInputStream p = new ObjectInputStream(istream); try { NumberFormat nf = (NumberFormat) p.readObject(); - errln("FAIL: Deserialized bogus NumberFormat int:" + + fail("FAIL: Deserialized bogus NumberFormat int:" + nf.getMinimumIntegerDigits() + ".." + nf.getMaximumIntegerDigits() + " frac:" + nf.getMinimumFractionDigits() + ".." + nf.getMaximumFractionDigits()); } catch (InvalidObjectException e) { - logln("Ok: " + e.getMessage()); + System.out.println("Ok: " + e.getMessage()); } istream.close(); @@ -1470,13 +1525,13 @@ public void Test4185761() throws IOException, ClassNotFoundException { p = new ObjectInputStream(istream); try { NumberFormat nf = (NumberFormat) p.readObject(); - errln("FAIL: Deserialized bogus DecimalFormat int:" + + fail("FAIL: Deserialized bogus DecimalFormat int:" + nf.getMinimumIntegerDigits() + ".." + nf.getMaximumIntegerDigits() + " frac:" + nf.getMinimumFractionDigits() + ".." + nf.getMaximumFractionDigits()); } catch (InvalidObjectException e) { - logln("Ok: " + e.getMessage()); + System.out.println("Ok: " + e.getMessage()); } istream.close(); } @@ -1488,6 +1543,7 @@ public void Test4185761() throws IOException, ClassNotFoundException { * symbol, percent, and permille. This is filed as bugs 4212072 and * 4212073. */ + @Test public void Test4212072() throws IOException, ClassNotFoundException { DecimalFormatSymbols sym = DecimalFormatSymbols.getInstance(Locale.US); DecimalFormat fmt = new DecimalFormat("#", sym); @@ -1495,11 +1551,11 @@ public void Test4212072() throws IOException, ClassNotFoundException { sym.setMinusSign('^'); fmt.setDecimalFormatSymbols(sym); if (!fmt.format(-1).equals("^1")) { - errln("FAIL: -1 x (minus=^) -> " + fmt.format(-1) + + fail("FAIL: -1 x (minus=^) -> " + fmt.format(-1) + ", exp ^1"); } if (!fmt.getNegativePrefix().equals("^")) { - errln("FAIL: (minus=^).getNegativePrefix -> " + + fail("FAIL: (minus=^).getNegativePrefix -> " + fmt.getNegativePrefix() + ", exp ^"); } sym.setMinusSign('-'); @@ -1508,11 +1564,11 @@ public void Test4212072() throws IOException, ClassNotFoundException { sym.setPercent('^'); fmt.setDecimalFormatSymbols(sym); if (!fmt.format(0.25).equals("25^")) { - errln("FAIL: 0.25 x (percent=^) -> " + fmt.format(0.25) + + fail("FAIL: 0.25 x (percent=^) -> " + fmt.format(0.25) + ", exp 25^"); } if (!fmt.getPositiveSuffix().equals("^")) { - errln("FAIL: (percent=^).getPositiveSuffix -> " + + fail("FAIL: (percent=^).getPositiveSuffix -> " + fmt.getPositiveSuffix() + ", exp ^"); } sym.setPercent('%'); @@ -1521,11 +1577,11 @@ public void Test4212072() throws IOException, ClassNotFoundException { sym.setPerMill('^'); fmt.setDecimalFormatSymbols(sym); if (!fmt.format(0.25).equals("250^")) { - errln("FAIL: 0.25 x (permill=^) -> " + fmt.format(0.25) + + fail("FAIL: 0.25 x (permill=^) -> " + fmt.format(0.25) + ", exp 250^"); } if (!fmt.getPositiveSuffix().equals("^")) { - errln("FAIL: (permill=^).getPositiveSuffix -> " + + fail("FAIL: (permill=^).getPositiveSuffix -> " + fmt.getPositiveSuffix() + ", exp ^"); } sym.setPerMill('\u2030'); @@ -1534,11 +1590,11 @@ public void Test4212072() throws IOException, ClassNotFoundException { sym.setCurrencySymbol("usd"); fmt.setDecimalFormatSymbols(sym); if (!fmt.format(12.5).equals("usd12.50")) { - errln("FAIL: 12.5 x (currency=usd) -> " + fmt.format(12.5) + + fail("FAIL: 12.5 x (currency=usd) -> " + fmt.format(12.5) + ", exp usd12.50"); } if (!fmt.getPositivePrefix().equals("usd")) { - errln("FAIL: (currency=usd).getPositivePrefix -> " + + fail("FAIL: (currency=usd).getPositivePrefix -> " + fmt.getPositivePrefix() + ", exp usd"); } sym.setCurrencySymbol("$"); @@ -1547,11 +1603,11 @@ public void Test4212072() throws IOException, ClassNotFoundException { sym.setInternationalCurrencySymbol("DOL"); fmt.setDecimalFormatSymbols(sym); if (!fmt.format(12.5).equals("DOL12.50")) { - errln("FAIL: 12.5 x (intlcurrency=DOL) -> " + fmt.format(12.5) + + fail("FAIL: 12.5 x (intlcurrency=DOL) -> " + fmt.format(12.5) + ", exp DOL12.50"); } if (!fmt.getPositivePrefix().equals("DOL")) { - errln("FAIL: (intlcurrency=DOL).getPositivePrefix -> " + + fail("FAIL: (intlcurrency=DOL).getPositivePrefix -> " + fmt.getPositivePrefix() + ", exp DOL"); } sym.setInternationalCurrencySymbol("USD"); @@ -1580,7 +1636,7 @@ public void Test4212072() throws IOException, ClassNotFoundException { DecimalFormatSymbols symb = DecimalFormatSymbols.getInstance(avail[i]); DecimalFormat f2 = new DecimalFormat(pat, symb); if (!df.equals(f2)) { - errln("FAIL: " + avail[i] + " -> \"" + pat + + fail("FAIL: " + avail[i] + " -> \"" + pat + "\" -> \"" + f2.toPattern() + '"'); } @@ -1588,7 +1644,7 @@ public void Test4212072() throws IOException, ClassNotFoundException { pat = df.toLocalizedPattern(); f2.applyLocalizedPattern(pat); if (!df.equals(f2)) { - errln("FAIL: " + avail[i] + " -> localized \"" + pat + + fail("FAIL: " + avail[i] + " -> localized \"" + pat + "\" -> \"" + f2.toPattern() + '"'); } @@ -1603,7 +1659,7 @@ public void Test4212072() throws IOException, ClassNotFoundException { new ObjectInputStream(new ByteArrayInputStream(bytes)); f2 = (DecimalFormat) ois.readObject(); if (!df.equals(f2)) { - errln("FAIL: Stream in/out " + avail[i] + " -> \"" + pat + + fail("FAIL: Stream in/out " + avail[i] + " -> \"" + pat + "\" -> " + (f2 != null ? ("\""+f2.toPattern()+'"') : "null")); } @@ -1615,6 +1671,7 @@ public void Test4212072() throws IOException, ClassNotFoundException { /** * DecimalFormat.parse() fails for mulipliers 2^n. */ + @Test public void Test4216742() throws ParseException { DecimalFormat fmt = (DecimalFormat) NumberFormat.getInstance(Locale.US); long[] DATA = { Long.MIN_VALUE, Long.MAX_VALUE, -100000000L, 100000000L}; @@ -1624,7 +1681,7 @@ public void Test4216742() throws ParseException { fmt.setMultiplier(m); long n = fmt.parse(str).longValue(); if (n > 0 != DATA[i] > 0) { - errln("\"" + str + "\" parse(x " + fmt.getMultiplier() + + fail("\"" + str + "\" parse(x " + fmt.getMultiplier() + ") => " + n); } } @@ -1635,6 +1692,7 @@ public void Test4216742() throws ParseException { * DecimalFormat formats 1.001 to "1.00" instead of "1" with 2 fraction * digits. */ + @Test public void Test4217661() { Object[] DATA = { 0.001, "0", @@ -1647,7 +1705,7 @@ public void Test4217661() { for (int i=0; i 0 && args[0].equals("-debug")) { - DEBUG = true; - String[] newargs = new String[args.length - 1]; - System.arraycopy(args, 1, newargs, 0, newargs.length); - args = newargs; - } - new NumberRoundTrip().run(args); - } - + @Test public void TestNumberFormatRoundTrip() { - logln("Default Locale"); + System.out.println("Default Locale"); localeName = "Default Locale"; formatName = "getInstance"; doTest(NumberFormat.getInstance()); @@ -74,7 +70,7 @@ public void TestNumberFormatRoundTrip() { Locale[] loc = NumberFormat.getAvailableLocales(); for (int i=0; i " + escape(s)); + System.out.println(" " + value + " F> " + escape(s)); n = fmt.parse(s); - if (DEBUG) logln(" " + escape(s) + " P> " + n); + System.out.println(" " + escape(s) + " P> " + n); s2 = fmt.format(n); - if (DEBUG) logln(" " + n + " F> " + escape(s2)); + System.out.println(" " + n + " F> " + escape(s2)); if (STRING_COMPARE) { if (!s.equals(s2)) { if (fmt instanceof DecimalFormat) { - logln("Text mismatch: expected: " + s + ", got: " + s2 + " --- Try BigDecimal parsing."); + System.out.println("Text mismatch: expected: " + s + ", got: " + s2 + " --- Try BigDecimal parsing."); ((DecimalFormat)fmt).setParseBigDecimal(true); n = fmt.parse(s); - if (DEBUG) logln(" " + escape(s) + " P> " + n); + System.out.println(" " + escape(s) + " P> " + n); s2 = fmt.format(n); - if (DEBUG) logln(" " + n + " F> " + escape(s2)); + System.out.println(" " + n + " F> " + escape(s2)); ((DecimalFormat)fmt).setParseBigDecimal(false); if (!s.equals(s2)) { @@ -197,14 +193,14 @@ public void doTest(NumberFormat fmt, Number value) { n + typeOf(n) + " F> " + escape(s2); if (err.length() > 0) { - errln("*** " + err + " with " + + fail("*** " + err + " with " + formatName + " in " + localeName + " " + message); } else { - logln(message); + System.out.println(message); } } catch (ParseException e) { - errln("*** " + e.toString() + " with " + + fail("*** " + e.toString() + " with " + formatName + " in " + localeName); } } diff --git a/test/jdk/java/text/Format/NumberFormat/NumberTest.java b/test/jdk/java/text/Format/NumberFormat/NumberTest.java index fd78223ccca..fc24322ada9 100644 --- a/test/jdk/java/text/Format/NumberFormat/NumberTest.java +++ b/test/jdk/java/text/Format/NumberFormat/NumberTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,24 +25,24 @@ * @test * @bug 4122840 4135202 4408066 4838107 8008577 * @summary test NumberFormat - * @library /java/text/testlib * @modules java.base/sun.util.resources * jdk.localedata * @compile -XDignore.symbol.file NumberTest.java - * @run main/othervm -Djava.locale.providers=COMPAT,SPI NumberTest + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI NumberTest */ import java.util.*; import java.text.*; import sun.util.resources.LocaleData; -public class NumberTest extends IntlTest -{ - public static void main(String[] args) throws Exception { - new NumberTest().run(args); - } +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.fail; + +public class NumberTest +{ // Test pattern handling + @Test public void TestPatterns() { DecimalFormatSymbols sym = DecimalFormatSymbols.getInstance(Locale.US); @@ -54,20 +54,21 @@ public void TestPatterns() DecimalFormat fmt = new DecimalFormat(pat[i], sym); String newp = fmt.toPattern(); if (!newp.equals(newpat[i])) - errln("FAIL: Pattern " + pat[i] + " should transmute to " + newpat[i] + + fail("FAIL: Pattern " + pat[i] + " should transmute to " + newpat[i] + "; " + newp + " seen instead"); String s = fmt.format(0); if (!s.equals(num[i])) { - errln("FAIL: Pattern " + pat[i] + " should format zero as " + num[i] + + fail("FAIL: Pattern " + pat[i] + " should format zero as " + num[i] + "; " + s + " seen instead"); - logln("Min integer digits = " + fmt.getMinimumIntegerDigits()); + System.out.println("Min integer digits = " + fmt.getMinimumIntegerDigits()); } } } // Test exponential pattern + @Test public void TestExponential() { DecimalFormatSymbols sym = DecimalFormatSymbols.getInstance(Locale.US); String pat[] = { "0.####E0", "00.000E00", "##0.####E000", "0.###E0;[0.###E0]" }; @@ -100,14 +101,14 @@ public void TestExponential() { int ival = 0, ilval = 0; for (int p=0; p \"" + + System.out.println("Pattern \"" + pat[p] + "\" -toPattern-> \"" + fmt.toPattern() + '"'); for (int v=0; v " + escape(s)); + System.out.println(" Format " + val[v] + " -> " + escape(s)); if (!s.equals(valFormat[v+ival])) { - errln("FAIL: Expected " + valFormat[v+ival] + + fail("FAIL: Expected " + valFormat[v+ival] + ", got " + s + ", pattern=" + fmt.toPattern()); } @@ -115,22 +116,22 @@ public void TestExponential() { ParsePosition pos = new ParsePosition(0); Number a = fmt.parse(s, pos); if (pos.getIndex() == s.length()) { - logln(" Parse -> " + a); + System.out.println(" Parse -> " + a); if (a.doubleValue() != valParse[v+ival]) { - errln("FAIL: Expected " + valParse[v+ival] + + fail("FAIL: Expected " + valParse[v+ival] + ", got " + a.doubleValue() + ", pattern=" + fmt.toPattern()); } } else { - errln(" FAIL: Partial parse (" + pos.getIndex() + + fail(" FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + a); } } for (int v=0; v " + escape(s)); + System.out.println(" Format " + lval[v] + "L -> " + escape(s)); if (!s.equals(lvalFormat[v+ilval])) { - errln("ERROR: Expected " + lvalFormat[v+ilval] + + fail("ERROR: Expected " + lvalFormat[v+ilval] + ", got " + s + ", pattern=" + fmt.toPattern()); } @@ -138,14 +139,14 @@ public void TestExponential() { ParsePosition pos = new ParsePosition(0); Number a = fmt.parse(s, pos); if (pos.getIndex() == s.length()) { - logln(" Parse -> " + a); + System.out.println(" Parse -> " + a); if (a.longValue() != lvalParse[v+ilval]) { - errln("FAIL: Expected " + lvalParse[v+ilval] + + fail("FAIL: Expected " + lvalParse[v+ilval] + ", got " + a + ", pattern=" + fmt.toPattern()); } } else { - errln(" FAIL: Partial parse (" + pos.getIndex() + + fail(" FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + a); } } @@ -155,24 +156,26 @@ public void TestExponential() { } // Test the handling of quotes + @Test public void TestQuotes() { String pat; DecimalFormatSymbols sym = DecimalFormatSymbols.getInstance(Locale.US); DecimalFormat fmt = new DecimalFormat(pat = "a'fo''o'b#", sym); String s = fmt.format(123); - logln("Pattern \"" + pat + "\""); - logln(" Format 123 -> " + escape(s)); - if (!s.equals("afo'ob123")) errln("FAIL: Expected afo'ob123"); + System.out.println("Pattern \"" + pat + "\""); + System.out.println(" Format 123 -> " + escape(s)); + if (!s.equals("afo'ob123")) fail("FAIL: Expected afo'ob123"); fmt = new DecimalFormat(pat = "a''b#", sym); s = fmt.format(123); - logln("Pattern \"" + pat + "\""); - logln(" Format 123 -> " + escape(s)); - if (!s.equals("a'b123")) errln("FAIL: Expected a'b123"); + System.out.println("Pattern \"" + pat + "\""); + System.out.println(" Format 123 -> " + escape(s)); + if (!s.equals("a'b123")) fail("FAIL: Expected a'b123"); } // Test the use of the currency sign + @Test public void TestCurrencySign() { DecimalFormatSymbols sym = DecimalFormatSymbols.getInstance(Locale.US); @@ -181,21 +184,21 @@ public void TestCurrencySign() // DecimalFormatSymbols sym = fmt.getDecimalFormatSymbols(); String s = fmt.format(1234.56); - logln("Pattern \"" + fmt.toPattern() + "\""); - logln(" Format " + 1234.56 + " -> " + escape(s)); - if (!s.equals("$1,234.56")) errln("FAIL: Expected $1,234.56"); + System.out.println("Pattern \"" + fmt.toPattern() + "\""); + System.out.println(" Format " + 1234.56 + " -> " + escape(s)); + if (!s.equals("$1,234.56")) fail("FAIL: Expected $1,234.56"); s = fmt.format(-1234.56); - logln(" Format " + -1234.56 + " -> " + escape(s)); - if (!s.equals("-$1,234.56")) errln("FAIL: Expected -$1,234.56"); + System.out.println(" Format " + -1234.56 + " -> " + escape(s)); + if (!s.equals("-$1,234.56")) fail("FAIL: Expected -$1,234.56"); fmt = new DecimalFormat("\u00A4\u00A4 #,##0.00;\u00A4\u00A4 -#,##0.00", sym); s = fmt.format(1234.56); - logln("Pattern \"" + fmt.toPattern() + "\""); - logln(" Format " + 1234.56 + " -> " + escape(s)); - if (!s.equals("USD 1,234.56")) errln("FAIL: Expected USD 1,234.56"); + System.out.println("Pattern \"" + fmt.toPattern() + "\""); + System.out.println(" Format " + 1234.56 + " -> " + escape(s)); + if (!s.equals("USD 1,234.56")) fail("FAIL: Expected USD 1,234.56"); s = fmt.format(-1234.56); - logln(" Format " + -1234.56 + " -> " + escape(s)); - if (!s.equals("USD -1,234.56")) errln("FAIL: Expected USD -1,234.56"); + System.out.println(" Format " + -1234.56 + " -> " + escape(s)); + if (!s.equals("USD -1,234.56")) fail("FAIL: Expected USD -1,234.56"); } static String escape(String s) { @@ -219,25 +222,26 @@ static String escape(String s) // Test simple currency format // Bug 4024941; this code used to throw a NumberFormat exception + @Test public void TestCurrency() { NumberFormat currencyFmt = NumberFormat.getCurrencyInstance(Locale.CANADA_FRENCH); String s = currencyFmt.format(1.50); - logln("Un pauvre ici a..........." + s); + System.out.println("Un pauvre ici a..........." + s); if (!s.equals("1,50 $")) { - errln("FAIL: Expected 1,50 $; got " + s + "; "+ dumpFmt(currencyFmt)); + fail("FAIL: Expected 1,50 $; got " + s + "; "+ dumpFmt(currencyFmt)); } currencyFmt = NumberFormat.getCurrencyInstance(Locale.GERMANY); s = currencyFmt.format(1.50); - logln("Un pauvre en Allemagne a.." + s); + System.out.println("Un pauvre en Allemagne a.." + s); if (!s.equals("1,50 \u20AC")) { - errln("FAIL: Expected 1,50 \u20AC; got " + s + "; " + dumpFmt(currencyFmt)); + fail("FAIL: Expected 1,50 \u20AC; got " + s + "; " + dumpFmt(currencyFmt)); } currencyFmt = NumberFormat.getCurrencyInstance(Locale.FRANCE); s = currencyFmt.format(1.50); - logln("Un pauvre en France a....." + s); + System.out.println("Un pauvre en France a....." + s); if (!s.equals("1,50 \u20AC")) { - errln("FAIL: Expected 1,50 \u20AC; got " + s + "; " + dumpFmt(currencyFmt)); + fail("FAIL: Expected 1,50 \u20AC; got " + s + "; " + dumpFmt(currencyFmt)); } } @@ -254,18 +258,20 @@ String dumpFmt(NumberFormat numfmt) { // Test numeric parsing // Bug 4059870 + @Test public void TestParse() { String arg = "0"; java.text.DecimalFormat format = new java.text.DecimalFormat("00"); try { Number n = format.parse(arg); - logln("parse(" + arg + ") = " + n); - if (n.doubleValue() != 0.0) errln("FAIL: Expected 0"); - } catch (Exception e) { errln("Exception caught: " + e); } + System.out.println("parse(" + arg + ") = " + n); + if (n.doubleValue() != 0.0) fail("FAIL: Expected 0"); + } catch (Exception e) { fail("Exception caught: " + e); } } // Test rounding + @Test public void TestRounding487() { NumberFormat nf = NumberFormat.getInstance(Locale.US); roundingTest(nf, 0.00159999, 4, "0.0016"); @@ -278,9 +284,9 @@ public void TestRounding487() { void roundingTest(NumberFormat nf, double x, int maxFractionDigits, String expected) { nf.setMaximumFractionDigits(maxFractionDigits); String out = nf.format(x); - logln("" + x + " formats with " + maxFractionDigits + " fractional digits to " + out); + System.out.println("" + x + " formats with " + maxFractionDigits + " fractional digits to " + out); if (!out.equals(expected)) { - errln("FAIL: Expected " + expected + ", got " + out); + fail("FAIL: Expected " + expected + ", got " + out); } } @@ -292,6 +298,7 @@ void roundingTest(NumberFormat nf, double x, int maxFractionDigits, String expec * a couple. * @see java.lang.Character#isDigit(char) */ + @Test public void TestUnicodeDigits() { char[] zeros = { 0x0030, // ISO-LATIN-1 digits ('0' through '9') @@ -324,9 +331,9 @@ public void TestUnicodeDigits() { } catch (ParseException e) { n = -2; } if (n != 314) - errln("Can't parse Unicode " + Integer.toHexString(zero) + " as digit (" + n + ")"); + fail("Can't parse Unicode " + Integer.toHexString(zero) + " as digit (" + n + ")"); else - logln("Parse digit " + Integer.toHexString(zero) + " ok"); + System.out.println("Parse digit " + Integer.toHexString(zero) + " ok"); } } @@ -334,6 +341,7 @@ public void TestUnicodeDigits() { * Bug 4122840 * Make sure that the currency symbol is not hard-coded in any locale. */ + @Test public void TestCurrencySubstitution() { final String SYM = ""; final String INTL_SYM = ""; @@ -356,36 +364,37 @@ public void TestCurrencySubstitution() { String customPos = df.format(1234.5678); String customNeg = df.format(-1234.5678); if (genericPos.equals(customPos) || genericNeg.equals(customNeg)) { - errln("FAIL: " + locales[i] + + fail("FAIL: " + locales[i] + " not using currency symbol substitution: " + genericPos); } else { if (customPos.indexOf(SYM) >= 0) { if (customNeg.indexOf(INTL_SYM) >= 0) - errln("Fail: Positive and negative patterns use different symbols"); + fail("Fail: Positive and negative patterns use different symbols"); else - logln("Ok: " + locales[i] + + System.out.println("Ok: " + locales[i] + " uses currency symbol: " + genericPos + ", " + customPos); } else if (customPos.indexOf(INTL_SYM) >= 0) { if (customNeg.indexOf(SYM) >= 0) - errln("Fail: Positive and negative patterns use different symbols"); + fail("Fail: Positive and negative patterns use different symbols"); else - logln("Ok: " + locales[i] + + System.out.println("Ok: " + locales[i] + " uses intl. currency symbol: " + genericPos + ", " + customPos); } else { - errln("FAIL: " + locales[i] + + fail("FAIL: " + locales[i] + " contains no currency symbol (impossible!)"); } } } - else logln("Skipping " + locales[i] + "; not a DecimalFormat"); + else System.out.println("Skipping " + locales[i] + "; not a DecimalFormat"); } } + @Test public void TestIntegerFormat() throws ParseException { NumberFormat format = NumberFormat.getIntegerInstance(Locale.GERMANY); @@ -395,7 +404,7 @@ public void TestIntegerFormat() throws ParseException { for (int i = 0; i < formatInput.length; i++) { String result = format.format(formatInput[i]); if (!result.equals(formatExpected[i])) { - errln("FAIL: Expected " + formatExpected[i] + ", got " + result); + fail("FAIL: Expected " + formatExpected[i] + ", got " + result); } } @@ -405,7 +414,7 @@ public void TestIntegerFormat() throws ParseException { for (int i = 0; i < parseInput.length; i++) { float result = format.parse(parseInput[i]).floatValue(); if (result != parseExpected[i]) { - errln("FAIL: Expected " + parseExpected[i] + ", got " + result); + fail("FAIL: Expected " + parseExpected[i] + ", got " + result); } } } diff --git a/test/jdk/java/text/Format/NumberFormat/PositionTest.java b/test/jdk/java/text/Format/NumberFormat/PositionTest.java index 31a5a3dbebd..d916e0ab1ed 100644 --- a/test/jdk/java/text/Format/NumberFormat/PositionTest.java +++ b/test/jdk/java/text/Format/NumberFormat/PositionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,8 +24,8 @@ /** * @test * @bug 4109023 4153060 4153061 - * @library /java/text/testlib * @summary test ParsePosition and FieldPosition + * @run junit PositionTest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -42,33 +42,34 @@ import java.text.*; import java.io.*; -public class PositionTest extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new PositionTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class PositionTest { + @Test public void TestParsePosition() { ParsePosition pp1 = new ParsePosition(0); if (pp1.getIndex() == 0) { - logln("PP constructor() tested."); + System.out.println("PP constructor() tested."); }else{ - errln("*** PP getIndex or constructor() result"); + fail("*** PP getIndex or constructor() result"); } { int to = 5; ParsePosition pp2 = new ParsePosition ( to ); if (pp2.getIndex() == 5) { - logln("PP getIndex and constructor(TextOffset) tested."); + System.out.println("PP getIndex and constructor(TextOffset) tested."); }else{ - errln("*** PP getIndex or constructor(TextOffset) result"); + fail("*** PP getIndex or constructor(TextOffset) result"); } pp2.setIndex( 3 ); if (pp2.getIndex() == 3) { - logln("PP setIndex tested."); + System.out.println("PP setIndex tested."); }else{ - errln("*** PP getIndex or setIndex result"); + fail("*** PP getIndex or setIndex result"); } } @@ -77,37 +78,38 @@ public void TestParsePosition() { pp3 = new ParsePosition( 5 ); ParsePosition pp4 = new ParsePosition(5); if (! pp2.equals(pp3)) { - logln("PP not equals tested."); + System.out.println("PP not equals tested."); }else{ - errln("*** PP not equals fails"); + fail("*** PP not equals fails"); } if (pp3.equals(pp4)) { - logln("PP equals tested."); + System.out.println("PP equals tested."); }else{ - errln("*** PP equals fails (" + pp3.getIndex() + " != " + pp4.getIndex() + ")"); + fail("*** PP equals fails (" + pp3.getIndex() + " != " + pp4.getIndex() + ")"); } ParsePosition pp5; pp5 = pp4; if (pp4.equals(pp5)) { - logln("PP operator= tested."); + System.out.println("PP operator= tested."); }else{ - errln("*** PP operator= operator== or operator != result"); + fail("*** PP operator= operator== or operator != result"); } } + @Test public void TestFieldPosition() { FieldPosition fp = new FieldPosition( 7 ); if (fp.getField() == 7) { - logln("FP constructor(int) and getField tested."); + System.out.println("FP constructor(int) and getField tested."); }else{ - errln("*** FP constructor(int) or getField"); + fail("*** FP constructor(int) or getField"); } FieldPosition fph = new FieldPosition( 3 ); - if ( fph.getField() != 3) errln("*** FP getField or heap constr."); + if ( fph.getField() != 3) fail("*** FP getField or heap constr."); boolean err1 = false; boolean err2 = false; @@ -121,24 +123,25 @@ public void TestFieldPosition() { // if (fp.getEndIndex() != i+7) err3 = true; // } if (!err1) { - logln("FP setField and getField tested."); + System.out.println("FP setField and getField tested."); }else{ - errln("*** FP setField or getField"); + fail("*** FP setField or getField"); } if (!err2) { - logln("FP setBeginIndex and getBeginIndex tested."); + System.out.println("FP setBeginIndex and getBeginIndex tested."); }else{ - errln("*** FP setBeginIndex or getBeginIndex"); + fail("*** FP setBeginIndex or getBeginIndex"); } if (!err3) { - logln("FP setEndIndex and getEndIndex tested."); + System.out.println("FP setEndIndex and getEndIndex tested."); }else{ - errln("*** FP setEndIndex or getEndIndex"); + fail("*** FP setEndIndex or getEndIndex"); } - logln(""); + System.out.println(""); } + @Test public void TestFieldPosition_example() { //***** no error detection yet !!!!!!! //***** this test is for compiler checks and visual verification only. @@ -164,41 +167,43 @@ public void TestFieldPosition_example() { tempLen : (tempLen - pos.getEndIndex()); for (int j=0; j contents = parser.parse(new BufferedReader( new FileReader(file))); List test = (List)contents.get("tests"); for (int counter = 0; counter < test.size(); counter++) { - logln("creating: " + (counter / 2)); + System.out.println("creating: " + (counter / 2)); AttributedCharacterIterator iterator = create((Map)test.get(counter)); - logln("verifying: " + (counter / 2)); + System.out.println("verifying: " + (counter / 2)); verify(iterator, (Map)test.get(++counter)); } } catch (IOException ioe) { - errln("Error reading: " + ioe); + fail("Error reading: " + ioe); } } @@ -175,20 +169,20 @@ public void verify(AttributedCharacterIterator iterator,Map table escapeIfNecessary((String)table.get("text")))) { String text = getText(iterator); - errln("text doesn't match, got: " + getText(iterator)); + fail("text doesn't match, got: " + getText(iterator)); } if (iterator.getBeginIndex() != 0) { - errln("Bogus start: " + iterator.getBeginIndex()); + fail("Bogus start: " + iterator.getBeginIndex()); } if (iterator.getEndIndex() != length) { - errln("Bogus end: " + iterator.getEndIndex()); + fail("Bogus end: " + iterator.getEndIndex()); } for (int counter = 0; counter < length; counter++) { iterator.setIndex(counter); if (!verifyAttributes(iterator.getAttributes().keySet(), makeAttributes((List)table.get(Integer. toString(counter))))) { - errln("Attributes don't match at " + counter + " expecting " + + fail("Attributes don't match at " + counter + " expecting " + makeAttributes((List)table.get(Integer.toString (counter))) + " got " + iterator.getAttributes().keySet()); @@ -199,7 +193,7 @@ public void verify(AttributedCharacterIterator iterator,Map table if (!verifyAttributes(iterator.getAttributes().keySet(), makeAttributes((List)table.get(Integer. toString(counter))))) { - errln("Attributes don't match at " + counter + " expecting " + + fail("Attributes don't match at " + counter + " expecting " + makeAttributes((List)table.get(Integer.toString (counter))) + " got " + iterator.getAttributes().keySet()); @@ -243,22 +237,22 @@ private void verifyLimit(AttributedCharacterIterator iterator, for (int counter = begin; counter < end; counter++) { iterator.setIndex(counter); if (iterator.getRunStart() != begin) { - errln("Begin doesn't match want " + begin + " got " + + fail("Begin doesn't match want " + begin + " got " + iterator.getRunStart() + " at " + counter + " attrs " + attrs); } if (iterator.getRunStart(attrs) != begin2) { - errln("Begin2 doesn't match want " + begin2 + " got " + + fail("Begin2 doesn't match want " + begin2 + " got " + iterator.getRunStart(attrs) + " at " + counter + " attrs " + attrs); } if (iterator.getRunLimit() != end) { - errln("End doesn't match want " + end + " got " + + fail("End doesn't match want " + end + " got " + iterator.getRunLimit() + " at " + counter + " attrs " + attrs); } if (iterator.getRunLimit(attrs) != end2) { - errln("End2 doesn't match want " + end2 + " got " + + fail("End2 doesn't match want " + end2 + " got " + iterator.getRunLimit(attrs) + " at " + counter + " attrs " + attrs); } @@ -312,15 +306,15 @@ private void verifyFieldPosition(FieldPosition fp, int begin, int end, format.format(value, buffer, fp); if (fp.getBeginIndex() != begin) { - errln("bogus begin want " + begin + " got " + fp.getBeginIndex() + + fail("bogus begin want " + begin + " got " + fp.getBeginIndex() + " for " + fp + " at " + index); } if (fp.getEndIndex() != end) { - errln("bogus end want " + end + " got " + fp.getEndIndex() + + fail("bogus end want " + end + " got " + fp.getEndIndex() + " for " + fp + " at " + index); } if (!buffer.toString().equals(text)) { - errln("Text does not match, want !" + buffer.toString() + + fail("Text does not match, want !" + buffer.toString() + "! got !" + text + "!"); } } @@ -331,11 +325,11 @@ public AttributedCharacterIterator create(Map table) { value = createInstance((String)table.get("valueClass"), ((List)table.get("valueArgs")).toArray()); - logln("Created format: " + format + " value " + value); + System.out.println("Created format: " + format + " value " + value); AttributedCharacterIterator aci = format. formatToCharacterIterator(value); - logln("Obtained Iterator: " + aci); + System.out.println("Obtained Iterator: " + aci); return aci; } @@ -373,7 +367,7 @@ private Object createInstance(String className, Object[] args) { return value; } } catch (Throwable th) { - errln("Error creating instance " + th); + fail("Error creating instance " + th); return null; } } @@ -413,7 +407,7 @@ private Object lookupField(String name) { } catch (Throwable th) { error = th; } - errln("Could not lookup field " + name + " " + error); + fail("Could not lookup field " + name + " " + error); return null; } diff --git a/test/jdk/java/text/Normalizer/ICUBasicTest.java b/test/jdk/java/text/Normalizer/ICUBasicTest.java index 206291b99a7..62761a2f545 100644 --- a/test/jdk/java/text/Normalizer/ICUBasicTest.java +++ b/test/jdk/java/text/Normalizer/ICUBasicTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,9 +26,8 @@ * @summary Confirm Normalizer's fundamental behavior. Imported from ICU4J 3.2's * src/com/ibm/icu/dev/test and modified. * @modules java.base/sun.text java.base/jdk.internal.icu.text - * @library /java/text/testlib * @compile -XDignore.symbol.file ICUBasicTest.java - * @run main/timeout=30 ICUBasicTest + * @run junit/timeout=30 ICUBasicTest */ /* @@ -45,11 +44,11 @@ import static java.text.Normalizer.Form.*; -public class ICUBasicTest extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new ICUBasicTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class ICUBasicTest { /* * Normalization modes @@ -77,6 +76,7 @@ public static void main(String[] args) throws Exception { * PRI #29 is supported in Unicode 4.1.0. Therefore, expected results are * different for earlier Unicode versions. */ + @Test public void TestComposition() { final TestCompositionCase cases[] = new TestCompositionCase[] { @@ -116,10 +116,7 @@ public void TestComposition() { output = Normalizer.normalize(cases[i].input, cases[i].form, cases[i].options); if (!output.equals(cases[i].expect)) { - errln("unexpected result for case " + i + ". Expected=" - + cases[i].expect + ", Actual=" + output); - } else if (verbose) { - logln("expected result for case " + i + ". Expected=" + fail("unexpected result for case " + i + ". Expected=" + cases[i].expect + ", Actual=" + output); } } @@ -144,13 +141,14 @@ private final static class TestCompositionCase { /* * Added in order to detect a regression. */ + @Test public void TestCombiningMarks() { String src = "\u0f71\u0f72\u0f73\u0f74\u0f75"; String expected = "\u0F71\u0F71\u0F71\u0F72\u0F72\u0F74\u0F74"; String result = NormalizerBase.normalize(src, NFD); if (!expected.equals(result)) { - errln("Reordering of combining marks failed. Expected: " + + fail("Reordering of combining marks failed. Expected: " + HexFormat.of().withDelimiter(" ").formatHex(expected.getBytes()) + " Got: "+ HexFormat.of().withDelimiter(" ").formatHex(result.getBytes())); } @@ -159,12 +157,13 @@ public void TestCombiningMarks() { /* * Added in order to detect a regression. */ + @Test public void TestBengali() throws Exception { String input = "\u09bc\u09be\u09cd\u09be"; String output=NormalizerBase.normalize(input, NFC); if (!input.equals(output)) { - errln("ERROR in NFC of string"); + fail("ERROR in NFC of string"); } return; } @@ -178,6 +177,7 @@ public void TestBengali() throws Exception { * characters at the start of a string are not put in canonical * order correctly by compose() if there is no starter. */ + @Test public void TestVerisign() throws Exception { String[] inputs = { "\u05b8\u05b9\u05b1\u0591\u05c3\u05b0\u05ac\u059f", @@ -194,7 +194,7 @@ public void TestVerisign() throws Exception { String result = NormalizerBase.normalize(input, NFD); if (!result.equals(output)) { - errln("FAIL input: " + HexFormat.of().withDelimiter(" ") + fail("FAIL input: " + HexFormat.of().withDelimiter(" ") .formatHex(input.getBytes()) + "\n" + " decompose: " + HexFormat.of().withDelimiter(" ") .formatHex(result.getBytes()) + "\n" + @@ -204,7 +204,7 @@ public void TestVerisign() throws Exception { result = NormalizerBase.normalize(input, NFC); if (!result.equals(output)) { - errln("FAIL input: " + HexFormat.of().withDelimiter(" ") + fail("FAIL input: " + HexFormat.of().withDelimiter(" ") .formatHex(input.getBytes()) + "\n" + " compose: " + HexFormat.of().withDelimiter(" ") .formatHex(output.getBytes()) + "\n" + @@ -223,6 +223,7 @@ public void TestVerisign() throws Exception { * map to the same canonical class, which is not the case, in * reality. */ + @Test public void TestZeroIndex() throws Exception { String[] DATA = { // Expect col1 x COMPOSE_COMPAT => col2 @@ -240,12 +241,12 @@ public void TestZeroIndex() throws Exception { String exp = DATA[i+1]; if (b.equals(exp)) { - logln("Ok: " + HexFormat.of().withDelimiter(" ") + System.out.println("Ok: " + HexFormat.of().withDelimiter(" ") .formatHex(a.getBytes()) + " x COMPOSE_COMPAT => " + HexFormat.of().withDelimiter(" ") .formatHex(b.getBytes())); } else { - errln("FAIL: " + HexFormat.of().withDelimiter(" ") + fail("FAIL: " + HexFormat.of().withDelimiter(" ") .formatHex(b.getBytes()) + " x COMPOSE_COMPAT => " + HexFormat.of().withDelimiter(" ") .formatHex(a.getBytes()) + ", expect " + @@ -256,10 +257,10 @@ public void TestZeroIndex() throws Exception { a = NormalizerBase.normalize(b, NFD); exp = DATA[i+2]; if (a.equals(exp)) { - logln("Ok: " + HexFormat.of().withDelimiter(" ").formatHex(b.getBytes()) + " x DECOMP => " + + System.out.println("Ok: " + HexFormat.of().withDelimiter(" ").formatHex(b.getBytes()) + " x DECOMP => " + HexFormat.of().withDelimiter(" ").formatHex(a.getBytes())); } else { - errln("FAIL: " + HexFormat.of().withDelimiter(" ").formatHex(b.getBytes()) + " x DECOMP => " + + fail("FAIL: " + HexFormat.of().withDelimiter(" ").formatHex(b.getBytes()) + " x DECOMP => " + HexFormat.of().withDelimiter(" ").formatHex(a.getBytes()) + ", expect " + HexFormat.of().withDelimiter(" ").formatHex(exp.getBytes())); } } @@ -269,6 +270,7 @@ public void TestZeroIndex() throws Exception { * Make sure characters in the CompositionExclusion.txt list do not get * composed to. */ + @Test public void TestCompositionExclusion() throws Exception { // This list is generated from CompositionExclusion.txt. // Update whenever the normalizer tables are updated. Note @@ -397,14 +399,7 @@ private void checkCompositionExclusion_320(String s) throws Exception { String c = NormalizerBase.normalize(b, NFC); if (c.equals(a)) { - errln("FAIL: " + HexFormat.of().withDelimiter(" ") - .formatHex(a.getBytes()) + " x DECOMP_COMPAT => " + - HexFormat.of().withDelimiter(" ") - .formatHex(b.getBytes()) + " x COMPOSE => " + - HexFormat.of().withDelimiter(" ") - .formatHex(c.getBytes()) + " for the latest Unicode"); - } else if (verbose) { - logln("Ok: " + HexFormat.of().withDelimiter(" ") + fail("FAIL: " + HexFormat.of().withDelimiter(" ") .formatHex(a.getBytes()) + " x DECOMP_COMPAT => " + HexFormat.of().withDelimiter(" ") .formatHex(b.getBytes()) + " x COMPOSE => " + @@ -415,18 +410,14 @@ private void checkCompositionExclusion_320(String s) throws Exception { b = NormalizerBase.normalize(a, NFKD, Normalizer.UNICODE_3_2); c = NormalizerBase.normalize(b, NFC, Normalizer.UNICODE_3_2); if (c.equals(a)) { - errln("FAIL: " + HexFormat.of().withDelimiter(" ") - .formatHex(a.getBytes()) + " x DECOMP_COMPAT => " + - HexFormat.of().withDelimiter(" ").formatHex(b.getBytes()) + " x COMPOSE => " + - HexFormat.of().withDelimiter(" ").formatHex(c.getBytes()) + " for Unicode 3.2.0"); - } else if (verbose) { - logln("Ok: " + HexFormat.of().withDelimiter(" ") + fail("FAIL: " + HexFormat.of().withDelimiter(" ") .formatHex(a.getBytes()) + " x DECOMP_COMPAT => " + HexFormat.of().withDelimiter(" ").formatHex(b.getBytes()) + " x COMPOSE => " + HexFormat.of().withDelimiter(" ").formatHex(c.getBytes()) + " for Unicode 3.2.0"); } } + @Test public void TestTibetan() throws Exception { String[][] decomp = { { "\u0f77", "\u0f77", "\u0fb2\u0f71\u0f80" } @@ -441,6 +432,7 @@ public void TestTibetan() throws Exception { staticTest(NFKC,compose, 2); } + @Test public void TestExplodingBase() throws Exception{ // \u017f - Latin small letter long s // \u0307 - combining dot above @@ -574,18 +566,22 @@ public void TestExplodingBase() throws Exception{ { "\u30AB\uFF9E", "\u30AB\u3099", "\u30AC" }, }; + @Test public void TestNFD() throws Exception{ staticTest(NFD, canonTests, 1); } + @Test public void TestNFC() throws Exception{ staticTest(NFC, canonTests, 2); } + @Test public void TestNFKD() throws Exception{ staticTest(NFKD, compatTests, 1); } + @Test public void TestNFKC() throws Exception{ staticTest(NFKC, compatTests, 2); } @@ -595,14 +591,14 @@ private void staticTest(java.text.Normalizer.Form form, int outCol) throws Exception { for (int i = 0; i < tests.length; i++) { String input = tests[i][0]; - logln("Normalizing '" + input + "' (" + HexFormat.of() + System.out.println("Normalizing '" + input + "' (" + HexFormat.of() .withDelimiter(" ").formatHex(input.getBytes()) + ")" ); String expect =tests[i][outCol]; String output = java.text.Normalizer.normalize(input, form); if (!output.equals(expect)) { - errln("FAIL: case " + i + fail("FAIL: case " + i + " expected '" + expect + "' (" + HexFormat.of() .withDelimiter(" ").formatHex(expect.getBytes()) + ")" + " but got '" + output + "' (" + HexFormat.of() @@ -621,13 +617,15 @@ private void staticTest(java.text.Normalizer.Form form, { "\u1111\u1171\u11b6", "\u1111\u1171\u11b6", "\ud4db" }, }; + @Test public void TestHangulCompose() throws Exception{ - logln("Canonical composition..."); + System.out.println("Canonical composition..."); staticTest(NFC, hangulCanon, 2); } + @Test public void TestHangulDecomp() throws Exception{ - logln("Canonical decomposition..."); + System.out.println("Canonical decomposition..."); staticTest(NFD, hangulCanon, 1); } diff --git a/test/jdk/java/text/Normalizer/NormalizerAPITest.java b/test/jdk/java/text/Normalizer/NormalizerAPITest.java index 00deb3c843c..d696d5cbc2d 100644 --- a/test/jdk/java/text/Normalizer/NormalizerAPITest.java +++ b/test/jdk/java/text/Normalizer/NormalizerAPITest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,14 +26,17 @@ * @bug 4221795 8174270 * @summary Confirm Normalizer's fundamental behavior * @modules java.base/sun.text java.base/jdk.internal.icu.text - * @library /java/text/testlib * @compile -XDignore.symbol.file NormalizerAPITest.java - * @run main/timeout=30 NormalizerAPITest + * @run junit/timeout=30 NormalizerAPITest */ import java.text.Normalizer; import java.nio.CharBuffer; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + /* * Tests around null/"" arguments for public methods. @@ -41,7 +44,7 @@ * You may think that so elaborate testing for such a part is not necessary. * But I actually detected a bug by this program during my porting work. */ -public class NormalizerAPITest extends IntlTest { +public class NormalizerAPITest { // // Shortcuts @@ -71,13 +74,10 @@ public class NormalizerAPITest extends IntlTest { static final String nonNullStr = "testdata"; - public static void main(String[] args) throws Exception { - new NormalizerAPITest().run(args); - } - /* * Check if normalize(null) throws NullPointerException as expected. */ + @Test public void Test_NullPointerException_java_normalize() { boolean error = false; @@ -100,13 +100,14 @@ public void Test_NullPointerException_java_normalize() { } if (error) { - errln("normalize(null) should throw NullPointerException."); + fail("normalize(null) should throw NullPointerException."); } } /* * Check if normalize(null) throws NullPointerException as expected. */ + @Test public void Test_NullPointerException_sun_normalize() { boolean error = false; @@ -131,13 +132,14 @@ public void Test_NullPointerException_sun_normalize() { } if (error) { - errln("normalize(null) should throw NullPointerException."); + fail("normalize(null) should throw NullPointerException."); } } /* * Check if isNormalized(null) throws NullPointerException as expected. */ + @Test public void Test_NullPointerException_java_isNormalized() { boolean error = false; @@ -160,13 +162,14 @@ public void Test_NullPointerException_java_isNormalized() { catch (NullPointerException e) { } if (error) { - errln("isNormalized(null) should throw NullPointerException."); + fail("isNormalized(null) should throw NullPointerException."); } } /* * Check if isNormalized(null) throws NullPointerException as expected. */ + @Test public void Test_NullPointerException_sun_isNormalized() { boolean error = false; @@ -191,7 +194,7 @@ public void Test_NullPointerException_sun_isNormalized() { } if (error) { - errln("isNormalized(null) should throw NullPointerException."); + fail("isNormalized(null) should throw NullPointerException."); } } @@ -199,6 +202,7 @@ public void Test_NullPointerException_sun_isNormalized() { * Check if isNormalized("") doesn't throw NullPointerException and returns * "" as expected. */ + @Test public void Test_No_NullPointerException_java_normalize() { boolean error = false; @@ -215,7 +219,7 @@ public void Test_No_NullPointerException_java_normalize() { } if (error) { - errln("normalize() for String(\"\") should return \"\"."); + fail("normalize() for String(\"\") should return \"\"."); } } @@ -223,6 +227,7 @@ public void Test_No_NullPointerException_java_normalize() { * Check if isNormalized("") doesn't throw NullPointerException and returns * "" as expected. */ + @Test public void Test_No_NullPointerException_sun_normalize() { boolean error = false; @@ -240,7 +245,7 @@ public void Test_No_NullPointerException_sun_normalize() { } } if (error) { - errln("normalize() for String(\"\") should return \"\"."); + fail("normalize() for String(\"\") should return \"\"."); } } @@ -248,6 +253,7 @@ public void Test_No_NullPointerException_sun_normalize() { * Check if isNormalized("") doesn't throw NullPointerException and returns * "" as expected. */ + @Test public void Test_No_NullPointerException_java_isNormalized() { boolean error = false; @@ -263,7 +269,7 @@ public void Test_No_NullPointerException_java_isNormalized() { } } if (error) { - errln("isNormalized() for String(\"\") should not return true."); + fail("isNormalized() for String(\"\") should not return true."); } } @@ -271,6 +277,7 @@ public void Test_No_NullPointerException_java_isNormalized() { * Check if isNormalized("") doesn't throw NullPointerException and returns * "" as expected. */ + @Test public void Test_No_NullPointerException_sun_isNormalized() { boolean error = false; @@ -288,7 +295,7 @@ public void Test_No_NullPointerException_sun_isNormalized() { } } if (error) { - errln("isNormalized() for String(\"\") should not return true."); + fail("isNormalized() for String(\"\") should not return true."); } } @@ -296,6 +303,7 @@ public void Test_No_NullPointerException_sun_isNormalized() { * Check if normalize() and isNormalized() work as expected for every * known class which implement CharSequence Interface. */ + @Test public void Test_CharSequence() { check_CharSequence(String.valueOf(inputData), @@ -315,23 +323,23 @@ public void Test_CharSequence() { void check_CharSequence(CharSequence in, CharSequence expected) { String out = Normalizer.normalize(in, NFD); if (!out.equals(expected.toString())) { - errln("java.text.Normalizer.normalize(" + + fail("java.text.Normalizer.normalize(" + in.getClass().getSimpleName() + ") failed."); } out = sun.text.Normalizer.normalize(in, NFD, jdk.internal.icu.text.NormalizerBase.UNICODE_LATEST); if (!out.equals(expected.toString())) { - errln("sun.text.Normalizer.normalize(" + + fail("sun.text.Normalizer.normalize(" + in.getClass().getSimpleName() + ") failed."); } if (!Normalizer.isNormalized(expected, NFD)) { - errln("java.text.Normalizer.isNormalize(" + + fail("java.text.Normalizer.isNormalize(" + in.getClass().getSimpleName() + ") failed."); } if (!sun.text.Normalizer.isNormalized(expected, NFD, jdk.internal.icu.text.NormalizerBase.UNICODE_LATEST)) { - errln("sun.text.Normalizer.isNormalize(" + + fail("sun.text.Normalizer.isNormalize(" + in.getClass().getSimpleName() + ") failed."); } } diff --git a/test/jdk/java/text/testlib/HexDumpReader.java b/test/jdk/java/text/testlib/HexDumpReader.java index 31a820d04d4..61fcf27832a 100644 --- a/test/jdk/java/text/testlib/HexDumpReader.java +++ b/test/jdk/java/text/testlib/HexDumpReader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,6 +27,7 @@ import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; @@ -37,7 +38,11 @@ * * $ od -vw -t x1 foo | sed -r -e 's/^[0-9]+ ?//' -e 's/ //g' -e '/^$/d' */ -public class HexDumpReader { +public final class HexDumpReader { + + // Utility class should not be instantiated + private HexDumpReader() {} + public static InputStream getStreamFromHexDump(String fileName) { return getStreamFromHexDump(new File(System.getProperty("test.src", "."), fileName)); @@ -48,7 +53,7 @@ public static InputStream getStreamFromHexDump(File hexFile) { int lineNo = 0; try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(hexFile), - "us-ascii"))) { + StandardCharsets.US_ASCII))) { String line; while ((line = reader.readLine()) != null) { lineNo++; diff --git a/test/jdk/java/text/testlib/IntlTest.java b/test/jdk/java/text/testlib/IntlTest.java deleted file mode 100644 index a3f1f72ab3f..00000000000 --- a/test/jdk/java/text/testlib/IntlTest.java +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.IOException; -import java.io.PrintWriter; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.Map; -import java.util.LinkedHashMap; -import java.util.List; - -/** - * IntlTest is a base class for tests that can be run conveniently from - * the command line as well as under the Java test harness. - *

- * Sub-classes implement a set of public void methods named "Test*" or - * "test*" with no arguments. Each of these methods performs some - * test. Test methods should indicate errors by calling either err() or - * errln(). This will increment the errorCount field and may optionally - * print a message to the log. Debugging information may also be added to - * the log via the log and logln methods. These methods will add their - * arguments to the log only if the test is being run in verbose mode. - */ -public abstract class IntlTest { - - //------------------------------------------------------------------------ - // Everything below here is boilerplate code that makes it possible - // to add a new test by simply adding a method to an existing class. - //------------------------------------------------------------------------ - protected IntlTest() { - Class testClass = getClass(); - testName = testClass.getCanonicalName(); - // Populate testMethods with all the test methods. - Method[] methods = testClass.getDeclaredMethods(); - for (Method method : methods) { - if (Modifier.isPublic(method.getModifiers()) - && method.getReturnType() == void.class - && method.getParameterCount() == 0) { - String name = method.getName(); - if (name.length() > 4) { - if (name.startsWith("Test") || name.startsWith("test")) { - testMethods.put(name, method); - } - } - } - } - } - - protected void run(String[] args) throws Exception { - // Set up the log and reference streams. We use PrintWriters in order to - // take advantage of character conversion. The JavaEsc converter will - // convert Unicode outside the ASCII range to Java's \\uxxxx notation. - log = new PrintWriter(System.out, true); - List testsToRun = configureTestsAndArgs(args); - System.out.println(testName + " {"); - indentLevel++; - - // Run the list of tests given in the test arguments - for (Method testMethod : testsToRun) { - int oldCount = errorCount; - String testName = testMethod.getName(); - writeTestName(testName); - try { - testMethod.invoke(this); - } catch (IllegalAccessException e) { - errln("Can't access test method " + testName); - } catch (InvocationTargetException e) { - // Log exception first, that way if -nothrow is - // not an arg, the original exception is still logged - logExc(e); - errln(String.format("$$$ Uncaught exception thrown in %s," + - " see above for cause", testName)); - } - writeTestResult(errorCount - oldCount); - } - indentLevel--; - if (prompt) { - System.out.println("Hit RETURN to exit..."); - try { - System.in.read(); - } catch (IOException e) { - System.out.println("Exception: " + e.toString() + e.getMessage()); - } - } - if (exitCode) { - System.exit(errorCount); - } - if (errorCount > 0) { - throw new RuntimeException(String.format( - "$$$ %s FAILED with %s failures%n", testName, errorCount)); - } else { - log.println(String.format("\t$$$ %s PASSED%n", testName)); - } - } - - private List configureTestsAndArgs(String[] args) { - // Parse the test arguments. They can be either the flag - // "-verbose" or names of test methods. Create a list of - // tests to be run. - List testsToRun = new ArrayList<>(args.length); - for (String arg : args) { - switch (arg) { - case "-verbose" -> verbose = true; - case "-prompt" -> prompt = true; - case "-nothrow" -> nothrow = true; - case "-exitcode" -> exitCode = true; - default -> { - Method m = testMethods.get(arg); - if (m == null) { - System.out.println("Method " + arg + ": not found"); - usage(); - return testsToRun; - } - testsToRun.add(m); - } - } - } - // If no test method names were given explicitly, run them all. - if (testsToRun.isEmpty()) { - testsToRun.addAll(testMethods.values()); - } - // Arbitrarily sort the tests, so that they are run in the same order every time - testsToRun.sort(Comparator.comparing(Method::getName)); - return testsToRun; - } - - /** - * Adds the given message to the log if we are in verbose mode. - */ - protected void log(String message) { - logImpl(message, false); - } - - protected void logln(String message) { - logImpl(message, true); - } - - protected void logln() { - logImpl(null, true); - } - - private void logImpl(String message, boolean newline) { - if (verbose) { - if (message != null) { - indent(indentLevel + 1); - log.print(message); - } - if (newline) { - log.println(); - } - } - } - - private void logExc(InvocationTargetException ite) { - indent(indentLevel); - ite.getTargetException().printStackTrace(this.log); - } - - protected void err(String message) { - errImpl(message, false); - } - - protected void errln(String message) { - errImpl(message, true); - } - - private void errImpl(String message, boolean newline) { - errorCount++; - indent(indentLevel + 1); - log.print(message); - if (newline) { - log.println(); - } - log.flush(); - - if (!nothrow) { - throw new RuntimeException(message); - } - } - - protected int getErrorCount() { - return errorCount; - } - - protected void writeTestName(String testName) { - indent(indentLevel); - log.print(testName); - log.flush(); - needLineFeed = true; - } - - protected void writeTestResult(int count) { - if (!needLineFeed) { - indent(indentLevel); - log.print("}"); - } - needLineFeed = false; - - if (count != 0) { - log.println(" FAILED"); - } else { - log.println(" Passed"); - } - } - - private void indent(int distance) { - if (needLineFeed) { - log.println(" {"); - needLineFeed = false; - } - log.print(SPACES.substring(0, distance * 2)); - } - - /** - * Print a usage message for this test class. - */ - void usage() { - System.out.println(getClass().getName() + - ": [-verbose] [-nothrow] [-exitcode] [-prompt] [test names]"); - - System.out.println(" Available test names:"); - for (String methodName : testMethods.keySet()) { - System.out.println("\t" + methodName); - } - } - private final String testName; - private boolean prompt; - private boolean nothrow; - protected boolean verbose; - private boolean exitCode; - private PrintWriter log; - private int indentLevel; - private boolean needLineFeed; - private int errorCount; - - private final Map testMethods = new LinkedHashMap<>(); - - private static final String SPACES = " "; -} diff --git a/test/jdk/java/text/testlib/TestUtils.java b/test/jdk/java/text/testlib/TestUtils.java index 309df451697..f2f7e57e197 100644 --- a/test/jdk/java/text/testlib/TestUtils.java +++ b/test/jdk/java/text/testlib/TestUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,23 +21,35 @@ * questions. */ +import java.text.CollationElementIterator; +import java.text.CollationKey; +import java.text.Collator; import java.text.DecimalFormatSymbols; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; -import java.util.Locale.Builder; - /** - * TestUtils provides utility methods to get a locale-dependent attribute. - * For example, - * - whether or not a non-Gregorian calendar is used - * - whether or not non-ASCII digits are used - * + * TestUtils provides utility methods used by i18n related tests. * This class was developed to help testing for internationalization & - * localization and is not versatile. + * localization and is not versatile. This class is split into the following sections, + * 1) Methods to get a locale-dependent attribute. + * For example, + * - whether a non-Gregorian calendar is used + * - whether non-ASCII digits are used + * 2) Methods that help Collator related tests + * For example, + * - compare CollationElementIterators + * - test the expected relation key result for a Collator */ -public class TestUtils { +public final class TestUtils { + + // Utility class should not be instantiated + private TestUtils() {} + + /* + * The below methods are utilities for getting locale-dependent attributes. + */ /** * Returns true if the give locale uses Gregorian calendar. @@ -56,7 +68,6 @@ public static boolean usesAsciiDigits(Locale locale) { /** * Returns true if the given locale has a special variant which is treated * as ill-formed in BCP 47. - * * BCP 47 requires a variant subtag to be 5 to 8 alphanumerics or a * single numeric followed by 3 alphanumerics. * However, note that this methods doesn't check a variant so rigorously @@ -71,4 +82,103 @@ public static boolean hasSpecialVariant(Locale locale) { && "JP".equals(variant) || "NY".equals(variant) || "TH".equals(variant); } + /* + * The below methods are utilities specific to the Collation tests + */ + + /** + * Compares two CollationElementIterators and throws an exception + * with a message detailing which collation elements were not equal + */ + public static void compareCollationElementIters(CollationElementIterator i1, CollationElementIterator i2) { + int c1, c2, count = 0; + do { + c1 = i1.next(); + c2 = i2.next(); + if (c1 != c2) { + throw new RuntimeException(" " + count + ": " + c1 + " != " + c2); + } + count++; + } while (c1 != CollationElementIterator.NULLORDER); + } + + // Replace non-printable characters with unicode escapes + public static String prettify(String str) { + StringBuilder result = new StringBuilder(); + + String zero = "0000"; + + for (int i = 0; i < str.length(); i++) { + char ch = str.charAt(i); + if (ch < 0x09 || (ch > 0x0A && ch < 0x20)|| (ch > 0x7E && ch < 0xA0) || ch > 0x100) { + String hex = Integer.toString((int)ch,16); + + result.append("\\u").append(zero.substring(0, 4 - hex.length())).append(hex); + } else { + result.append(ch); + } + } + return result.toString(); + } + + // Produce a printable representation of a CollationKey + public static String prettifyCKey(CollationKey key) { + StringBuilder result = new StringBuilder(); + byte[] bytes = key.toByteArray(); + + for (int i = 0; i < bytes.length; i += 2) { + int val = (bytes[i] << 8) + bytes[i+1]; + result.append(Integer.toString(val, 16)).append(" "); + } + return result.toString(); + } + + /** + * Utility to test a collator with an array of test values. + * See the other doTest() method for specific comparison details. + */ + public static void doCollatorTest(Collator col, int strength, + String[] source, String[] target, int[] result) { + if (source.length != target.length) { + throw new RuntimeException("Data size mismatch: source = " + + source.length + ", target = " + target.length); + } + if (source.length != result.length) { + throw new RuntimeException("Data size mismatch: source & target = " + + source.length + ", result = " + result.length); + } + + col.setStrength(strength); + for (int i = 0; i < source.length ; i++) { + doCollatorTest(col, source[i], target[i], result[i]); + } + } + + /** + * Test that a collator returns the correct relation result value when + * comparing a source and target string. Also tests that the compare and collation + * key results return the same value. + */ + public static void doCollatorTest(Collator col, + String source, String target, int result) { + char relation = '='; + if (result <= -1) { + relation = '<'; + } else if (result >= 1) { + relation = '>'; + } + + int compareResult = col.compare(source, target); + CollationKey sortKey1 = col.getCollationKey(source); + CollationKey sortKey2 = col.getCollationKey(target); + int keyResult = sortKey1.compareTo(sortKey2); + if (compareResult != keyResult) { + throw new RuntimeException("Compare and Collation Key results are different! Source = " + + source + " Target = " + target); + } + if (keyResult != result) { + throw new RuntimeException("Collation Test failed! Source = " + source + " Target = " + + target + " result should be " + relation); + } + } } diff --git a/test/jdk/java/util/Calendar/CalendarLimitTest.java b/test/jdk/java/util/Calendar/CalendarLimitTest.java index ec73cc27bc5..e8a92f180ec 100644 --- a/test/jdk/java/util/Calendar/CalendarLimitTest.java +++ b/test/jdk/java/util/Calendar/CalendarLimitTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,12 +26,16 @@ * @bug 4033662 * @summary test for limit on Calendar * @library /java/text/testlib - * @run main CalendarLimitTest -verbose + * @run junit CalendarLimitTest */ import java.util.*; import java.text.*; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + /** * This test verifies the behavior of Calendar around the very earliest limits * which it can handle. It also verifies the behavior for large values of millis. @@ -42,7 +46,7 @@ * March 17, 1998: Added code to make sure big + dates are big + AD years, and * big - dates are big + BC years. */ -public class CalendarLimitTest extends IntlTest +public class CalendarLimitTest { // This number determined empirically; this is the old limit, // which we test for to make sure it isn't there anymore. @@ -61,16 +65,6 @@ public class CalendarLimitTest extends IntlTest static long ORIGIN; // This is the *approximate* point at which BC switches to AD - public static void main(String argv[]) throws Exception { - Locale locale = Locale.getDefault(); - if (!TestUtils.usesGregorianCalendar(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } - - new CalendarLimitTest().run(argv); - } - /** * Converts Julian day to time as milliseconds. * @param julian the given Julian day number. @@ -108,32 +102,38 @@ int test(long millis, Calendar cal, DateFormat fmt) boolean ok = true; if (exception != null) { - errln("FAIL: Exception " + s); + fail("FAIL: Exception " + s); ok = false; } if (((millis >= ORIGIN) && (era != GregorianCalendar.AD)) || ((millis < ORIGIN) && (era != GregorianCalendar.BC)) || (year < 1)) { - errln("FAIL: Bad year/era " + s); + fail("FAIL: Bad year/era " + s); ok = false; } if (dom<1 || dom>31) { - errln("FAIL: Bad DOM " + s); + fail("FAIL: Bad DOM " + s); ok = false; } if (Math.abs(millis - rt.getTime()) > ONE_DAY) { - errln("FAIL: RT fail " + s + " -> 0x" + + fail("FAIL: RT fail " + s + " -> 0x" + Long.toHexString(rt.getTime()) + " " + fmt.format(rt)); ok = false; } - if (ok) logln(s); + if (ok) System.out.println(s); if (era==GregorianCalendar.BC) year = 1-year; return year; } + @Test public void TestCalendarLimit() { + Locale locale = Locale.getDefault(); + if (!TestUtils.usesGregorianCalendar(locale)) { + System.out.println("Skipping this test because locale is " + locale); + return; + } ORIGIN = julianDayToMillis(JAN_1_1_JULIAN_DAY); Calendar cal = Calendar.getInstance(); @@ -154,7 +154,7 @@ public void TestCalendarLimit() { int y = test(m, cal, dateFormat); if (!first && y > lastYear) - errln("FAIL: Years should be decreasing " + lastYear + " " + y); + fail("FAIL: Years should be decreasing " + lastYear + " " + y); first = false; lastYear = y; } @@ -165,7 +165,7 @@ public void TestCalendarLimit() { int y = test(m, cal, dateFormat); if (!first && y < lastYear) - errln("FAIL: Years should be increasing " + lastYear + " " + y); + fail("FAIL: Years should be increasing " + lastYear + " " + y); first = false; lastYear = y; } @@ -188,7 +188,7 @@ public void TestCalendarLimit() cal.set(292269055, Calendar.DECEMBER, dom, h, 0); Date d = cal.getTime(); cal.setTime(d); - logln("" + h + ":00 Dec "+dom+", 292269055 BC -> " + + System.out.println("" + h + ":00 Dec "+dom+", 292269055 BC -> " + Long.toHexString(d.getTime()) + " -> " + dateFormat.format(cal.getTime())); } @@ -197,7 +197,7 @@ public void TestCalendarLimit() long t = 0x80000000018c5c00L; // Dec 3, 292269055 BC while (t<0) { cal.setTime(new Date(t)); - logln("0x" + Long.toHexString(t) + " -> " + + System.out.println("0x" + Long.toHexString(t) + " -> " + dateFormat.format(cal.getTime())); t -= ONE_HOUR; } diff --git a/test/jdk/java/util/Calendar/CalendarRegression.java b/test/jdk/java/util/Calendar/CalendarRegression.java index 8a1ebcc4544..f8018a7a26c 100644 --- a/test/jdk/java/util/Calendar/CalendarRegression.java +++ b/test/jdk/java/util/Calendar/CalendarRegression.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,7 +32,7 @@ * 4652815 4652830 4740554 4936355 4738710 4633646 4846659 4822110 4960642 * 4973919 4980088 4965624 5013094 5006864 8152077 * @library /java/text/testlib - * @run main CalendarRegression + * @run junit CalendarRegression */ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -53,22 +53,16 @@ import static java.util.Calendar.*; -public class CalendarRegression extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new CalendarRegression().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class CalendarRegression { /* Synopsis: java.sql.Timestamp constructor works wrong on Windows 95 ==== Here is the test ==== - public static void main (String args[]) { - java.sql.Timestamp t= new java.sql.Timestamp(0,15,5,5,8,13,123456700); - logln("expected=1901-04-05 05:08:13.1234567"); - logln(" result="+t); - } - ==== Here is the output of the test on Solaris or NT ==== expected=1901-04-05 05:08:13.1234567 result=1901-04-05 05:08:13.1234567 @@ -77,6 +71,7 @@ public static void main (String args[]) { expected=1901-04-05 05:08:13.1234567 result=1901-04-05 06:08:13.1234567 */ + @Test public void Test4031502() { // This bug actually occurs on Windows NT as well, and doesn't // require the host zone to be set; it can be set in Java. @@ -88,7 +83,7 @@ public void Test4031502() { cal.clear(); cal.set(1900, 15, 5, 5, 8, 13); if (cal.get(HOUR) != 5) { - logln(zone.getID() + " " + System.out.println(zone.getID() + " " + //zone.useDaylightTime() + " " + cal.get(DST_OFFSET) / (60 * 60 * 1000) + " " + zone.getRawOffset() / (60 * 60 * 1000) @@ -97,10 +92,11 @@ public void Test4031502() { } } if (bad) { - errln("TimeZone problems with GC"); + fail("TimeZone problems with GC"); } } + @Test public void Test4035301() { GregorianCalendar c = new GregorianCalendar(98, 8, 7); GregorianCalendar d = new GregorianCalendar(98, 8, 7); @@ -110,10 +106,11 @@ public void Test4035301() { || c.before(c) || !c.equals(c) || !c.equals(d)) { - errln("Fail"); + fail("Fail"); } } + @Test public void Test4040996() { String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000); SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]); @@ -125,97 +122,100 @@ public void Test4040996() { calendar.set(DAY_OF_MONTH, 18); calendar.set(SECOND, 30); - logln("MONTH: " + calendar.get(MONTH)); - logln("DAY_OF_MONTH: " + System.out.println("MONTH: " + calendar.get(MONTH)); + System.out.println("DAY_OF_MONTH: " + calendar.get(DAY_OF_MONTH)); - logln("MINUTE: " + calendar.get(MINUTE)); - logln("SECOND: " + calendar.get(SECOND)); + System.out.println("MINUTE: " + calendar.get(MINUTE)); + System.out.println("SECOND: " + calendar.get(SECOND)); calendar.add(SECOND, 6); //This will print out todays date for MONTH and DAY_OF_MONTH //instead of the date it was set to. //This happens when adding MILLISECOND or MINUTE also - logln("MONTH: " + calendar.get(MONTH)); - logln("DAY_OF_MONTH: " + System.out.println("MONTH: " + calendar.get(MONTH)); + System.out.println("DAY_OF_MONTH: " + calendar.get(DAY_OF_MONTH)); - logln("MINUTE: " + calendar.get(MINUTE)); - logln("SECOND: " + calendar.get(SECOND)); + System.out.println("MINUTE: " + calendar.get(MINUTE)); + System.out.println("SECOND: " + calendar.get(SECOND)); if (calendar.get(MONTH) != 3 || calendar.get(DAY_OF_MONTH) != 18 || calendar.get(SECOND) != 36) { - errln("Fail: Calendar.add misbehaves"); + fail("Fail: Calendar.add misbehaves"); } } + @Test public void Test4051765() { Calendar cal = Calendar.getInstance(); cal.setLenient(false); cal.set(DAY_OF_WEEK, 0); try { cal.getTime(); - errln("Fail: DAY_OF_WEEK 0 should be disallowed"); + fail("Fail: DAY_OF_WEEK 0 should be disallowed"); } catch (IllegalArgumentException e) { return; } } /* User error - no bug here + @Test public void Test4059524() { // Create calendar for April 10, 1997 GregorianCalendar calendar = new GregorianCalendar(); // print out a bunch of interesting things - logln("ERA: " + calendar.get(calendar.ERA)); - logln("YEAR: " + calendar.get(calendar.YEAR)); - logln("MONTH: " + calendar.get(calendar.MONTH)); - logln("WEEK_OF_YEAR: " + + System.out.println("ERA: " + calendar.get(calendar.ERA)); + System.out.println("YEAR: " + calendar.get(calendar.YEAR)); + System.out.println("MONTH: " + calendar.get(calendar.MONTH)); + System.out.println("WEEK_OF_YEAR: " + calendar.get(calendar.WEEK_OF_YEAR)); - logln("WEEK_OF_MONTH: " + + System.out.println("WEEK_OF_MONTH: " + calendar.get(calendar.WEEK_OF_MONTH)); - logln("DATE: " + calendar.get(calendar.DATE)); - logln("DAY_OF_MONTH: " + + System.out.println("DATE: " + calendar.get(calendar.DATE)); + System.out.println("DAY_OF_MONTH: " + calendar.get(calendar.DAY_OF_MONTH)); - logln("DAY_OF_YEAR: " + calendar.get(calendar.DAY_OF_YEAR)); - logln("DAY_OF_WEEK: " + calendar.get(calendar.DAY_OF_WEEK)); - logln("DAY_OF_WEEK_IN_MONTH: " + + System.out.println("DAY_OF_YEAR: " + calendar.get(calendar.DAY_OF_YEAR)); + System.out.println("DAY_OF_WEEK: " + calendar.get(calendar.DAY_OF_WEEK)); + System.out.println("DAY_OF_WEEK_IN_MONTH: " + calendar.get(calendar.DAY_OF_WEEK_IN_MONTH)); - logln("AM_PM: " + calendar.get(calendar.AM_PM)); - logln("HOUR: " + calendar.get(calendar.HOUR)); - logln("HOUR_OF_DAY: " + calendar.get(calendar.HOUR_OF_DAY)); - logln("MINUTE: " + calendar.get(calendar.MINUTE)); - logln("SECOND: " + calendar.get(calendar.SECOND)); - logln("MILLISECOND: " + calendar.get(calendar.MILLISECOND)); - logln("ZONE_OFFSET: " + System.out.println("AM_PM: " + calendar.get(calendar.AM_PM)); + System.out.println("HOUR: " + calendar.get(calendar.HOUR)); + System.out.println("HOUR_OF_DAY: " + calendar.get(calendar.HOUR_OF_DAY)); + System.out.println("MINUTE: " + calendar.get(calendar.MINUTE)); + System.out.println("SECOND: " + calendar.get(calendar.SECOND)); + System.out.println("MILLISECOND: " + calendar.get(calendar.MILLISECOND)); + System.out.println("ZONE_OFFSET: " + (calendar.get(calendar.ZONE_OFFSET)/(60*60*1000))); - logln("DST_OFFSET: " + System.out.println("DST_OFFSET: " + (calendar.get(calendar.DST_OFFSET)/(60*60*1000))); calendar = new GregorianCalendar(1997,3,10); calendar.getTime(); - logln("April 10, 1997"); - logln("ERA: " + calendar.get(calendar.ERA)); - logln("YEAR: " + calendar.get(calendar.YEAR)); - logln("MONTH: " + calendar.get(calendar.MONTH)); - logln("WEEK_OF_YEAR: " + + System.out.println("April 10, 1997"); + System.out.println("ERA: " + calendar.get(calendar.ERA)); + System.out.println("YEAR: " + calendar.get(calendar.YEAR)); + System.out.println("MONTH: " + calendar.get(calendar.MONTH)); + System.out.println("WEEK_OF_YEAR: " + calendar.get(calendar.WEEK_OF_YEAR)); - logln("WEEK_OF_MONTH: " + + System.out.println("WEEK_OF_MONTH: " + calendar.get(calendar.WEEK_OF_MONTH)); - logln("DATE: " + calendar.get(calendar.DATE)); - logln("DAY_OF_MONTH: " + + System.out.println("DATE: " + calendar.get(calendar.DATE)); + System.out.println("DAY_OF_MONTH: " + calendar.get(calendar.DAY_OF_MONTH)); - logln("DAY_OF_YEAR: " + calendar.get(calendar.DAY_OF_YEAR)); - logln("DAY_OF_WEEK: " + calendar.get(calendar.DAY_OF_WEEK)); - logln("DAY_OF_WEEK_IN_MONTH: " + calendar.get(calendar.DAY_OF_WEEK_IN_MONTH)); - logln("AM_PM: " + calendar.get(calendar.AM_PM)); - logln("HOUR: " + calendar.get(calendar.HOUR)); - logln("HOUR_OF_DAY: " + calendar.get(calendar.HOUR_OF_DAY)); - logln("MINUTE: " + calendar.get(calendar.MINUTE)); - logln("SECOND: " + calendar.get(calendar.SECOND)); - logln("MILLISECOND: " + calendar.get(calendar.MILLISECOND)); - logln("ZONE_OFFSET: " + System.out.println("DAY_OF_YEAR: " + calendar.get(calendar.DAY_OF_YEAR)); + System.out.println("DAY_OF_WEEK: " + calendar.get(calendar.DAY_OF_WEEK)); + System.out.println("DAY_OF_WEEK_IN_MONTH: " + calendar.get(calendar.DAY_OF_WEEK_IN_MONTH)); + System.out.println("AM_PM: " + calendar.get(calendar.AM_PM)); + System.out.println("HOUR: " + calendar.get(calendar.HOUR)); + System.out.println("HOUR_OF_DAY: " + calendar.get(calendar.HOUR_OF_DAY)); + System.out.println("MINUTE: " + calendar.get(calendar.MINUTE)); + System.out.println("SECOND: " + calendar.get(calendar.SECOND)); + System.out.println("MILLISECOND: " + calendar.get(calendar.MILLISECOND)); + System.out.println("ZONE_OFFSET: " + (calendar.get(calendar.ZONE_OFFSET)/(60*60*1000))); // in hours - logln("DST_OFFSET: " + System.out.println("DST_OFFSET: " + (calendar.get(calendar.DST_OFFSET)/(60*60*1000))); // in hours } */ + @Test public void Test4059654() { GregorianCalendar gc = new GregorianCalendar(); @@ -231,10 +231,11 @@ public void Test4059654() { @SuppressWarnings("deprecation") Date exp = new Date(97, 3, 1, 0, 0, 0); if (!cd.equals(exp)) { - errln("Fail: Calendar.set broken. Got " + cd + " Want " + exp); + fail("Fail: Calendar.set broken. Got " + cd + " Want " + exp); } } + @Test public void Test4061476() { SimpleDateFormat fmt = new SimpleDateFormat("ddMMMyy", Locale.UK); Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"), @@ -246,14 +247,15 @@ public void Test4061476() { } catch (Exception e) { } cal.set(HOUR_OF_DAY, 13); - logln("Hour: " + cal.get(HOUR_OF_DAY)); + System.out.println("Hour: " + cal.get(HOUR_OF_DAY)); cal.add(HOUR_OF_DAY, 6); - logln("Hour: " + cal.get(HOUR_OF_DAY)); + System.out.println("Hour: " + cal.get(HOUR_OF_DAY)); if (cal.get(HOUR_OF_DAY) != 19) { - errln("Fail: Want 19 Got " + cal.get(HOUR_OF_DAY)); + fail("Fail: Want 19 Got " + cal.get(HOUR_OF_DAY)); } } + @Test public void Test4070502() { @SuppressWarnings("deprecation") Date d = getAssociatedDate(new Date(98, 0, 30)); @@ -261,7 +263,7 @@ public void Test4070502() { cal.setTime(d); if (cal.get(DAY_OF_WEEK) == SATURDAY || cal.get(DAY_OF_WEEK) == SUNDAY) { - errln("Fail: Want weekday Got " + d); + fail("Fail: Want weekday Got " + d); } } @@ -289,6 +291,7 @@ public static Date getAssociatedDate(Date d) { return cal.getTime(); } + @Test public void Test4071197() { dowTest(false); dowTest(true); @@ -303,29 +306,31 @@ void dowTest(boolean lenient) { int dow = cal.get(DAY_OF_WEEK); int min = cal.getMinimum(DAY_OF_WEEK); int max = cal.getMaximum(DAY_OF_WEEK); - logln(cal.getTime().toString()); + System.out.println(cal.getTime().toString()); if (min != SUNDAY || max != SATURDAY) { - errln("FAIL: Min/max bad"); + fail("FAIL: Min/max bad"); } if (dow < min || dow > max) { - errln("FAIL: Day of week " + dow + " out of range"); + fail("FAIL: Day of week " + dow + " out of range"); } if (dow != SUNDAY) { - errln("FAIL: Day of week should be SUNDAY Got " + dow); + fail("FAIL: Day of week should be SUNDAY Got " + dow); } } @SuppressWarnings("deprecation") + @Test public void Test4071385() { Calendar cal = Calendar.getInstance(); cal.setTime(new Date(98, JUNE, 24)); cal.set(MONTH, NOVEMBER); // change a field - logln(cal.getTime().toString()); + System.out.println(cal.getTime().toString()); if (!cal.getTime().equals(new Date(98, NOVEMBER, 24))) { - errln("Fail"); + fail("Fail"); } } + @Test public void Test4073929() { GregorianCalendar foo1 = new GregorianCalendar(1997, 8, 27); foo1.add(DAY_OF_MONTH, +1); @@ -335,10 +340,11 @@ public void Test4073929() { if (testyear != 1997 || testmonth != 8 || testday != 28) { - errln("Fail: Calendar not initialized"); + fail("Fail: Calendar not initialized"); } } + @Test public void Test4083167() { TimeZone saveZone = TimeZone.getDefault(); try { @@ -351,7 +357,7 @@ public void Test4083167() { + cal.get(SECOND) * 1000L + cal.get(MILLISECOND); - logln("Current time: " + firstDate.toString()); + System.out.println("Current time: " + firstDate.toString()); for (int validity = 0; validity < 30; validity++) { Date lastDate = new Date(firstDate.getTime() @@ -362,7 +368,7 @@ public void Test4083167() { + cal.get(SECOND) * 1000L + cal.get(MILLISECOND); if (firstMillisInDay != millisInDay) { - errln("Day has shifted " + lastDate); + fail("Day has shifted " + lastDate); } } } finally { @@ -370,6 +376,7 @@ public void Test4083167() { } } + @Test public void Test4086724() { SimpleDateFormat date; TimeZone saveZone = TimeZone.getDefault(); @@ -387,12 +394,12 @@ public void Test4086724() { Date now = cal.getTime(); String formattedDate = date.format(now); if (!formattedDate.equals(summerTime)) { - errln("Wrong display name \"" + formattedDate + fail("Wrong display name \"" + formattedDate + "\" for <" + now + ">"); } int weekOfYear = cal.get(WEEK_OF_YEAR); if (weekOfYear != 40) { - errln("Wrong week-of-year " + weekOfYear + fail("Wrong week-of-year " + weekOfYear + " for <" + now + ">"); } @@ -400,12 +407,12 @@ public void Test4086724() { now = cal.getTime(); formattedDate = date.format(now); if (!formattedDate.equals(standardTime)) { - errln("Wrong display name \"" + formattedDate + fail("Wrong display name \"" + formattedDate + "\" for <" + now + ">"); } weekOfYear = cal.get(WEEK_OF_YEAR); if (weekOfYear != 1) { - errln("Wrong week-of-year " + weekOfYear + fail("Wrong week-of-year " + weekOfYear + " for <" + now + ">"); } @@ -413,12 +420,12 @@ public void Test4086724() { now = cal.getTime(); formattedDate = date.format(now); if (!formattedDate.equals(standardTime)) { - errln("Wrong display name \"" + formattedDate + fail("Wrong display name \"" + formattedDate + "\" for <" + now + ">"); } weekOfYear = cal.get(WEEK_OF_YEAR); if (weekOfYear != 1) { - errln("Wrong week-of-year " + weekOfYear + fail("Wrong week-of-year " + weekOfYear + " for <" + now + ">"); } @@ -426,12 +433,12 @@ public void Test4086724() { now = cal.getTime(); formattedDate = date.format(now); if (!formattedDate.equals(standardTime)) { - errln("Wrong display name \"" + formattedDate + fail("Wrong display name \"" + formattedDate + "\" for <" + now + ">"); } weekOfYear = cal.get(WEEK_OF_YEAR); if (weekOfYear != 2) { - errln("Wrong week-of-year " + weekOfYear + fail("Wrong week-of-year " + weekOfYear + " for <" + now + ">"); } @@ -441,6 +448,7 @@ public void Test4086724() { } } + @Test public void Test4092362() { GregorianCalendar cal1 = new GregorianCalendar(1997, 10, 11, 10, 20, 40); /*cal1.set( Calendar.YEAR, 1997 ); @@ -450,8 +458,8 @@ public void Test4092362() { cal1.set( Calendar.MINUTE, 20 ); cal1.set( Calendar.SECOND, 40 ); */ - logln(" Cal1 = " + cal1.getTime().getTime()); - logln(" Cal1 time in ms = " + cal1.get(MILLISECOND)); + System.out.println(" Cal1 = " + cal1.getTime().getTime()); + System.out.println(" Cal1 time in ms = " + cal1.get(MILLISECOND)); for (int k = 0; k < 100; k++); GregorianCalendar cal2 = new GregorianCalendar(1997, 10, 11, 10, 20, 40); @@ -462,21 +470,23 @@ public void Test4092362() { cal2.set( Calendar.MINUTE, 20 ); cal2.set( Calendar.SECOND, 40 ); */ - logln(" Cal2 = " + cal2.getTime().getTime()); - logln(" Cal2 time in ms = " + cal2.get(MILLISECOND)); + System.out.println(" Cal2 = " + cal2.getTime().getTime()); + System.out.println(" Cal2 time in ms = " + cal2.get(MILLISECOND)); if (!cal1.equals(cal2)) { - errln("Fail: Milliseconds randomized"); + fail("Fail: Milliseconds randomized"); } } + @Test public void Test4095407() { GregorianCalendar a = new GregorianCalendar(1997, NOVEMBER, 13); int dow = a.get(DAY_OF_WEEK); if (dow != THURSDAY) { - errln("Fail: Want THURSDAY Got " + dow); + fail("Fail: Want THURSDAY Got " + dow); } } + @Test public void Test4096231() { TimeZone GMT = TimeZone.getTimeZone("GMT"); TimeZone PST = TimeZone.getTimeZone("PST"); @@ -485,19 +495,19 @@ public void Test4096231() { Calendar cal1 = new GregorianCalendar(PST); cal1.setTime(new Date(880698639000L)); int p; - logln("PST 1 is: " + (p = cal1.get(HOUR_OF_DAY))); + System.out.println("PST 1 is: " + (p = cal1.get(HOUR_OF_DAY))); cal1.setTimeZone(GMT); // Issue 1: Changing the timezone doesn't change the // represented time. int h1, h2; - logln("GMT 1 is: " + (h1 = cal1.get(HOUR_OF_DAY))); + System.out.println("GMT 1 is: " + (h1 = cal1.get(HOUR_OF_DAY))); cal1.setTime(new Date(880698639000L)); - logln("GMT 2 is: " + (h2 = cal1.get(HOUR_OF_DAY))); + System.out.println("GMT 2 is: " + (h2 = cal1.get(HOUR_OF_DAY))); // Note: This test had a bug in it. It wanted h1!=h2, when // what was meant was h1!=p. Fixed this concurrent with fix // to 4177484. if (p == h1 || h1 != h2) { - errln("Fail: Hour same in different zones"); + fail("Fail: Hour same in different zones"); } Calendar cal2 = new GregorianCalendar(GMT); @@ -513,11 +523,11 @@ public void Test4096231() { cal1.get(SECOND)); long t1, t2, t3, t4; - logln("RGMT 1 is: " + (t1 = cal2.getTime().getTime())); + System.out.println("RGMT 1 is: " + (t1 = cal2.getTime().getTime())); cal3.set(year, month, day, hr, min, sec); - logln("RPST 1 is: " + (t2 = cal3.getTime().getTime())); + System.out.println("RPST 1 is: " + (t2 = cal3.getTime().getTime())); cal3.setTimeZone(GMT); - logln("RGMT 2 is: " + (t3 = cal3.getTime().getTime())); + System.out.println("RGMT 2 is: " + (t3 = cal3.getTime().getTime())); cal3.set(cal1.get(YEAR), cal1.get(MONTH), cal1.get(DAY_OF_MONTH), @@ -527,40 +537,42 @@ public void Test4096231() { // Issue 2: Calendar continues to use the timezone in its // constructor for set() conversions, regardless // of calls to setTimeZone() - logln("RGMT 3 is: " + (t4 = cal3.getTime().getTime())); + System.out.println("RGMT 3 is: " + (t4 = cal3.getTime().getTime())); if (t1 == t2 || t1 != t4 || t2 != t3) { - errln("Fail: Calendar zone behavior faulty"); + fail("Fail: Calendar zone behavior faulty"); } } + @Test public void Test4096539() { int[] y = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; for (int x = 0; x < 12; x++) { GregorianCalendar gc = new GregorianCalendar(1997, x, y[x]); int m1, m2; - log((m1 = gc.get(MONTH) + 1) + "/" + System.out.println((m1 = gc.get(MONTH) + 1) + "/" + gc.get(DATE) + "/" + gc.get(YEAR) + " + 1mo = "); gc.add(MONTH, 1); - logln((m2 = gc.get(MONTH) + 1) + "/" + System.out.println((m2 = gc.get(MONTH) + 1) + "/" + gc.get(DATE) + "/" + gc.get(YEAR) ); int m = (m1 % 12) + 1; if (m2 != m) { - errln("Fail: Want " + m + " Got " + m2); + fail("Fail: Want " + m + " Got " + m2); } } } + @Test public void Test4100311() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -568,16 +580,17 @@ public void Test4100311() { cal.set(YEAR, 1997); cal.set(DAY_OF_YEAR, 1); Date d = cal.getTime(); // Should be Jan 1 - logln(d.toString()); + System.out.println(d.toString()); if (cal.get(DAY_OF_YEAR) != 1) { - errln("Fail: DAY_OF_YEAR not set"); + fail("Fail: DAY_OF_YEAR not set"); } } + @Test public void Test4103271() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -594,7 +607,7 @@ public void Test4103271() { testCal.setMinimalDaysInFirstWeek(minDays); testCal.setFirstDayOfWeek(firstDay); testDesc = ("Test" + String.valueOf(firstDay) + String.valueOf(minDays)); - logln(testDesc + " => 1st day of week=" + System.out.println(testDesc + " => 1st day of week=" + String.valueOf(firstDay) + ", minimum days in first week=" + String.valueOf(minDays)); @@ -609,7 +622,7 @@ public void Test4103271() { calWOY = String.valueOf(actWOY); output = testDesc + " - " + sdf.format(d) + "\t"; output = output + "\t" + calWOY; - logln(output); + System.out.println(output); fail = true; } } @@ -626,18 +639,18 @@ public void Test4103271() { 1, 1, 1, 1, 1, 1, 1}; testCal.setFirstDayOfWeek(SUNDAY); for (int j = 0; j < DATA.length; j += 22) { - logln("Minimal days in first week = " + DATA[j] + System.out.println("Minimal days in first week = " + DATA[j] + " Week starts on Sunday"); testCal.setMinimalDaysInFirstWeek(DATA[j]); testCal.set(1997, DECEMBER, 21); for (int i = 0; i < 21; ++i) { int woy = testCal.get(WEEK_OF_YEAR); - log("\t" + testCal.getTime() + " " + woy); + System.out.println("\t" + testCal.getTime() + " " + woy); if (woy != DATA[j + 1 + i]) { - log(" ERROR"); + System.out.println(" ERROR"); fail = true; } else { - logln(" OK"); + System.out.println(" OK"); } // Now compute the time from the fields, and make sure we @@ -648,10 +661,10 @@ public void Test4103271() { testCal.set(WEEK_OF_YEAR, DATA[j + 1 + i]); testCal.set(DAY_OF_WEEK, (i % 7) + SUNDAY); if (!testCal.getTime().equals(save)) { - logln(" Parse failed: " + testCal.getTime()); + System.out.println(" Parse failed: " + testCal.getTime()); fail = true; } else { - logln(" Passed"); + System.out.println(" Passed"); } testCal.setTime(save); @@ -682,12 +695,12 @@ public void Test4103271() { testCal.set(YEAR, y); testCal.set(WEEK_OF_YEAR, woy); testCal.set(DAY_OF_WEEK, dow); - log(y + "-W" + woy + "-DOW" + dow); + System.out.println(y + "-W" + woy + "-DOW" + dow); if (!testCal.getTime().equals(exp)) { - logln(" FAILED expect: " + exp + "\n got: " + testCal.getTime()); + System.out.println(" FAILED expect: " + exp + "\n got: " + testCal.getTime()); fail = true; } else { - logln(" OK"); + System.out.println(" OK"); } } @@ -714,14 +727,14 @@ public void Test4103271() { } else { testCal.roll(WEEK_OF_YEAR, amount); } - log((ADDROLL[i] == ADD ? "add(WOY," : "roll(WOY,") + System.out.println((ADDROLL[i] == ADD ? "add(WOY," : "roll(WOY,") + amount + ")\t " + before + "\n\t\t => " + testCal.getTime()); if (!after.equals(testCal.getTime())) { - logln("\tFAIL\n\t\texp: " + after); + System.out.println("\tFAIL\n\t\texp: " + after); fail = true; } else { - logln(" OK"); + System.out.println(" OK"); } testCal.setTime(after); @@ -730,22 +743,23 @@ public void Test4103271() { } else { testCal.roll(WEEK_OF_YEAR, -amount); } - log((ADDROLL[i] == ADD ? "add(WOY," : "roll(WOY,") + System.out.println((ADDROLL[i] == ADD ? "add(WOY," : "roll(WOY,") + (-amount) + ") " + after + "\n\t\t => " + testCal.getTime()); if (!before.equals(testCal.getTime())) { - logln("\tFAIL\n\t\texp: " + before); + System.out.println("\tFAIL\n\t\texp: " + before); fail = true; } else { - logln("\tOK"); + System.out.println("\tOK"); } } if (fail) { - errln("Fail: Week of year misbehaving"); + fail("Fail: Week of year misbehaving"); } } + @Test public void Test4106136() { Locale saveLocale = Locale.getDefault(); try { @@ -758,7 +772,7 @@ public void Test4106136() { NumberFormat.getAvailableLocales().length}; for (int j = 0; j < n.length; ++j) { if (n[j] == 0) { - errln("Fail: No locales for " + locales[i]); + fail("Fail: No locales for " + locales[i]); } } } @@ -768,6 +782,7 @@ public void Test4106136() { } @SuppressWarnings("deprecation") + @Test public void Test4108764() { Date d00 = new Date(97, MARCH, 15, 12, 00, 00); Date d01 = new Date(97, MARCH, 15, 12, 00, 56); @@ -779,42 +794,43 @@ public void Test4108764() { cal.setTime(d11); cal.clear(MINUTE); - logln(cal.getTime().toString()); + System.out.println(cal.getTime().toString()); if (!cal.getTime().equals(d01)) { - errln("Fail: clear(MINUTE) broken"); + fail("Fail: clear(MINUTE) broken"); } cal.set(SECOND, 0); - logln(cal.getTime().toString()); + System.out.println(cal.getTime().toString()); if (!cal.getTime().equals(d00)) { - errln("Fail: set(SECOND, 0) broken"); + fail("Fail: set(SECOND, 0) broken"); } cal.setTime(d11); cal.set(SECOND, 0); - logln(cal.getTime().toString()); + System.out.println(cal.getTime().toString()); if (!cal.getTime().equals(d10)) { - errln("Fail: set(SECOND, 0) broken #2"); + fail("Fail: set(SECOND, 0) broken #2"); } cal.clear(MINUTE); - logln(cal.getTime().toString()); + System.out.println(cal.getTime().toString()); if (!cal.getTime().equals(d00)) { - errln("Fail: clear(MINUTE) broken #2"); + fail("Fail: clear(MINUTE) broken #2"); } cal.clear(); - logln(cal.getTime().toString()); + System.out.println(cal.getTime().toString()); if (!cal.getTime().equals(epoch)) { - errln("Fail: clear() broken Want " + epoch); + fail("Fail: clear() broken Want " + epoch); } } @SuppressWarnings("deprecation") + @Test public void Test4114578() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -849,28 +865,28 @@ public void Test4114578() { int amt = (int) DATA[i + 2]; long expectedChange = DATA[i + 3]; - log(date.toString()); + System.out.println(date.toString()); cal.setTime(date); switch ((int) DATA[i + 1]) { case ADD: - log(" add (HOUR," + (amt < 0 ? "" : "+") + amt + ")= "); + System.out.println(" add (HOUR," + (amt < 0 ? "" : "+") + amt + ")= "); cal.add(HOUR, amt); break; case ROLL: - log(" roll(HOUR," + (amt < 0 ? "" : "+") + amt + ")= "); + System.out.println(" roll(HOUR," + (amt < 0 ? "" : "+") + amt + ")= "); cal.roll(HOUR, amt); break; } - log(cal.getTime().toString()); + System.out.println(cal.getTime().toString()); long change = cal.getTime().getTime() - date.getTime(); if (change != expectedChange) { fail = true; - logln(" FAIL"); + System.out.println(" FAIL"); } else { - logln(" OK"); + System.out.println(" OK"); } } } finally { @@ -878,29 +894,31 @@ public void Test4114578() { } if (fail) { - errln("Fail: roll/add misbehaves around DST onset/cease"); + fail("Fail: roll/add misbehaves around DST onset/cease"); } } /** * Make sure maximum for HOUR field is 11, not 12. */ + @Test public void Test4118384() { Calendar cal = Calendar.getInstance(); if (cal.getMaximum(HOUR) != 11 || cal.getLeastMaximum(HOUR) != 11 || cal.getActualMaximum(HOUR) != 11) { - errln("Fail: maximum of HOUR field should be 11"); + fail("Fail: maximum of HOUR field should be 11"); } } /** * Check isLeapYear for BC years. */ + @Test public void Test4125881() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -910,10 +928,10 @@ public void Test4125881() { for (int y = -20; y <= 10; ++y) { cal.set(ERA, y < 1 ? GregorianCalendar.BC : GregorianCalendar.AD); cal.set(YEAR, y < 1 ? 1 - y : y); - logln(y + " = " + fmt.format(cal.getTime()) + " " + System.out.println(y + " = " + fmt.format(cal.getTime()) + " " + cal.isLeapYear(y)); if (cal.isLeapYear(y) != ((y + 40) % 4 == 0)) { - errln("Leap years broken"); + fail("Leap years broken"); } } } @@ -922,10 +940,11 @@ public void Test4125881() { * Prove that GregorianCalendar is proleptic (it used to cut off * at 45 BC, and not have leap years before then). */ + @Test public void Test4125892() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -939,7 +958,7 @@ public void Test4125892() { cal.add(DATE, 1); if (cal.get(DATE) != 29 || !cal.isLeapYear(-80)) { // -80 == 81 BC - errln("Calendar not proleptic"); + fail("Calendar not proleptic"); } } @@ -948,6 +967,7 @@ public void Test4125892() { * Calendar needs a good implementation that subclasses can override, * and GregorianCalendar should use that implementation. */ + @Test public void Test4136399() { /* Note: This test is actually more strict than it has to be. * Technically, there is no requirement that unequal objects have @@ -961,24 +981,24 @@ public void Test4136399() { Calendar a = Calendar.getInstance(); Calendar b = (Calendar) a.clone(); if (a.hashCode() != b.hashCode()) { - errln("Calendar hash code unequal for cloned objects"); + fail("Calendar hash code unequal for cloned objects"); } b.setMinimalDaysInFirstWeek(7 - a.getMinimalDaysInFirstWeek()); if (a.hashCode() == b.hashCode()) { - errln("Calendar hash code ignores minimal days in first week"); + fail("Calendar hash code ignores minimal days in first week"); } b.setMinimalDaysInFirstWeek(a.getMinimalDaysInFirstWeek()); b.setFirstDayOfWeek((a.getFirstDayOfWeek() % 7) + 1); // Next day if (a.hashCode() == b.hashCode()) { - errln("Calendar hash code ignores first day of week"); + fail("Calendar hash code ignores first day of week"); } b.setFirstDayOfWeek(a.getFirstDayOfWeek()); b.setLenient(!a.isLenient()); if (a.hashCode() == b.hashCode()) { - errln("Calendar hash code ignores lenient setting"); + fail("Calendar hash code ignores lenient setting"); } b.setLenient(a.isLenient()); @@ -986,36 +1006,37 @@ public void Test4136399() { // of a reference -- this is true as of this writing b.getTimeZone().setRawOffset(a.getTimeZone().getRawOffset() + 60 * 60 * 1000); if (a.hashCode() == b.hashCode()) { - errln("Calendar hash code ignores zone"); + fail("Calendar hash code ignores zone"); } b.getTimeZone().setRawOffset(a.getTimeZone().getRawOffset()); GregorianCalendar c = new GregorianCalendar(); GregorianCalendar d = (GregorianCalendar) c.clone(); if (c.hashCode() != d.hashCode()) { - errln("GregorianCalendar hash code unequal for clones objects"); + fail("GregorianCalendar hash code unequal for clones objects"); } Date cutover = c.getGregorianChange(); d.setGregorianChange(new Date(cutover.getTime() + 24 * 60 * 60 * 1000)); if (c.hashCode() == d.hashCode()) { - errln("GregorianCalendar hash code ignores cutover"); + fail("GregorianCalendar hash code ignores cutover"); } } /** * GregorianCalendar.equals() ignores cutover date */ + @Test public void Test4141665() { GregorianCalendar cal = new GregorianCalendar(); GregorianCalendar cal2 = (GregorianCalendar) cal.clone(); Date cut = cal.getGregorianChange(); Date cut2 = new Date(cut.getTime() + 100 * 24 * 60 * 60 * 1000L); // 100 days later if (!cal.equals(cal2)) { - errln("Cloned GregorianCalendars not equal"); + fail("Cloned GregorianCalendars not equal"); } cal2.setGregorianChange(cut2); if (cal.equals(cal2)) { - errln("GregorianCalendar.equals() ignores cutover"); + fail("GregorianCalendar.equals() ignores cutover"); } } @@ -1023,16 +1044,17 @@ public void Test4141665() { * Bug states that ArrayIndexOutOfBoundsException is thrown by GregorianCalendar.roll() * when IllegalArgumentException should be. */ + @Test public void Test4142933() { GregorianCalendar calendar = new GregorianCalendar(); try { calendar.roll(-1, true); - errln("Test failed, no exception trown"); + fail("Test failed, no exception trown"); } catch (IllegalArgumentException e) { // OK: Do nothing // logln("Test passed"); } catch (Exception e) { - errln("Test failed. Unexpected exception is thrown: " + e); + fail("Test failed. Unexpected exception is thrown: " + e); e.printStackTrace(); } } @@ -1044,6 +1066,7 @@ public void Test4142933() { * report to therefore only check the behavior of a calendar with a zero raw * offset zone. */ + @Test public void Test4145158() { GregorianCalendar calendar = new GregorianCalendar(); @@ -1058,13 +1081,14 @@ public void Test4145158() { int era2 = calendar.get(ERA); if (year1 == year2 && era1 == era2) { - errln("Fail: Long.MIN_VALUE or Long.MAX_VALUE wrapping around"); + fail("Fail: Long.MIN_VALUE or Long.MAX_VALUE wrapping around"); } } /** * Maximum value for YEAR field wrong. */ + @Test public void Test4145983() { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTimeZone(TimeZone.getTimeZone("GMT")); @@ -1074,7 +1098,7 @@ public void Test4145983() { int year = calendar.get(YEAR); int maxYear = calendar.getMaximum(YEAR); if (year > maxYear) { - errln("Failed for " + DATES[i].getTime() + " ms: year=" + fail("Failed for " + DATES[i].getTime() + " ms: year=" + year + ", maxYear=" + maxYear); } } @@ -1086,6 +1110,7 @@ public void Test4145983() { * report test was written. In reality the bug is restricted to the DAY_OF_YEAR * field. - liu 6/29/98 */ + @Test public void Test4147269() { final String[] fieldName = { "ERA", @@ -1121,7 +1146,7 @@ public void Test4147269() { calendar.getTime(); // Force time computation // We expect an exception to be thrown. If we fall through // to the next line, then we have a bug. - errln("Test failed with field " + fieldName[field] + fail("Test failed with field " + fieldName[field] + ", date before: " + date + ", date after: " + calendar.getTime() + ", value: " + value + " (max = " + max + ")"); @@ -1135,6 +1160,7 @@ public void Test4147269() { * doesn't behave as a pure Julian calendar. * CANNOT REPRODUCE THIS BUG */ + @Test public void Test4149677() { TimeZone[] zones = {TimeZone.getTimeZone("GMT"), TimeZone.getTimeZone("PST"), @@ -1145,11 +1171,11 @@ public void Test4149677() { // Make sure extreme values don't wrap around calendar.setTime(new Date(Long.MIN_VALUE)); if (calendar.get(ERA) != GregorianCalendar.BC) { - errln("Fail: Date(Long.MIN_VALUE) has an AD year in " + zones[i]); + fail("Fail: Date(Long.MIN_VALUE) has an AD year in " + zones[i]); } calendar.setTime(new Date(Long.MAX_VALUE)); if (calendar.get(ERA) != GregorianCalendar.AD) { - errln("Fail: Date(Long.MAX_VALUE) has a BC year in " + zones[i]); + fail("Fail: Date(Long.MAX_VALUE) has a BC year in " + zones[i]); } calendar.setGregorianChange(new Date(Long.MAX_VALUE)); @@ -1157,9 +1183,9 @@ public void Test4149677() { boolean is100Leap = calendar.isLeapYear(100); if (!is100Leap) { - errln("test failed with zone " + zones[i].getID()); - errln(" cutover date is Date(Long.MAX_VALUE)"); - errln(" isLeapYear(100) returns: " + is100Leap); + fail("test failed with zone " + zones[i].getID() + + "\n cutover date is Date(Long.MAX_VALUE)" + + "\n isLeapYear(100) returns: " + is100Leap); } } } @@ -1168,6 +1194,7 @@ public void Test4149677() { * Calendar and Date HOUR broken. If HOUR is out-of-range, Calendar * and Date classes will misbehave. */ + @Test public void Test4162587() { TimeZone savedTz = TimeZone.getDefault(); TimeZone tz = TimeZone.getTimeZone("PST"); @@ -1178,29 +1205,29 @@ public void Test4162587() { try { for (int i = 0; i < 5; ++i) { if (i > 0) { - logln("---"); + System.out.println("---"); } cal.clear(); cal.set(1998, APRIL, 5, i, 0); d = cal.getTime(); String s0 = d.toString(); - logln("0 " + i + ": " + s0); + System.out.println("0 " + i + ": " + s0); cal.clear(); cal.set(1998, APRIL, 4, i + 24, 0); d = cal.getTime(); String sPlus = d.toString(); - logln("+ " + i + ": " + sPlus); + System.out.println("+ " + i + ": " + sPlus); cal.clear(); cal.set(1998, APRIL, 6, i - 24, 0); d = cal.getTime(); String sMinus = d.toString(); - logln("- " + i + ": " + sMinus); + System.out.println("- " + i + ": " + sMinus); if (!s0.equals(sPlus) || !s0.equals(sMinus)) { - errln("Fail: All three lines must match"); + fail("Fail: All three lines must match"); } } } finally { @@ -1211,27 +1238,29 @@ public void Test4162587() { /** * Adding 12 months behaves differently from adding 1 year */ + @Test public void Test4165343() { GregorianCalendar calendar = new GregorianCalendar(1996, FEBRUARY, 29); Date start = calendar.getTime(); - logln("init date: " + start); + System.out.println("init date: " + start); calendar.add(MONTH, 12); Date date1 = calendar.getTime(); - logln("after adding 12 months: " + date1); + System.out.println("after adding 12 months: " + date1); calendar.setTime(start); calendar.add(YEAR, 1); Date date2 = calendar.getTime(); - logln("after adding one year : " + date2); + System.out.println("after adding one year : " + date2); if (date1.equals(date2)) { - logln("Test passed"); + System.out.println("Test passed"); } else { - errln("Test failed"); + fail("Test failed"); } } /** * GregorianCalendar.getActualMaximum() does not account for first day of week. */ + @Test public void Test4166109() { /* Test month: * @@ -1249,7 +1278,7 @@ public void Test4166109() { GregorianCalendar calendar = new GregorianCalendar(Locale.US); calendar.set(1998, MARCH, 1); calendar.setMinimalDaysInFirstWeek(1); - logln("Date: " + calendar.getTime()); + System.out.println("Date: " + calendar.getTime()); int firstInMonth = calendar.get(DAY_OF_MONTH); @@ -1258,7 +1287,7 @@ public void Test4166109() { int returned = calendar.getActualMaximum(field); int expected = (31 + ((firstInMonth - firstInWeek + 7) % 7) + 6) / 7; - logln("First day of week = " + firstInWeek + System.out.println("First day of week = " + firstInWeek + " getActualMaximum(WEEK_OF_MONTH) = " + returned + " expected = " + expected + ((returned == expected) ? " ok" : " FAIL")); @@ -1268,7 +1297,7 @@ public void Test4166109() { } } if (!passed) { - errln("Test failed"); + fail("Test failed"); } } @@ -1279,6 +1308,7 @@ public void Test4166109() { * setGregorianChange didn't change object's date. But it was * changed. See 4928615. */ + @Test public void Test4167060() { int field = YEAR; DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy G", @@ -1293,7 +1323,7 @@ public void Test4167060() { String[] id = {"Hybrid", "Gregorian", "Julian"}; for (int k = 0; k < 3; ++k) { - logln("--- " + id[k] + " ---"); + System.out.println("--- " + id[k] + " ---"); for (int j = 0; j < dates.length; ++j) { GregorianCalendar calendar = new GregorianCalendar(); @@ -1308,8 +1338,8 @@ public void Test4167060() { Date dateBefore = calendar.getTime(); int maxYear = calendar.getActualMaximum(field); - logln("maxYear: " + maxYear + " for " + format.format(calendar.getTime())); - logln("date before: " + format.format(dateBefore)); + System.out.println("maxYear: " + maxYear + " for " + format.format(calendar.getTime())); + System.out.println("date before: " + format.format(dateBefore)); int[] years = {2000, maxYear - 1, maxYear, maxYear + 1}; @@ -1320,12 +1350,12 @@ public void Test4167060() { int newYear = calendar.get(field); calendar.setTime(dateBefore); // restore calendar for next use - logln(" Year " + years[i] + (valid ? " ok " : " bad") + System.out.println(" Year " + years[i] + (valid ? " ok " : " bad") + " => " + format.format(dateAfter)); if (valid && newYear != years[i]) { - errln(" FAIL: " + newYear + " should be valid; date, month and time shouldn't change"); + fail(" FAIL: " + newYear + " should be valid; date, month and time shouldn't change"); } else if (!valid && newYear == years[i]) { - errln(" FAIL: " + newYear + " should be invalid"); + fail(" FAIL: " + newYear + " should be invalid"); } } } @@ -1336,10 +1366,11 @@ public void Test4167060() { * Calendar.roll broken * This bug relies on the TimeZone bug 4173604 to also be fixed. */ + @Test public void Test4173516() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -1365,11 +1396,11 @@ public void Test4173516() { cal.roll(HOUR, 0x7F000000); cal.roll(HOUR, -0x7F000000); if (cal.getTime().getTime() != 0) { - errln("Hour rolling broken. expected 0, got " + cal.getTime().getTime()); + fail("Hour rolling broken. expected 0, got " + cal.getTime().getTime()); } for (int op = 0; op < 2; ++op) { - logln("Testing GregorianCalendar " + (op == 0 ? "add" : "roll")); + System.out.println("Testing GregorianCalendar " + (op == 0 ? "add" : "roll")); for (int field = 0; field < FIELD_COUNT; ++field) { if (field != ZONE_OFFSET @@ -1395,7 +1426,7 @@ public void Test4173516() { || cal.get(MINUTE) != fields[4] || cal.get(SECOND) != fields[5] || cal.get(MILLISECOND) != fields[6]) { - errln("Field " + field + fail("Field " + field + " (" + fieldNames[field] + ") FAIL, expected " + fields[0] @@ -1417,7 +1448,7 @@ public void Test4173516() { cal.set(fields[0], fields[1], fields[2], fields[3], fields[4], fields[5]); cal.set(MILLISECOND, fields[6]); - errln(cal.get(YEAR) + fail(cal.get(YEAR) + "/" + (cal.get(MONTH) + 1) + "/" + cal.get(DATE) + " " + cal.get(HOUR_OF_DAY) @@ -1435,7 +1466,7 @@ public void Test4173516() { long t = cal.getTime().getTime(); long delta = t - prev; prev = t; - errln((op == 0 ? "add(" : "roll(") + fail((op == 0 ? "add(" : "roll(") + fieldNames[field] + ", " + (i < limit ? "+" : "-") + "1) => " + cal.get(YEAR) @@ -1457,6 +1488,7 @@ public void Test4173516() { } } + @Test public void Test4174361() { GregorianCalendar calendar = new GregorianCalendar(1996, 1, 29); @@ -1470,13 +1502,14 @@ public void Test4174361() { int d2 = calendar.get(DAY_OF_MONTH); if (d1 != d2) { - errln("adding months to Feb 29 broken"); + fail("adding months to Feb 29 broken"); } } /** * Calendar does not update field values when setTimeZone is called. */ + @Test public void Test4177484() { TimeZone PST = TimeZone.getTimeZone("PST"); TimeZone EST = TimeZone.getTimeZone("EST"); @@ -1488,7 +1521,7 @@ public void Test4177484() { cal.setTimeZone(EST); int h2 = cal.get(HOUR_OF_DAY); if (h1 == h2) { - errln("FAIL: Fields not updated after setTimeZone"); + fail("FAIL: Fields not updated after setTimeZone"); } // getTime() must NOT change when time zone is changed. @@ -1500,13 +1533,14 @@ public void Test4177484() { cal.setTimeZone(EST); Date est10 = cal.getTime(); if (!pst10.equals(est10)) { - errln("FAIL: setTimeZone changed time"); + fail("FAIL: setTimeZone changed time"); } } /** * Week of year is wrong at the start and end of the year. */ + @Test public void Test4197699() { GregorianCalendar cal = new GregorianCalendar(); cal.setFirstDayOfWeek(MONDAY); @@ -1523,14 +1557,14 @@ public void Test4197699() { int expWOY = DATA[i++]; int actWOY = cal.get(WEEK_OF_YEAR); if (expWOY == actWOY) { - logln("Ok: " + fmt.format(cal.getTime())); + System.out.println("Ok: " + fmt.format(cal.getTime())); } else { - errln("FAIL: " + fmt.format(cal.getTime()) + fail("FAIL: " + fmt.format(cal.getTime()) + ", expected WOY=" + expWOY); cal.add(DATE, -8); for (int j = 0; j < 14; ++j) { cal.add(DATE, 1); - logln(fmt.format(cal.getTime())); + System.out.println(fmt.format(cal.getTime())); } } } @@ -1549,6 +1583,7 @@ public void Test4197699() { * WEEK_OF_YEAR + DAY_OF_WEEK */ @SuppressWarnings("deprecation") + @Test public void Test4209071() { Calendar cal = Calendar.getInstance(Locale.US); @@ -1625,7 +1660,7 @@ public void Test4209071() { Date act = cal.getTime(); if (!act.equals(exp)) { - errln("FAIL: Test " + (i / 2) + " got " + act + fail("FAIL: Test " + (i / 2) + " got " + act + ", want " + exp + " (see test/java/util/Calendar/CalendarRegression.java"); } @@ -1649,13 +1684,14 @@ public void Test4209071() { cal.set(YEAR, 1997); Date actual = cal.getTime(); if (!actual.equals(DATA[i + 1])) { - errln("FAIL: Sunday " + DATA[i] + fail("FAIL: Sunday " + DATA[i] + " of Jan 1997 -> " + actual + ", want " + DATA[i + 1]); } } } + @Test public void Test4288792() throws Exception { TimeZone savedTZ = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); @@ -1678,7 +1714,7 @@ public void Test4288792() throws Exception { cal.add(DATE, 1); int WOY = cal.get(WEEK_OF_YEAR); if (WOY != maxWeek) { - errln(cal.getTime() + ",got=" + WOY + fail(cal.getTime() + ",got=" + WOY + ",expected=" + maxWeek + ",min=" + j1 + ",first=" + j); } @@ -1687,7 +1723,7 @@ public void Test4288792() throws Exception { cal.add(DATE, 1); int WOY = cal.get(WEEK_OF_YEAR); if (WOY != 1) { - errln(cal.getTime() + ",got=" + WOY + fail(cal.getTime() + ",got=" + WOY + ",expected=1,min=" + j1 + ",first" + j); } } @@ -1698,6 +1734,7 @@ public void Test4288792() throws Exception { } } + @Test public void Test4328747() throws Exception { Calendar c = Calendar.getInstance(Locale.US); c.clear(); @@ -1718,7 +1755,7 @@ public void Test4328747() throws Exception { // Bug gives 1965 11 19 if ((result.get(YEAR) != 1966) || (result.get(MONTH) != 0) || (result.get(DATE) != 1)) { - errln("deserialized Calendar returned wrong date field(s): " + fail("deserialized Calendar returned wrong date field(s): " + result.get(YEAR) + "/" + result.get(MONTH) + "/" + result.get(DATE) + ", expected 1966/0/1"); } @@ -1728,6 +1765,7 @@ public void Test4328747() throws Exception { * Test whether Calendar can be serialized/deserialized correctly * even if invalid/customized TimeZone is used. */ + @Test public void Test4413980() { TimeZone savedTimeZone = TimeZone.getDefault(); try { @@ -1751,18 +1789,18 @@ public void Test4413980() { if (!c.equals(t.readObject())) { pass = false; - logln("Calendar instance which uses TimeZone <" + System.out.println("Calendar instance which uses TimeZone <" + IDs[i] + "> is incorrectly serialized/deserialized."); } else { - logln("Calendar instance which uses TimeZone <" + System.out.println("Calendar instance which uses TimeZone <" + IDs[i] + "> is correctly serialized/deserialized."); } } if (!pass) { - errln("Fail: Calendar serialization/equality bug"); + fail("Fail: Calendar serialization/equality bug"); } } catch (IOException | ClassNotFoundException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } finally { TimeZone.setDefault(savedTimeZone); @@ -1772,6 +1810,7 @@ public void Test4413980() { /** * 4546637: Incorrect WEEK_OF_MONTH after changing First Day Of Week */ + @Test public void Test4546637() { GregorianCalendar day = new GregorianCalendar(2001, NOVEMBER, 04); day.setMinimalDaysInFirstWeek(1); @@ -1779,13 +1818,14 @@ public void Test4546637() { day.setFirstDayOfWeek(MONDAY); if (day.get(WEEK_OF_MONTH) != 1) { - errln("Fail: 2001/11/4 must be the first week of the month."); + fail("Fail: 2001/11/4 must be the first week of the month."); } } /** * 4623997: GregorianCalendar returns bad WEEK_OF_YEAR */ + @Test public void Test4623997() { GregorianCalendar cal = new GregorianCalendar(2000, JANUARY, 1); @@ -1795,7 +1835,7 @@ public void Test4623997() { cal.setMinimalDaysInFirstWeek(4); if (cal.get(WEEK_OF_YEAR) != 52) { - errln("Fail: 2000/1/1 must be the 52nd week of the year."); + fail("Fail: 2000/1/1 must be the 52nd week of the year."); } } @@ -1805,11 +1845,12 @@ public void Test4623997() { *

Need to use SimpleDateFormat to test because a call to * get(int) changes internal states of a Calendar. */ + @Test public void Test4685354() { Locale locale = Locale.getDefault(); if (!TestUtils.usesAsciiDigits(locale) || !TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -1831,7 +1872,7 @@ public void Test4685354() { calendar.set(DAY_OF_MONTH, 0); s = df.format(calendar.getTime()); if (!expected.equals(s)) { - errln("DAY_OF_MONTH w/o ZONE_OFFSET: expected: " + expected + ", got: " + s); + fail("DAY_OF_MONTH w/o ZONE_OFFSET: expected: " + expected + ", got: " + s); } // The same thing must work with ZONE_OFFSET set @@ -1847,7 +1888,7 @@ public void Test4685354() { calendar.set(DAY_OF_MONTH, 0); s = df.format(calendar.getTime()); if (!expected.equals(s)) { - errln("DAY_OF_MONTH: expected: " + expected + ", got: " + s); + fail("DAY_OF_MONTH: expected: " + expected + ", got: " + s); } expected = "1999/12/24"; // 0th week of 2000 @@ -1867,7 +1908,7 @@ public void Test4685354() { calendar.set(WEEK_OF_YEAR, 0); s = df.format(calendar.getTime()); if (!expected.equals(s)) { - errln("WEEK_OF_YEAR: expected: " + expected + ", got: " + s); + fail("WEEK_OF_YEAR: expected: " + expected + ", got: " + s); } // change the state back calendar.clear(); @@ -1879,7 +1920,7 @@ public void Test4685354() { calendar.set(WEEK_OF_MONTH, 0); s = df.format(calendar.getTime()); if (!expected.equals(s)) { - errln("WEEK_OF_MONTH: expected: " + expected + ", got: " + s); + fail("WEEK_OF_MONTH: expected: " + expected + ", got: " + s); } // Make sure the time fields work correctly. @@ -1903,7 +1944,7 @@ public void Test4685354() { // time should be back to 22:59:59. s = df.format(calendar.getTime()); if (!expected.equals(s)) { - errln("MINUTE: expected: " + expected + ", got: " + s); + fail("MINUTE: expected: " + expected + ", got: " + s); } } @@ -1913,10 +1954,11 @@ public void Test4685354() { *

Need to use SimpleDateFormat to test because a call to * get(int) changes internal states of a Calendar. */ + @Test public void Test4655637() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -1935,7 +1977,7 @@ public void Test4655637() { String expected = "2001/01/08"; String s = df.format(cal.getTime()); if (!expected.equals(s)) { - errln("expected: " + expected + ", got: " + s); + fail("expected: " + expected + ", got: " + s); } } @@ -1947,6 +1989,7 @@ public void Test4655637() { * *

This test case throws ArrayIndexOutOfBoundsException without the fix. */ + @Test public void Test4683492() { Calendar cal = new GregorianCalendar(2002, 3, 29, 10, 0, 0); cal.set(DAY_OF_WEEK, FRIDAY); @@ -1956,13 +1999,14 @@ public void Test4683492() { String expected = "2003/01/31"; String s = df.format(cal.getTime()); if (!expected.equals(s)) { - errln("expected: " + expected + ", got: " + s); + fail("expected: " + expected + ", got: " + s); } } /** * 4080631: Calendar.hashCode is amazingly bad */ + @Test public void Test4080631() { Calendar cal = Calendar.getInstance(); int h1 = cal.hashCode(); @@ -1971,16 +2015,16 @@ public void Test4080631() { Calendar cal2 = (Calendar) cal.clone(); cal.add(MILLISECOND, +1); int h3 = cal.hashCode(); - logln("hash code: h1=" + h1 + ", h2=" + h2 + ", h3=" + h3); + System.out.println("hash code: h1=" + h1 + ", h2=" + h2 + ", h3=" + h3); if (h1 == h2 || h1 == h3 || h2 == h3) { - errln("hash code is poor: hashCode=" + h1); + fail("hash code is poor: hashCode=" + h1); } h2 = cal2.hashCode(); cal.add(MILLISECOND, -1); int h4 = cal.hashCode(); - logln("hash code: h2=" + h2 + ", h4=" + h4); + System.out.println("hash code: h2=" + h2 + ", h4=" + h4); if (cal.equals(cal2) && h2 != h4) { - errln("broken hash code: h2=" + h2 + ", h4=" + h4); + fail("broken hash code: h2=" + h2 + ", h4=" + h4); } int x = cal.getFirstDayOfWeek() + 3; if (x > SATURDAY) { @@ -1988,9 +2032,9 @@ public void Test4080631() { } cal.setFirstDayOfWeek(x); int h5 = cal.hashCode(); - logln("hash code: h4=" + h4 + ", h5=" + h5); + System.out.println("hash code: h4=" + h4 + ", h5=" + h5); if (h4 == h5) { - errln("has code is poor with first day of week param: hashCode=" + h4); + fail("has code is poor with first day of week param: hashCode=" + h4); } } @@ -1998,6 +2042,7 @@ public void Test4080631() { * 4125161: RFE: GregorianCalendar needs more era names (BCE and CE) */ /* + @Test public void Test4125161() throws Exception { Class gc = GregorianCalendar.class; Field f; @@ -2005,86 +2050,89 @@ public void Test4125161() throws Exception { f = gc.getDeclaredField("BCE"); mod = f.getModifiers(); if (!Modifier.isStatic(mod) || !Modifier.isFinal(mod)) { - errln("BCE: wrong modifiers: " + mod); + fail("BCE: wrong modifiers: " + mod); } f = gc.getDeclaredField("CE"); mod = f.getModifiers(); if (!Modifier.isStatic(mod) || !Modifier.isFinal(mod)) { - errln("CE: wrong modifiers: " + mod); + fail("CE: wrong modifiers: " + mod); } if (GregorianCalendar.BCE != GregorianCalendar.BC || GregorianCalendar.CE != GregorianCalendar.AD) { - errln("Wrong BCE and/or CE values"); + fail("Wrong BCE and/or CE values"); } } */ /** * 4167995: GregorianCalendar.setGregorianChange() not to spec */ + @Test public void Test4167995() { Koyomi gc = new Koyomi(TimeZone.getTimeZone("GMT")); - logln("Hybrid: min date"); + System.out.println("Hybrid: min date"); gc.setTime(new Date(Long.MIN_VALUE)); if (!gc.checkDate(292269055, DECEMBER, 2, SUNDAY) || !gc.checkFieldValue(ERA, GregorianCalendar.BC)) { - errln(gc.getMessage()); + fail(gc.getMessage()); } - logln("Hybrid: max date"); + System.out.println("Hybrid: max date"); gc.setTime(new Date(Long.MAX_VALUE)); if (!gc.checkDate(292278994, AUGUST, 17, SUNDAY) || !gc.checkFieldValue(ERA, GregorianCalendar.AD)) { - errln(gc.getMessage()); + fail(gc.getMessage()); } gc.setGregorianChange(new Date(Long.MIN_VALUE)); - logln("Gregorian: min date"); + System.out.println("Gregorian: min date"); gc.setTime(new Date(Long.MIN_VALUE)); if (!gc.checkDate(292275056, MAY, 16, SUNDAY) || !gc.checkFieldValue(ERA, GregorianCalendar.BC)) { - errln(gc.getMessage()); + fail(gc.getMessage()); } - logln("Gregorian: max date"); + System.out.println("Gregorian: max date"); gc.setTime(new Date(Long.MAX_VALUE)); if (!gc.checkDate(292278994, AUGUST, 17, SUNDAY) || !gc.checkFieldValue(ERA, GregorianCalendar.AD)) { - errln(gc.getMessage()); + fail(gc.getMessage()); } gc.setGregorianChange(new Date(Long.MAX_VALUE)); - logln("Julian: min date"); + System.out.println("Julian: min date"); gc.setTime(new Date(Long.MIN_VALUE)); if (!gc.checkDate(292269055, DECEMBER, 2, SUNDAY) || !gc.checkFieldValue(ERA, GregorianCalendar.BC)) { - errln(gc.getMessage()); + fail(gc.getMessage()); } - logln("Julian: max date"); + System.out.println("Julian: max date"); gc.setTime(new Date(Long.MAX_VALUE)); if (!gc.checkDate(292272993, JANUARY, 4, SUNDAY) || !gc.checkFieldValue(ERA, GregorianCalendar.AD)) { - errln(gc.getMessage()); + fail(gc.getMessage()); } } /** * 4340146: Calendar.equals modifies state */ + @Test public void Test4340146() { Koyomi cal = new Koyomi(); cal.clear(); cal.set(2003, OCTOBER, 32); cal.equals(new Koyomi()); if (!cal.checkInternalDate(2003, OCTOBER, 32)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } new Koyomi().equals(cal); if (!cal.checkInternalDate(2003, OCTOBER, 32)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } /** * 4639407: GregorianCalendar doesn't work in non-lenient due to timezone bounds checking */ + @Test public void Test4639407() { // The following operations in non-lenient mode shouldn't // throw IllegalArgumentException. @@ -2100,6 +2148,7 @@ public void Test4639407() { /** * 4652815: rolling week-of-year back hundreds of weeks changes year */ + @Test public void Test4652815() { Koyomi cal = new Koyomi(Locale.US); testRoll(cal, 2003, SEPTEMBER, 29); @@ -2112,18 +2161,18 @@ private void testRoll(Koyomi cal, int year, int month, int dayOfMonth) { cal.clear(); cal.set(year, month, dayOfMonth); cal.getTime(); // normalize fields - logln("Roll backwards from " + cal.toDateString()); + System.out.println("Roll backwards from " + cal.toDateString()); for (int i = 0; i < 1000; i++) { cal.roll(WEEK_OF_YEAR, -i); if (!cal.checkFieldValue(YEAR, year)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } - logln("Roll forewards from " + cal.toDateString()); + System.out.println("Roll forewards from " + cal.toDateString()); for (int i = 0; i < 1000; i++) { cal.roll(WEEK_OF_YEAR, +i); if (!cal.checkFieldValue(YEAR, year)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } } @@ -2131,47 +2180,50 @@ private void testRoll(Koyomi cal, int year, int month, int dayOfMonth) { /** * 4652830: GregorianCalendar roll behaves unexpectedly for dates in BC era */ + @Test public void Test4652830() { Koyomi cal = new Koyomi(Locale.US); cal.clear(); - logln("BCE 9-2-28 (leap year) roll DAY_OF_MONTH++ twice"); + System.out.println("BCE 9-2-28 (leap year) roll DAY_OF_MONTH++ twice"); cal.set(ERA, GregorianCalendar.BC); cal.set(9, FEBRUARY, 28); if (cal.getActualMaximum(DAY_OF_YEAR) != 366) { - errln(" wrong actual max of DAY_OF_YEAR: got " + fail(" wrong actual max of DAY_OF_YEAR: got " + cal.getActualMaximum(DAY_OF_YEAR) + " expected " + 366); } cal.roll(DAY_OF_MONTH, +1); if (!cal.checkFieldValue(ERA, GregorianCalendar.BC) || !cal.checkDate(9, FEBRUARY, 29)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } cal.roll(DAY_OF_MONTH, +1); if (!cal.checkFieldValue(ERA, GregorianCalendar.BC) || !cal.checkDate(9, FEBRUARY, 1)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } /** * 4740554: GregorianCalendar.getActualMaximum is inconsistent with normalization */ + @Test public void Test4740554() { - logln("1999/(Feb+12)/1 should be normalized to 2000/Feb/1 for getActualMaximum"); + System.out.println("1999/(Feb+12)/1 should be normalized to 2000/Feb/1 for getActualMaximum"); Koyomi cal = new Koyomi(Locale.US); cal.clear(); cal.set(1999, FEBRUARY + 12, 1); if (!cal.checkActualMaximum(DAY_OF_YEAR, 366)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkActualMaximum(DAY_OF_MONTH, 29)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } /** * 4936355: GregorianCalendar causes overflow/underflow with time of day calculation */ + @Test public void Test4936355() { Koyomi cal = new Koyomi(TimeZone.getTimeZone("GMT")); cal.clear(); @@ -2213,7 +2265,7 @@ private void checkTimeCalculation(Koyomi cal, int field, int value, long expecte long time2 = cal.getTimeInMillis(); if ((time + expectedDelta) != time2) { String s = value == Integer.MAX_VALUE ? "Integer.MAX_VALUE" : "Integer.MIN_VALUE"; - errln("set(" + Koyomi.getFieldName(field) + ", " + s + ") failed." + " got " + time2 + fail("set(" + Koyomi.getFieldName(field) + ", " + s + ") failed." + " got " + time2 + ", expected " + (time + expectedDelta)); } } @@ -2222,6 +2274,7 @@ private void checkTimeCalculation(Koyomi cal, int field, int value, long expecte * 4722650: Calendar.equals can throw an exception in non-lenient * (piggy-back tests for compareTo() which is new in 1.5) */ + @Test public void Test4722650() { Calendar cal1 = new GregorianCalendar(); cal1.clear(); @@ -2233,26 +2286,26 @@ public void Test4722650() { cal2.set(2003, OCTOBER, 31); try { if (cal1.equals(cal2)) { - errln("lenient and non-lenient shouldn't be equal. (2003/10/31)"); + fail("lenient and non-lenient shouldn't be equal. (2003/10/31)"); } if (cal1.compareTo(cal2) != 0) { - errln("cal1 and cal2 should represent the same time. (2003/10/31)"); + fail("cal1 and cal2 should represent the same time. (2003/10/31)"); } } catch (IllegalArgumentException e) { - errln("equals threw IllegalArugumentException with non-lenient"); + fail("equals threw IllegalArugumentException with non-lenient"); } cal1.set(2003, OCTOBER, 32); cal2.set(2003, OCTOBER, 32); try { if (cal1.equals(cal2)) { - errln("lenient and non-lenient shouldn't be equal. (2003/10/32)"); + fail("lenient and non-lenient shouldn't be equal. (2003/10/32)"); } if (cal1.compareTo(cal2) != 0) { - errln("cal1 and cal2 should represent the same time. (2003/10/32)"); + fail("cal1 and cal2 should represent the same time. (2003/10/32)"); } } catch (IllegalArgumentException e) { - errln("equals threw IllegalArugumentException with non-lenient"); + fail("equals threw IllegalArugumentException with non-lenient"); } cal1 = Calendar.getInstance(new Locale("th", "TH")); @@ -2260,48 +2313,49 @@ public void Test4722650() { cal2 = Calendar.getInstance(Locale.US); cal2.setTimeInMillis(0L); if (cal1.equals(cal2)) { - errln("Buddhist.equals(Gregorian) shouldn't be true. (millis=0)"); + fail("Buddhist.equals(Gregorian) shouldn't be true. (millis=0)"); } if (cal1.compareTo(cal2) != 0) { - errln("cal1 (Buddhist) and cal2 (Gregorian) should represent the same time. (millis=0)"); + fail("cal1 (Buddhist) and cal2 (Gregorian) should represent the same time. (millis=0)"); } } /** * 4738710: API: Calendar comparison methods should be improved */ + @Test public void Test4738710() { Calendar cal0 = new GregorianCalendar(2003, SEPTEMBER, 30); Comparable cal1 = new GregorianCalendar(2003, OCTOBER, 1); Calendar cal2 = new GregorianCalendar(2003, OCTOBER, 2); if (!(cal1.compareTo(cal0) > 0)) { - errln("!(cal1 > cal0)"); + fail("!(cal1 > cal0)"); } if (!(cal1.compareTo(cal2) < 0)) { - errln("!(cal1 < cal2)"); + fail("!(cal1 < cal2)"); } if (cal1.compareTo(new GregorianCalendar(2003, OCTOBER, 1)) != 0) { - errln("cal1 != new GregorianCalendar(2003, OCTOBER, 1)"); + fail("cal1 != new GregorianCalendar(2003, OCTOBER, 1)"); } if (cal0.after(cal2)) { - errln("cal0 shouldn't be after cal2"); + fail("cal0 shouldn't be after cal2"); } if (cal2.before(cal0)) { - errln("cal2 shouldn't be before cal0"); + fail("cal2 shouldn't be before cal0"); } if (cal0.after(0)) { - errln("cal0.after() returned true with an Integer."); + fail("cal0.after() returned true with an Integer."); } if (cal0.before(0)) { - errln("cal0.before() returned true with an Integer."); + fail("cal0.before() returned true with an Integer."); } if (cal0.after(null)) { - errln("cal0.after() returned true with null."); + fail("cal0.after() returned true with null."); } if (cal0.before(null)) { - errln("cal0.before() returned true with null."); + fail("cal0.before() returned true with null."); } } @@ -2309,6 +2363,7 @@ public void Test4738710() { * 4633646: Setting WEEK_OF_MONTH to 1 results in incorrect date */ @SuppressWarnings("deprecation") + @Test public void Test4633646() { Koyomi cal = new Koyomi(Locale.US); cal.setTime(new Date(2002 - 1900, 1 - 1, 28)); @@ -2334,15 +2389,15 @@ void sub4633646(Koyomi cal) { cal.set(WEEK_OF_MONTH, 1); if (cal.isLenient()) { if (!cal.checkDate(2001, DECEMBER, 31)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkFieldValue(WEEK_OF_MONTH, 6)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } else { try { Date d = cal.getTime(); - errln("didn't throw IllegalArgumentException in non-lenient"); + fail("didn't throw IllegalArgumentException in non-lenient"); } catch (IllegalArgumentException e) { } } @@ -2352,6 +2407,7 @@ void sub4633646(Koyomi cal) { * 4846659: Calendar: Both set() and roll() don't work for AM_PM time field * (Partially fixed only roll as of 1.5) */ + @Test public void Test4846659() { Koyomi cal = new Koyomi(); cal.clear(); @@ -2360,7 +2416,7 @@ public void Test4846659() { // Test roll() cal.roll(AM_PM, +1); // should turn to PM if (!cal.checkFieldValue(HOUR_OF_DAY, 10 + 12)) { - errln("roll: AM_PM didn't change to PM"); + fail("roll: AM_PM didn't change to PM"); } cal.clear(); @@ -2369,7 +2425,7 @@ public void Test4846659() { // Test set() cal.set(AM_PM, PM); // should turn to PM if (!cal.checkFieldValue(HOUR_OF_DAY, 10 + 12)) { - errln("set: AM_PM didn't change to PM"); + fail("set: AM_PM didn't change to PM"); } cal.clear(); @@ -2378,13 +2434,14 @@ public void Test4846659() { cal.set(AM_PM, PM); cal.set(HOUR, 9); if (!cal.checkFieldValue(HOUR_OF_DAY, 9 + 12)) { - errln("set: both AM_PM and HOUT didn't change to PM"); + fail("set: both AM_PM and HOUT didn't change to PM"); } } /** * 4822110: GregorianCalendar.get() returns an incorrect date after setFirstDayOfWeek() */ + @Test public void Test4822110() { Koyomi cal = new Koyomi(Locale.US); // June 2003 @@ -2401,17 +2458,18 @@ public void Test4822110() { cal.setFirstDayOfWeek(MONDAY); // Now 6/2 to 6/8 should be the 2nd week of June. Sunday of // that week is 6/8. - logln("1: " + cal.get(WEEK_OF_MONTH) + ", " + cal.get(DAY_OF_MONTH)); + System.out.println("1: " + cal.get(WEEK_OF_MONTH) + ", " + cal.get(DAY_OF_MONTH)); cal.set(DAY_OF_WEEK, SUNDAY); - logln("1st Sunday of June 2003 with FirstDayOfWeek=MONDAY"); + System.out.println("1st Sunday of June 2003 with FirstDayOfWeek=MONDAY"); if (!cal.checkDate(2003, JUNE, 8)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } /** * 4973919: Inconsistent GregorianCalendar hashCode before and after serialization */ + @Test public void Test4966499() throws Exception { GregorianCalendar date1 = new GregorianCalendar(2004, JANUARY, 7); @@ -2428,10 +2486,10 @@ public void Test4966499() throws Exception { GregorianCalendar date2 = (GregorianCalendar) ois.readObject(); if (!date1.equals(date2)) { - errln("date1.equals(date2) != true"); + fail("date1.equals(date2) != true"); } if (date1.hashCode() != date2.hashCode()) { - errln("inconsistent hashCode() value (before=0x" + fail("inconsistent hashCode() value (before=0x" + Integer.toHexString(date1.hashCode()) + ", after=0x" + Integer.toHexString(date2.hashCode()) + ")"); } @@ -2440,54 +2498,56 @@ public void Test4966499() throws Exception { /** * 4980088: GregorianCalendar.getActualMaximum doesn't throw exception */ + @Test public void Test4980088() { GregorianCalendar cal = new GregorianCalendar(); try { int x = cal.getMaximum(100); - errln("getMaximum(100) didn't throw an exception."); + fail("getMaximum(100) didn't throw an exception."); } catch (IndexOutOfBoundsException e) { - logln("getMaximum: " + e.getClass().getName() + ": " + e.getMessage()); + System.out.println("getMaximum: " + e.getClass().getName() + ": " + e.getMessage()); } try { int x = cal.getLeastMaximum(100); - errln("getLeastMaximum(100) didn't throw an exception."); + fail("getLeastMaximum(100) didn't throw an exception."); } catch (IndexOutOfBoundsException e) { - logln("getLeastMaximum: " + e.getClass().getName() + ": " + e.getMessage()); + System.out.println("getLeastMaximum: " + e.getClass().getName() + ": " + e.getMessage()); } try { int x = cal.getActualMaximum(100); - errln("getActualMaximum(100) didn't throw an exception."); + fail("getActualMaximum(100) didn't throw an exception."); } catch (IndexOutOfBoundsException e) { - logln("getActualMaximum: " + e.getClass().getName() + ": " + e.getMessage()); + System.out.println("getActualMaximum: " + e.getClass().getName() + ": " + e.getMessage()); } try { int x = cal.getMinimum(100); - errln("getMinimum(100) didn't throw an exception."); + fail("getMinimum(100) didn't throw an exception."); } catch (IndexOutOfBoundsException e) { - logln("getMinimum: " + e.getClass().getName() + ": " + e.getMessage()); + System.out.println("getMinimum: " + e.getClass().getName() + ": " + e.getMessage()); } try { int x = cal.getGreatestMinimum(100); - errln("getGreatestMinimum(100) didn't throw an exception."); + fail("getGreatestMinimum(100) didn't throw an exception."); } catch (IndexOutOfBoundsException e) { - logln("getGreatestMinimum: " + e.getClass().getName() + ": " + e.getMessage()); + System.out.println("getGreatestMinimum: " + e.getClass().getName() + ": " + e.getMessage()); } try { int x = cal.getActualMinimum(100); - errln("getActualMinimum(100) didn't throw an exception."); + fail("getActualMinimum(100) didn't throw an exception."); } catch (IndexOutOfBoundsException e) { - logln("getActualMinimum: " + e.getClass().getName() + ": " + e.getMessage()); + System.out.println("getActualMinimum: " + e.getClass().getName() + ": " + e.getMessage()); } } /** * 4965624: GregorianCalendar.isLeapYear(1000) returns incorrect value */ + @Test public void Test4965624() { // 5013094: This test case needs to use "GMT" to specify // Gregorian cutover dates. @@ -2509,7 +2569,7 @@ public void Test4965624() { GregorianCalendar cal = new GregorianCalendar(); cal.setGregorianChange(d); if (cal.isLeapYear(1000) != expected) { - errln("isLeapYear(1000) returned " + cal.isLeapYear(1000) + fail("isLeapYear(1000) returned " + cal.isLeapYear(1000) + " with cutover date (Julian) " + d); } }); @@ -2532,16 +2592,17 @@ static Date getGregorianDate(int year, int month, int dayOfMonth) { /** * 5006864: Define the minimum value of DAY_OF_WEEK_IN_MONTH as 1 */ + @Test public void Test5006864() { GregorianCalendar cal = new GregorianCalendar(); int min = cal.getMinimum(DAY_OF_WEEK_IN_MONTH); if (min != 1) { - errln("GregorianCalendar.getMinimum(DAY_OF_WEEK_IN_MONTH) returned " + fail("GregorianCalendar.getMinimum(DAY_OF_WEEK_IN_MONTH) returned " + min + ", expected 1."); } min = cal.getGreatestMinimum(DAY_OF_WEEK_IN_MONTH); if (min != 1) { - errln("GregorianCalendar.getGreatestMinimum(DAY_OF_WEEK_IN_MONTH) returned " + fail("GregorianCalendar.getGreatestMinimum(DAY_OF_WEEK_IN_MONTH) returned " + min + ", expected 1."); } } diff --git a/test/jdk/java/util/Calendar/CalendarTest.java b/test/jdk/java/util/Calendar/CalendarTest.java index 432d31b8d54..91a7ad813d3 100644 --- a/test/jdk/java/util/Calendar/CalendarTest.java +++ b/test/jdk/java/util/Calendar/CalendarTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,7 @@ * @summary test for Calendar * @library /java/text/testlib * @modules java.base/java.util:+open - * @run main CalendarTest + * @run junit CalendarTest * @key randomness */ @@ -48,18 +48,19 @@ import static java.util.Calendar.*; -public class CalendarTest extends IntlTest { +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class CalendarTest { static final int ONE_DAY = 24 * 60 * 60 * 1000; static final int EPOCH_JULIAN = 2440588; - public static void main(String argv[]) throws Exception { - new CalendarTest().run(argv); - } - /** * Test the behavior of the GregorianCalendar around the changeover. */ + @Test public void TestGregorianChangeover() { TimeZone savedZone = TimeZone.getDefault(); /* @@ -97,10 +98,10 @@ public void TestGregorianChangeover() { int dom = cal.get(DATE); int dow = cal.get(DAY_OF_WEEK); - logln("Changeover " + (i >= 0 ? "+" : "") + i + System.out.println("Changeover " + (i >= 0 ? "+" : "") + i + " days: " + y + "/" + mon + "/" + dom + " dow=" + dow); if (y != 1582 || mon != MON[j] || dom != DOM[j] || dow != DOW[j]) { - errln(" Fail: Above line is wrong"); + fail(" Fail: Above line is wrong"); } } } finally { @@ -114,6 +115,7 @@ public void TestGregorianChangeover() { * (first day of week, minimal days in first week). */ @SuppressWarnings("deprecation") + @Test public void TestMapping() { TimeZone saveZone = TimeZone.getDefault(); int[] DATA = { @@ -160,9 +162,9 @@ public void TestMapping() { + year2 + "-" + (month2 + 1 - JANUARY) + "-" + dom2; if (delta != 0 || year != year2 || month != month2 || dom != dom2) { - errln(s + " FAIL"); + fail(s + " FAIL"); } else { - logln(s); + System.out.println(s); } // Test Julian computation @@ -184,9 +186,9 @@ public void TestMapping() { + year2 + "-" + (month2 + 1 - JANUARY) + "-" + dom2; if (delta != 0 || year != year2 || month != month2 || dom != dom2) { - errln(s + " FAIL"); + fail(s + " FAIL"); } else { - logln(s); + System.out.println(s); } } @@ -212,16 +214,17 @@ private void auxMapping(Calendar cal, int y, int m, int d) { int month2 = cal.get(MONTH); int dom2 = cal.get(DAY_OF_MONTH); if (y != year2 || m != month2 || dom2 != d) { - errln("Round-trip failure: " + y + "-" + (m + 1) + "-" + d + " =>ms=> " + fail("Round-trip failure: " + y + "-" + (m + 1) + "-" + d + " =>ms=> " + year2 + "-" + (month2 + 1) + "-" + dom2); } } @SuppressWarnings("deprecation") + @Test public void TestGenericAPI() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -235,7 +238,7 @@ public void TestGenericAPI() { Calendar cal = Calendar.getInstance((SimpleTimeZone) zone.clone()); if (!zone.equals(cal.getTimeZone())) { - errln("FAIL: Calendar.getTimeZone failed"); + fail("FAIL: Calendar.getTimeZone failed"); } Calendar cal2 = Calendar.getInstance(cal.getTimeZone()); @@ -244,27 +247,27 @@ public void TestGenericAPI() { cal2.setTime(when); if (!(cal.equals(cal2))) { - errln("FAIL: Calendar.operator== failed"); + fail("FAIL: Calendar.operator== failed"); } // if ((*cal != *cal2)) errln("FAIL: Calendar.operator!= failed"); if (!cal.equals(cal2) || cal.before(cal2) || cal.after(cal2)) { - errln("FAIL: equals/before/after failed"); + fail("FAIL: equals/before/after failed"); } cal2.setTime(new Date(when.getTime() + 1000)); if (cal.equals(cal2) || cal2.before(cal) || cal.after(cal2)) { - errln("FAIL: equals/before/after failed"); + fail("FAIL: equals/before/after failed"); } cal.roll(SECOND, true); if (!cal.equals(cal2) || cal.before(cal2) || cal.after(cal2)) { - errln("FAIL: equals/before/after failed"); + fail("FAIL: equals/before/after failed"); } // Roll back to January @@ -272,20 +275,20 @@ public void TestGenericAPI() { if (cal.equals(cal2) || cal2.before(cal) || cal.after(cal2)) { - errln("FAIL: equals/before/after failed"); + fail("FAIL: equals/before/after failed"); } // C++ only /* TimeZone z = cal.orphanTimeZone(); if (z.getID(str) != tzid || z.getRawOffset() != tzoffset) - errln("FAIL: orphanTimeZone failed"); + fail("FAIL: orphanTimeZone failed"); */ for (int i = 0; i < 2; ++i) { boolean lenient = (i > 0); cal.setLenient(lenient); if (lenient != cal.isLenient()) { - errln("FAIL: setLenient/isLenient failed"); + fail("FAIL: setLenient/isLenient failed"); } // Later: Check for lenient behavior } @@ -294,26 +297,26 @@ public void TestGenericAPI() { for (i = SUNDAY; i <= SATURDAY; ++i) { cal.setFirstDayOfWeek(i); if (cal.getFirstDayOfWeek() != i) { - errln("FAIL: set/getFirstDayOfWeek failed"); + fail("FAIL: set/getFirstDayOfWeek failed"); } } for (i = 0; i <= 7; ++i) { cal.setMinimalDaysInFirstWeek(i); if (cal.getMinimalDaysInFirstWeek() != i) { - errln("FAIL: set/getFirstDayOfWeek failed"); + fail("FAIL: set/getFirstDayOfWeek failed"); } } for (i = 0; i < FIELD_COUNT; ++i) { if (cal.getMinimum(i) != cal.getGreatestMinimum(i)) { - errln("FAIL: getMinimum doesn't match getGreatestMinimum for field " + i); + fail("FAIL: getMinimum doesn't match getGreatestMinimum for field " + i); } if (cal.getLeastMaximum(i) > cal.getMaximum(i)) { - errln("FAIL: getLeastMaximum larger than getMaximum for field " + i); + fail("FAIL: getLeastMaximum larger than getMaximum for field " + i); } if (cal.getMinimum(i) >= cal.getMaximum(i)) { - errln("FAIL: getMinimum not less than getMaximum for field " + i); + fail("FAIL: getMinimum not less than getMaximum for field " + i); } } @@ -321,22 +324,22 @@ public void TestGenericAPI() { cal.clear(); cal.set(1984, 5, 24); if (cal.getTime().getTime() != new Date(84, 5, 24).getTime()) { - errln("FAIL: Calendar.set(3 args) failed"); - logln(" Got: " + cal.getTime() + " Expected: " + new Date(84, 5, 24)); + fail("FAIL: Calendar.set(3 args) failed"); + System.out.println(" Got: " + cal.getTime() + " Expected: " + new Date(84, 5, 24)); } cal.clear(); cal.set(1985, 3, 2, 11, 49); if (cal.getTime().getTime() != new Date(85, 3, 2, 11, 49).getTime()) { - errln("FAIL: Calendar.set(5 args) failed"); - logln(" Got: " + cal.getTime() + " Expected: " + new Date(85, 3, 2, 11, 49)); + fail("FAIL: Calendar.set(5 args) failed"); + System.out.println(" Got: " + cal.getTime() + " Expected: " + new Date(85, 3, 2, 11, 49)); } cal.clear(); cal.set(1995, 9, 12, 1, 39, 55); if (cal.getTime().getTime() != new Date(95, 9, 12, 1, 39, 55).getTime()) { - errln("FAIL: Calendar.set(6 args) failed"); - logln(" Got: " + cal.getTime() + " Expected: " + new Date(95, 9, 12, 1, 39, 55)); + fail("FAIL: Calendar.set(6 args) failed"); + System.out.println(" Got: " + cal.getTime() + " Expected: " + new Date(95, 9, 12, 1, 39, 55)); } cal.getTime(); @@ -349,17 +352,17 @@ public void TestGenericAPI() { case MINUTE: case SECOND: if (!cal.isSet(i)) { - errln("FAIL: !Calendar.isSet test failed: " + calendarFieldNames[i]); + fail("FAIL: !Calendar.isSet test failed: " + calendarFieldNames[i]); } break; default: if (cal.isSet(i)) { - errln("FAIL: Calendar.isSet test failed: " + calendarFieldNames[i]); + fail("FAIL: Calendar.isSet test failed: " + calendarFieldNames[i]); } } cal.clear(i); if (cal.isSet(i)) { - errln("FAIL: Calendar.clear/isSet failed"); + fail("FAIL: Calendar.clear/isSet failed"); } } @@ -368,7 +371,7 @@ public void TestGenericAPI() { Locale[] loc = Calendar.getAvailableLocales(); long count = loc.length; if (count < 1 || loc == null) { - errln("FAIL: getAvailableLocales failed"); + fail("FAIL: getAvailableLocales failed"); } else { for (i = 0; i < count; ++i) { cal = Calendar.getInstance(loc[i]); @@ -399,13 +402,13 @@ public void TestGenericAPI() { gc = new GregorianCalendar(1998, 10, 14, 21, 43); if (gc.getTime().getTime() != new Date(98, 10, 14, 21, 43).getTime()) { - errln("FAIL: new GregorianCalendar(ymdhm) failed"); + fail("FAIL: new GregorianCalendar(ymdhm) failed"); } // delete gc; gc = new GregorianCalendar(1998, 10, 14, 21, 43, 55); if (gc.getTime().getTime() != new Date(98, 10, 14, 21, 43, 55).getTime()) { - errln("FAIL: new GregorianCalendar(ymdhms) failed"); + fail("FAIL: new GregorianCalendar(ymdhms) failed"); } // C++ only: @@ -417,6 +420,7 @@ public void TestGenericAPI() { } // Verify Roger Webster's bug + @Test public void TestRog() { GregorianCalendar gc = new GregorianCalendar(); @@ -432,12 +436,13 @@ public void TestRog() { if (gc.get(YEAR) != year || gc.get(MONTH) != month || gc.get(DATE) != (date + i)) { - errln("FAIL: Date " + gc.getTime() + " wrong"); + fail("FAIL: Date " + gc.getTime() + " wrong"); } } } // Verify DAY_OF_WEEK + @Test public void TestDOW943() { dowTest(false); dowTest(true); @@ -453,18 +458,19 @@ void dowTest(boolean lenient) { int min = cal.getMinimum(DAY_OF_WEEK); int max = cal.getMaximum(DAY_OF_WEEK); if (dow < min || dow > max) { - errln("FAIL: Day of week " + dow + " out of range"); + fail("FAIL: Day of week " + dow + " out of range"); } if (dow != SUNDAY) { - errln("FAIL2: Day of week should be SUNDAY; is " + dow + ": " + cal.getTime()); + fail("FAIL2: Day of week should be SUNDAY; is " + dow + ": " + cal.getTime()); } if (min != SUNDAY || max != SATURDAY) { - errln("FAIL: Min/max bad"); + fail("FAIL: Min/max bad"); } } // Verify that the clone method produces distinct objects with no // unintentionally shared fields. + @Test public void TestClonesUnique908() { Calendar c = Calendar.getInstance(); Calendar d = (Calendar) c.clone(); @@ -472,31 +478,33 @@ public void TestClonesUnique908() { d.set(MILLISECOND, 456); if (c.get(MILLISECOND) != 123 || d.get(MILLISECOND) != 456) { - errln("FAIL: Clones share fields"); + fail("FAIL: Clones share fields"); } } // Verify effect of Gregorian cutoff value @SuppressWarnings("deprecation") + @Test public void TestGregorianChange768() { boolean b; GregorianCalendar c = new GregorianCalendar(); - logln("With cutoff " + c.getGregorianChange()); - logln(" isLeapYear(1800) = " + (b = c.isLeapYear(1800))); - logln(" (should be FALSE)"); + System.out.println("With cutoff " + c.getGregorianChange()); + System.out.println(" isLeapYear(1800) = " + (b = c.isLeapYear(1800))); + System.out.println(" (should be FALSE)"); if (b != false) { - errln("FAIL"); + fail("FAIL"); } c.setGregorianChange(new Date(0, 0, 1)); // Jan 1 1900 - logln("With cutoff " + c.getGregorianChange()); - logln(" isLeapYear(1800) = " + (b = c.isLeapYear(1800))); - logln(" (should be TRUE)"); + System.out.println("With cutoff " + c.getGregorianChange()); + System.out.println(" isLeapYear(1800) = " + (b = c.isLeapYear(1800))); + System.out.println(" (should be TRUE)"); if (b != true) { - errln("FAIL"); + fail("FAIL"); } } // Test the correct behavior of the disambiguation algorithm. + @Test public void TestDisambiguation765() throws Exception { Locale savedLocale = Locale.getDefault(); try { @@ -562,7 +570,7 @@ public void TestDisambiguation765() throws Exception { c.set(WEEK_OF_MONTH, 1); verify765("1997 Tuesday in week 0 of June = ", c, 1997, JUNE, 3); } catch (IllegalArgumentException ex) { - errln("FAIL: Exception seen: " + ex.getMessage()); + fail("FAIL: Exception seen: " + ex.getMessage()); // ex.printStackTrace(log); } @@ -596,9 +604,9 @@ void verify765(String msg, Calendar c, int year, int month, int day) { if (c.get(YEAR) == year && c.get(MONTH) == month && c.get(DATE) == day) { - logln("PASS: " + msg + c.getTime()); + System.out.println("PASS: " + msg + c.getTime()); } else { - errln("FAIL: " + msg + c.getTime() + fail("FAIL: " + msg + c.getTime() + "; expected " + year + "/" + (month + 1) + "/" + day); } @@ -607,17 +615,18 @@ void verify765(String msg, Calendar c, int year, int month, int day) { // Called when e expected to be non-null void verify765(String msg, IllegalArgumentException e) { if (e == null) { - errln("FAIL: No IllegalArgumentException for " + msg); + fail("FAIL: No IllegalArgumentException for " + msg); } else { - logln("PASS: " + msg + "IllegalArgument as expected"); + System.out.println("PASS: " + msg + "IllegalArgument as expected"); } } // Test the behavior of GMT vs. local time + @Test public void TestGMTvsLocal4064654() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -645,7 +654,7 @@ void test4064654(int yr, int mo, int dt, int hr, int mn, int sc) { gmtcal.set(MILLISECOND, 0); date = gmtcal.getTime(); - logln("date = " + date); + System.out.println("date = " + date); Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); @@ -658,7 +667,7 @@ void test4064654(int yr, int mo, int dt, int hr, int mn, int sc) { cal.get(DAY_OF_WEEK), cal.get(MILLISECOND)); - logln("offset for " + date + "= " + (offset / 1000 / 60 / 60.0) + "hr"); + System.out.println("offset for " + date + "= " + (offset / 1000 / 60 / 60.0) + "hr"); int utc = ((cal.get(HOUR_OF_DAY) * 60 + cal.get(MINUTE)) * 60 @@ -668,7 +677,7 @@ void test4064654(int yr, int mo, int dt, int hr, int mn, int sc) { int expected = ((hr * 60 + mn) * 60 + sc) * 1000; if (utc != expected) { - errln("FAIL: Discrepancy of " + fail("FAIL: Discrepancy of " + (utc - expected) + " millis = " + ((utc - expected) / 1000 / 60 / 60.0) + " hr"); } @@ -676,6 +685,7 @@ void test4064654(int yr, int mo, int dt, int hr, int mn, int sc) { // Verify that add and set work regardless of the order in which // they are called. + @Test public void TestAddSetOrder621() { @SuppressWarnings("deprecation") Date d = new Date(97, 4, 14, 13, 23, 45); @@ -699,13 +709,14 @@ public void TestAddSetOrder621() { String s2 = cal.getTime().toString(); if (s.equals(s2)) { - logln("Pass: " + s + " == " + s2); + System.out.println("Pass: " + s + " == " + s2); } else { - errln("FAIL: " + s + " != " + s2); + fail("FAIL: " + s + " != " + s2); } } // Verify that add works. + @Test public void TestAdd520() { int y = 1997, m = FEBRUARY, d = 1; GregorianCalendar temp = new GregorianCalendar(y, m, d); @@ -737,19 +748,20 @@ void check520(Calendar c, int y, int m, int d) { if (c.get(YEAR) != y || c.get(MONTH) != m || c.get(DATE) != d) { - errln("FAILURE: Expected YEAR/MONTH/DATE of " + fail("FAILURE: Expected YEAR/MONTH/DATE of " + y + "/" + (m + 1) + "/" + d + "; got " + c.get(YEAR) + "/" + (c.get(MONTH) + 1) + "/" + c.get(DATE)); } else { - logln("Confirmed: " + System.out.println("Confirmed: " + y + "/" + (m + 1) + "/" + d); } } // Verify that setting fields works. This test fails when an exception is thrown. + @Test public void TestFieldSet4781() { try { GregorianCalendar g = new GregorianCalendar(); @@ -763,16 +775,17 @@ public void TestFieldSet4781() { // The following line will result in IllegalArgumentException because // it thinks the YEAR is set and it is NOT. if (g2.equals(g)) { - logln("Same"); + System.out.println("Same"); } else { - logln("Different"); + System.out.println("Different"); } } catch (IllegalArgumentException e) { - errln("Unexpected exception seen: " + e); + fail("Unexpected exception seen: " + e); } } // Test serialization of a Calendar object + @Test public void TestSerialize337() { Calendar cal = Calendar.getInstance(); @@ -800,15 +813,15 @@ public void TestSerialize337() { File fl = new File(FILENAME); fl.delete(); } catch (IOException e) { - errln("FAIL: Exception received:"); + fail("FAIL: Exception received:"); // e.printStackTrace(log); } catch (ClassNotFoundException e) { - errln("FAIL: Exception received:"); + fail("FAIL: Exception received:"); // e.printStackTrace(log); } if (!ok) { - errln("Serialization of Calendar object failed."); + fail("Serialization of Calendar object failed."); } } static final String PREFIX = "abc"; @@ -816,6 +829,7 @@ public void TestSerialize337() { static final String FILENAME = "tmp337.bin"; // Try to zero out the seconds field + @Test public void TestSecondsZero121() { Calendar cal = new GregorianCalendar(); // Initialize with current date/time @@ -825,11 +839,12 @@ public void TestSecondsZero121() { Date d = cal.getTime(); String s = d.toString(); if (s.indexOf(":00 ") < 0) { - errln("Expected to see :00 in " + s); + fail("Expected to see :00 in " + s); } } // Try various sequences of add, set, and get method calls. + @Test public void TestAddSetGet0610() { // // Error case 1: @@ -840,13 +855,13 @@ public void TestAddSetGet0610() { { Calendar calendar = new GregorianCalendar(); calendar.set(1993, JANUARY, 4); - logln("1A) " + value(calendar)); + System.out.println("1A) " + value(calendar)); calendar.add(DATE, 1); String v = value(calendar); - logln("1B) " + v); - logln("--) 1993/0/5"); + System.out.println("1B) " + v); + System.out.println("--) 1993/0/5"); if (!v.equals(EXPECTED_0610)) { - errln("Expected " + EXPECTED_0610 + fail("Expected " + EXPECTED_0610 + "; saw " + v); } } @@ -858,13 +873,13 @@ public void TestAddSetGet0610() { // { Calendar calendar = new GregorianCalendar(1993, JANUARY, 4); - logln("2A) " + value(calendar)); + System.out.println("2A) " + value(calendar)); calendar.add(DATE, 1); String v = value(calendar); - logln("2B) " + v); - logln("--) 1993/0/5"); + System.out.println("2B) " + v); + System.out.println("--) 1993/0/5"); if (!v.equals(EXPECTED_0610)) { - errln("Expected " + EXPECTED_0610 + fail("Expected " + EXPECTED_0610 + "; saw " + v); } } @@ -877,14 +892,14 @@ public void TestAddSetGet0610() { // { Calendar calendar = new GregorianCalendar(1993, JANUARY, 4); - logln("3A) " + value(calendar)); + System.out.println("3A) " + value(calendar)); calendar.getTime(); calendar.add(DATE, 1); String v = value(calendar); - logln("3B) " + v); - logln("--) 1993/0/5"); + System.out.println("3B) " + v); + System.out.println("--) 1993/0/5"); if (!v.equals(EXPECTED_0610)) { - errln("Expected " + EXPECTED_0610 + fail("Expected " + EXPECTED_0610 + "; saw " + v); } } @@ -897,6 +912,7 @@ static String value(Calendar calendar) { static String EXPECTED_0610 = "1993/0/5"; // Test that certain fields on a certain date are as expected. + @Test public void TestFields060() { int year = 1997; int month = OCTOBER; //october @@ -908,7 +924,7 @@ public void TestFields060() { int field = EXPECTED_FIELDS[i++]; int expected = EXPECTED_FIELDS[i++]; if (calendar.get(field) != expected) { - errln("Expected field " + field + " to have value " + expected + fail("Expected field " + field + " to have value " + expected + "; received " + calendar.get(field) + " instead"); } } @@ -942,6 +958,7 @@ public void TestFields060() { // Verify that the fields are as expected (mostly zero) at the epoch start. // Note that we adjust for the default timezone to get most things to zero. + @Test public void TestEpochStartFields() { String[][] lt = { {"en", "US", "US/Pacific"}, /* First day = 1, Minimum day = 1 */ @@ -988,14 +1005,14 @@ public void TestEpochStartFields() { boolean err = false; for (int i = 0; i < calendarFieldNames.length; ++i) { if ((val = c.get(i)) != EPOCH_FIELDS[i]) { - errln("Wrong value: " + val + fail("Wrong value: " + val + " for field(" + calendarFieldNames[i] + "), expected: " + EPOCH_FIELDS[i]); err = true; } } if (err) { - errln("Failed: \n\tDate=" + d + "\n\tTimeZone=" + z + fail("Failed: \n\tDate=" + d + "\n\tTimeZone=" + z + "\n\tLocale=" + l + "\n\tCalendar=" + c); } } @@ -1007,6 +1024,7 @@ public void TestEpochStartFields() { // Verify that as you add days to the calendar (e.g., 24 day periods), // the day of the week shifts in the expected pattern. + @Test public void TestDOWProgression() { Calendar cal = new GregorianCalendar(1972, OCTOBER, 26); @@ -1020,66 +1038,68 @@ void marchByDelta(Calendar cal, int delta) { int DOW, newDOW = initialDOW; do { DOW = newDOW; - logln("DOW = " + DOW + " " + cur.getTime()); + System.out.println("DOW = " + DOW + " " + cur.getTime()); cur.add(DAY_OF_WEEK, delta); newDOW = cur.get(DAY_OF_WEEK); int expectedDOW = 1 + (DOW + delta - 1) % 7; if (newDOW != expectedDOW) { - errln("Day of week should be " + expectedDOW + fail("Day of week should be " + expectedDOW + " instead of " + newDOW + " on " + cur.getTime()); return; } } while (newDOW != initialDOW); } + @Test public void TestActualMinMax() { Calendar cal = new GregorianCalendar(1967, MARCH, 10); cal.setFirstDayOfWeek(SUNDAY); cal.setMinimalDaysInFirstWeek(3); if (cal.getActualMinimum(DAY_OF_MONTH) != 1) { - errln("Actual minimum date for 3/10/1967 should have been 1; got " + fail("Actual minimum date for 3/10/1967 should have been 1; got " + cal.getActualMinimum(DAY_OF_MONTH)); } if (cal.getActualMaximum(DAY_OF_MONTH) != 31) { - errln("Actual maximum date for 3/10/1967 should have been 31; got " + fail("Actual maximum date for 3/10/1967 should have been 31; got " + cal.getActualMaximum(DAY_OF_MONTH)); } cal.set(MONTH, FEBRUARY); if (cal.getActualMaximum(DAY_OF_MONTH) != 28) { - errln("Actual maximum date for 2/10/1967 should have been 28; got " + fail("Actual maximum date for 2/10/1967 should have been 28; got " + cal.getActualMaximum(DAY_OF_MONTH)); } if (cal.getActualMaximum(DAY_OF_YEAR) != 365) { - errln("Number of days in 1967 should have been 365; got " + fail("Number of days in 1967 should have been 365; got " + cal.getActualMaximum(DAY_OF_YEAR)); } cal.set(YEAR, 1968); if (cal.getActualMaximum(DAY_OF_MONTH) != 29) { - errln("Actual maximum date for 2/10/1968 should have been 29; got " + fail("Actual maximum date for 2/10/1968 should have been 29; got " + cal.getActualMaximum(DAY_OF_MONTH)); } if (cal.getActualMaximum(DAY_OF_YEAR) != 366) { - errln("Number of days in 1968 should have been 366; got " + fail("Number of days in 1968 should have been 366; got " + cal.getActualMaximum(DAY_OF_YEAR)); } // Using week settings of SUNDAY/3 (see above) if (cal.getActualMaximum(WEEK_OF_YEAR) != 52) { - errln("Number of weeks in 1968 should have been 52; got " + fail("Number of weeks in 1968 should have been 52; got " + cal.getActualMaximum(WEEK_OF_YEAR)); } cal.set(YEAR, 1976); // Using week settings of SUNDAY/3 (see above) if (cal.getActualMaximum(WEEK_OF_YEAR) != 53) { - errln("Number of weeks in 1976 should have been 53; got " + fail("Number of weeks in 1976 should have been 53; got " + cal.getActualMaximum(WEEK_OF_YEAR)); } } + @Test public void TestRoll() { Calendar cal = new GregorianCalendar(1997, JANUARY, 31); @@ -1089,7 +1109,7 @@ public void TestRoll() { Calendar cal2 = (Calendar) cal.clone(); cal2.roll(MONTH, i); if (cal2.get(DAY_OF_MONTH) != dayValues[i]) { - errln("Rolling the month in 1/31/1997 up by " + i + " should have yielded " + fail("Rolling the month in 1/31/1997 up by " + i + " should have yielded " + ((i + 1) % 12) + "/" + dayValues[i] + "/1997, but actually yielded " + ((i + 1) % 12) + "/" + cal2.get(DAY_OF_MONTH) + "/1997."); } @@ -1105,7 +1125,7 @@ public void TestRoll() { cal2.roll(YEAR, i); if (cal2.get(DAY_OF_MONTH) != dayValues2[i] || cal2.get(MONTH) != monthValues[i]) { - errln("Rolling the year in 2/29/1996 up by " + i + " should have yielded " + fail("Rolling the year in 2/29/1996 up by " + i + " should have yielded " + (monthValues[i] + 1) + "/" + dayValues2[i] + "/" + (1996 + i) + ", but actually yielded " + (cal2.get(MONTH) + 1) + "/" @@ -1118,17 +1138,17 @@ public void TestRoll() { cal.roll(HOUR_OF_DAY, -2); int f = cal.get(HOUR_OF_DAY); if (f != 22) { - errln("Rolling HOUR_OF_DAY=0 delta=-2 gave " + f + " Wanted 22"); + fail("Rolling HOUR_OF_DAY=0 delta=-2 gave " + f + " Wanted 22"); } cal.roll(HOUR_OF_DAY, 5); f = cal.get(HOUR_OF_DAY); if (f != 3) { - errln("Rolling HOUR_OF_DAY=22 delta=5 gave " + f + " Wanted 3"); + fail("Rolling HOUR_OF_DAY=22 delta=5 gave " + f + " Wanted 3"); } cal.roll(HOUR_OF_DAY, 21); f = cal.get(HOUR_OF_DAY); if (f != 0) { - errln("Rolling HOUR_OF_DAY=3 delta=21 gave " + f + " Wanted 0"); + fail("Rolling HOUR_OF_DAY=3 delta=21 gave " + f + " Wanted 0"); } // Test rolling hour @@ -1136,23 +1156,24 @@ public void TestRoll() { cal.roll(HOUR, -2); f = cal.get(HOUR); if (f != 10) { - errln("Rolling HOUR=0 delta=-2 gave " + f + " Wanted 10"); + fail("Rolling HOUR=0 delta=-2 gave " + f + " Wanted 10"); } cal.roll(HOUR, 5); f = cal.get(HOUR); if (f != 3) { - errln("Rolling HOUR=10 delta=5 gave " + f + " Wanted 3"); + fail("Rolling HOUR=10 delta=5 gave " + f + " Wanted 3"); } cal.roll(HOUR, 9); f = cal.get(HOUR); if (f != 0) { - errln("Rolling HOUR=3 delta=9 gave " + f + " Wanted 0"); + fail("Rolling HOUR=3 delta=9 gave " + f + " Wanted 0"); } } /* * Confirm that multiple calls to Calendar.set() works correctly. */ + @Test public void Test4374886() { Locale savedLocale = Locale.getDefault(); TimeZone savedTimeZone = TimeZone.getDefault(); @@ -1171,7 +1192,7 @@ public void Test4374886() { || cal.get(MONTH) != JANUARY || cal.get(DATE) != 22 || cal.get(DAY_OF_WEEK) != MONDAY) { - errln("Failed : got " + cal.getTime() + ", expected Mon Jan 22, 2001"); + fail("Failed : got " + cal.getTime() + ", expected Mon Jan 22, 2001"); } } finally { Locale.setDefault(savedLocale); @@ -1179,6 +1200,7 @@ public void Test4374886() { } } + @Test public void TestClonedSharedZones() throws NoSuchFieldException, IllegalAccessException { Field zone = Calendar.class.getDeclaredField("zone"); zone.setAccessible(true); @@ -1191,13 +1213,13 @@ public void TestClonedSharedZones() throws NoSuchFieldException, IllegalAccessEx // c1 should have a shared zone if (!sharedZone.getBoolean(c1)) { - errln("Failed : c1.sharedZone == false"); + fail("Failed : c1.sharedZone == false"); } else { // c2 should have a shared zone too if (!sharedZone.getBoolean(c2)) { - errln("Failed : c2.sharedZone == false"); + fail("Failed : c2.sharedZone == false"); } else if (zone.get(c1) != zone.get(c2)) { - errln("Failed : c1.zone != c2.zone"); + fail("Failed : c1.zone != c2.zone"); } } } diff --git a/test/jdk/java/util/Calendar/FieldStateTest.java b/test/jdk/java/util/Calendar/FieldStateTest.java index 9fe5e7fc472..6b4632c13e1 100644 --- a/test/jdk/java/util/Calendar/FieldStateTest.java +++ b/test/jdk/java/util/Calendar/FieldStateTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,9 +24,7 @@ /* * @test * @bug 4860664 4916815 4867075 - * @library /java/text/testlib - * @build Koyomi - * @run main FieldStateTest + * @run junit/othervm FieldStateTest * @summary Unit tests for internal fields states. */ @@ -36,31 +34,30 @@ import static java.util.Calendar.*; -public class FieldStateTest extends IntlTest { +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeAll; - public static void main(String[] args) throws Exception { - Locale reservedLocale = Locale.getDefault(); - TimeZone reservedTimeZone = TimeZone.getDefault(); - try { - TimeZone.setDefault(TimeZone.getTimeZone("GMT")); - Locale.setDefault(Locale.US); +import static org.junit.jupiter.api.Assertions.fail; - new FieldStateTest().run(args); - } finally { - // restore the reserved locale and time zone - Locale.setDefault(reservedLocale); - TimeZone.setDefault(reservedTimeZone); - } +public class FieldStateTest { + + // Change JVM default Locale and TimeZone + @BeforeAll + static void initAll() { + Locale.setDefault(Locale.US); + TimeZone.setDefault(TimeZone.getTimeZone("GMT")); } + + @Test public void TestFieldState() { Koyomi cal = new Koyomi(); - logln("Right after instantialtion:"); + System.out.println("Right after instantialtion:"); if (!cal.checkAllSet()) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln("Set date to 2003/10/31 after the instantiation:"); + System.out.println("Set date to 2003/10/31 after the instantiation:"); cal.set(2003, OCTOBER, 31); // let cal calculate the time cal.getTime(); @@ -70,18 +67,18 @@ public void TestFieldState() { // the fields have "computed". But we can't distinguish them // outside the package. if (!cal.checkAllSet()) { - errln(cal.getMessage()); + fail(cal.getMessage()); } // Make sure that the correct date was produced. if (!cal.checkInternalDate(2003, OCTOBER, 31, FRIDAY)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln("Change to Monday of the week, which is 2003/10/27:"); + System.out.println("Change to Monday of the week, which is 2003/10/27:"); cal.set(DAY_OF_WEEK, MONDAY); cal.getTime(); if (!cal.checkDate(2003, OCTOBER, 27)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } // The same operation didn't work after calling clear() before @@ -89,28 +86,28 @@ public void TestFieldState() { // operations. After the instantiation, all the fields are set // to "computed". But after calling clear(), the state becomes // "unset". - logln("Set to 2003/10/31 after clear():"); + System.out.println("Set to 2003/10/31 after clear():"); cal.clear(); cal.set(2003, OCTOBER, 31); cal.getTime(); cal.set(DAY_OF_WEEK, MONDAY); if (!cal.checkDate(2003, OCTOBER, 27, MONDAY)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln("Set to 2003/10/31 after clear(), then to the 51st week of year (12/19):"); + System.out.println("Set to 2003/10/31 after clear(), then to the 51st week of year (12/19):"); cal.clear(); cal.set(2003, OCTOBER, 31); cal.getTime(); cal.set(WEEK_OF_YEAR, 51); if (!cal.checkFieldValue(WEEK_OF_YEAR, 51)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkDate(2003, DECEMBER, 19, FRIDAY)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln("Set to 2003/10 Mon of 4th week (10/20: 43rd week of year, 293rd day):"); + System.out.println("Set to 2003/10 Mon of 4th week (10/20: 43rd week of year, 293rd day):"); cal.clear(); cal.set(YEAR, 2003); cal.set(MONTH, OCTOBER); @@ -118,32 +115,32 @@ public void TestFieldState() { cal.set(WEEK_OF_MONTH, 4); cal.getTime(); if (!cal.checkFieldValue(DAY_OF_MONTH, 20)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkFieldValue(DAY_OF_YEAR, 293)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkFieldValue(WEEK_OF_YEAR, 43)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln("Set to 2003/10 Mon of 43rd week of year (10/20: 4th week of month, 293rd day):"); + System.out.println("Set to 2003/10 Mon of 43rd week of year (10/20: 4th week of month, 293rd day):"); cal.clear(); cal.set(YEAR, 2003); cal.set(DAY_OF_WEEK, MONDAY); cal.set(WEEK_OF_YEAR, 43); cal.getTime(); if (!cal.checkDate(2003, OCTOBER, 20, MONDAY)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkFieldValue(WEEK_OF_MONTH, 4)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkFieldValue(DAY_OF_YEAR, 293)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln("Set day of week to SUNDAY and date to 2003/10/31. " + System.out.println("Set day of week to SUNDAY and date to 2003/10/31. " + "Then, getTime and set week of year to 43."); @SuppressWarnings("deprecation") @@ -161,15 +158,16 @@ public void TestFieldState() { cal.getTime(); cal.set(WEEK_OF_YEAR, 43); if (!cal.checkDate(2003, OCTOBER, 24, FRIDAY)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } /* * 4916815: REGRESSION: Problem with java.util.Calendar VM 1.4.2-b28 */ + @Test public void Test4916815() { - logln("Set date to 2003/9/26 (Fri). Roll to Aug and back to Sep. " + System.out.println("Set date to 2003/9/26 (Fri). Roll to Aug and back to Sep. " + "Set dayofweek to Sunday which should be 2003/9/21."); Koyomi cal = new Koyomi(); cal.clear(); @@ -183,13 +181,14 @@ public void Test4916815() { // Sunday of the week should be 2003/9/21. cal2.set(DAY_OF_WEEK, SUNDAY); if (!cal2.checkDate(2003, SEPTEMBER, 21, SUNDAY)) { - errln(cal2.getMessage()); + fail(cal2.getMessage()); } } /* * 4867075: GregorianCalendar get() calls complete() internally, should getTime() too? */ + @Test public void Test4867075() { Koyomi cal = new Koyomi(Locale.US); cal.clear(); @@ -209,7 +208,7 @@ private void checkDate(Koyomi cal, int dayOfWeek, cal.set(DAY_OF_WEEK, dayOfWeek); cal.getTime(); if (!cal.checkInternalDate(expectedYear, expectedMonth, expectedDayOfMonth, dayOfWeek)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } diff --git a/test/jdk/java/util/Calendar/GregorianCutoverTest.java b/test/jdk/java/util/Calendar/GregorianCutoverTest.java index a9b840a95b1..8b56c3ac62b 100644 --- a/test/jdk/java/util/Calendar/GregorianCutoverTest.java +++ b/test/jdk/java/util/Calendar/GregorianCutoverTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,9 +24,7 @@ /* * @test * @bug 4359204 4928615 4743587 4956232 6459836 6549953 - * @library /java/text/testlib - * @build Koyomi - * @run main GregorianCutoverTest + * @run junit/othervm GregorianCutoverTest * @summary Unit tests related to the Gregorian cutover support. */ @@ -36,25 +34,25 @@ import static java.util.GregorianCalendar.*; -public class GregorianCutoverTest extends IntlTest { +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeAll; - public static void main(String[] args) throws Exception { - TimeZone tz = TimeZone.getDefault(); - Locale lc = Locale.getDefault(); - try { - TimeZone.setDefault(TimeZone.getTimeZone("GMT")); - Locale.setDefault(Locale.US); +import static org.junit.jupiter.api.Assertions.fail; - new GregorianCutoverTest().run(args); - } finally { - TimeZone.setDefault(tz); - Locale.setDefault(lc); - } +public class GregorianCutoverTest { + + // Change JVM default Locale and TimeZone + @BeforeAll + static void initAll() { + Locale.setDefault(Locale.US); + TimeZone.setDefault(TimeZone.getTimeZone("GMT")); } + /** * 4359204: GregorianCalendar.get(cal.DAY_OF_YEAR) is inconsistent for year 1582 */ + @Test public void Test4359204() { Koyomi cal = new Koyomi(); @@ -100,79 +98,79 @@ public void Test4359204() { checkContinuity(cal, DAY_OF_YEAR); checkContinuity(cal, WEEK_OF_YEAR); - logln("Default cutover"); + System.out.println("Default cutover"); cal = new Koyomi(); cal.set(1582, OCTOBER, 1); - logln(" roll --DAY_OF_MONTH from 1582/10/01"); + System.out.println(" roll --DAY_OF_MONTH from 1582/10/01"); cal.roll(DAY_OF_MONTH, -1); if (!cal.checkDate(1582, OCTOBER, 31)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" roll DAY_OF_MONTH+10 from 1582/10/31"); + System.out.println(" roll DAY_OF_MONTH+10 from 1582/10/31"); cal.roll(DAY_OF_MONTH, +10); if (!cal.checkDate(1582, OCTOBER, 20)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" roll DAY_OF_MONTH-10 from 1582/10/20"); + System.out.println(" roll DAY_OF_MONTH-10 from 1582/10/20"); cal.roll(DAY_OF_MONTH, -10); if (!cal.checkDate(1582, OCTOBER, 31)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" roll back one day further"); + System.out.println(" roll back one day further"); cal.roll(DAY_OF_MONTH, +1); if (!cal.checkDate(1582, OCTOBER, 1)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } // should handle the gap between 1969/12/22 (Julian) to 1970/1/5 (Gregorian) - logln("Cutover date is 1970/1/5"); + System.out.println("Cutover date is 1970/1/5"); @SuppressWarnings("deprecation") Date d1 = new Date(1970 - 1900, JANUARY, 5); cal.setGregorianChange(d1); cal.set(ERA, AD); cal.set(YEAR, 1970); - logln(" Set DAY_OF_YEAR to the 28th day of 1970"); + System.out.println(" Set DAY_OF_YEAR to the 28th day of 1970"); cal.set(DAY_OF_YEAR, 28); if (!cal.checkDate(1970, FEBRUARY, 1)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkFieldValue(WEEK_OF_YEAR, 5)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" 1969/12/22 should be the 356th day of the year."); + System.out.println(" 1969/12/22 should be the 356th day of the year."); cal.set(1969, DECEMBER, 22); if (!cal.checkFieldValue(DAY_OF_YEAR, 356)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" Set DAY_OF_YEAR to autual maximum."); + System.out.println(" Set DAY_OF_YEAR to autual maximum."); int actualMaxDayOfYear = cal.getActualMaximum(DAY_OF_YEAR); if (actualMaxDayOfYear != 356) { - errln("actual maximum of DAY_OF_YEAR: got " + actualMaxDayOfYear + ", expected 356"); + fail("actual maximum of DAY_OF_YEAR: got " + actualMaxDayOfYear + ", expected 356"); } cal.set(DAY_OF_YEAR, actualMaxDayOfYear); if (!cal.checkDate(1969, DECEMBER, 22)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } cal.set(1969, DECEMBER, 22); cal.roll(DAY_OF_YEAR, +1); - logln(" Set to 1969/12/22 and roll DAY_OF_YEAR++"); + System.out.println(" Set to 1969/12/22 and roll DAY_OF_YEAR++"); if (!cal.checkDate(1969, JANUARY, 1)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" 1970/1/5 should be the first day of the year."); + System.out.println(" 1970/1/5 should be the first day of the year."); cal.set(1970, JANUARY, 5); if (!cal.checkFieldValue(DAY_OF_YEAR, 1)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" roll --DAY_OF_MONTH from 1970/1/5"); + System.out.println(" roll --DAY_OF_MONTH from 1970/1/5"); cal.roll(DAY_OF_MONTH, -1); if (!cal.checkDate(1970, JANUARY, 31)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" roll back one day of month"); + System.out.println(" roll back one day of month"); cal.roll(DAY_OF_MONTH, +1); if (!cal.checkDate(1970, JANUARY, 5)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } // Test "missing" dates in non-lenient. @@ -180,22 +178,22 @@ public void Test4359204() { cal.setLenient(false); try { // the next day of 1582/10/4 (Julian) is 1582/10/15 (Gregorian) - logln("1582/10/10 doesn't exit with the default cutover."); + System.out.println("1582/10/10 doesn't exit with the default cutover."); cal.set(1582, OCTOBER, 10); cal.getTime(); - errln(" Didn't throw IllegalArgumentException in non-lenient."); + fail(" Didn't throw IllegalArgumentException in non-lenient."); } catch (IllegalArgumentException e) { } } private void checkContinuity(Koyomi cal, int field) { cal.getTime(); - logln(Koyomi.getFieldName(field) + " starting on " + cal.toDateString()); + System.out.println(Koyomi.getFieldName(field) + " starting on " + cal.toDateString()); int max = cal.getActualMaximum(field); for (int i = 1; i <= max; i++) { - logln(i + " " + cal.toDateString()); + System.out.println(i + " " + cal.toDateString()); if (!cal.checkFieldValue(field, i)) { - errln(" " + cal.toDateString() + ":\t" + cal.getMessage()); + fail(" " + cal.toDateString() + ":\t" + cal.getMessage()); } cal.add(field, +1); } @@ -204,92 +202,95 @@ private void checkContinuity(Koyomi cal, int field) { /** * 4928615: GregorianCalendar returns wrong dates after setGregorianChange */ + @Test public void Test4928615() { Koyomi cal = new Koyomi(); - logln("Today is 2003/10/1 Gregorian."); + System.out.println("Today is 2003/10/1 Gregorian."); @SuppressWarnings("deprecation") Date x = new Date(2003 - 1900, 10 - 1, 1); cal.setTime(x); - logln(" Changing the cutover date to yesterday..."); + System.out.println(" Changing the cutover date to yesterday..."); cal.setGregorianChange(new Date(x.getTime() - (24 * 3600 * 1000))); if (!cal.checkDate(2003, OCTOBER, 1)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } - logln(" Changing the cutover date to tomorrow..."); + System.out.println(" Changing the cutover date to tomorrow..."); cal.setGregorianChange(new Date(x.getTime() + (24 * 3600 * 1000))); if (!cal.checkDate(2003, SEPTEMBER, 18)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } } /** * 4743587: GregorianCalendar.getLeastMaximum() returns wrong values */ + @Test public void Test4743587() { Koyomi cal = new Koyomi(); Koyomi cal2 = (Koyomi) cal.clone(); - logln("getLeastMaximum should handle cutover year.\n" + System.out.println("getLeastMaximum should handle cutover year.\n" + " default cutover date"); if (!cal.checkLeastMaximum(DAY_OF_YEAR, 365 - 10)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkLeastMaximum(WEEK_OF_YEAR, 52 - ((10 + 6) / 7))) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } // Corrected for 4956232 if (!cal.checkLeastMaximum(DAY_OF_MONTH, 28)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkLeastMaximum(WEEK_OF_MONTH, 3)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkLeastMaximum(DAY_OF_WEEK_IN_MONTH, 3)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } // make sure that getLeastMaximum calls didn't affect the date if (!cal.equals(cal2)) { - errln(" getLeastMaximum calls modified the object."); + fail(" getLeastMaximum calls modified the object."); } if (!cal.checkGreatestMinimum(DAY_OF_MONTH, 1)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } - logln(" changing the date to 1582/10/20 for actual min/max tests"); + System.out.println(" changing the date to 1582/10/20 for actual min/max tests"); cal.set(1582, OCTOBER, 20); if (!cal.checkActualMinimum(DAY_OF_MONTH, 1)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkActualMaximum(DAY_OF_MONTH, 31)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } cal = new Koyomi(); - logln("Change the cutover date to 1970/1/5."); + System.out.println("Change the cutover date to 1970/1/5."); @SuppressWarnings("deprecation") Date d = new Date(1970 - 1900, 0, 5); cal.setGregorianChange(d); if (!cal.checkLeastMaximum(DAY_OF_YEAR, 356)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkLeastMaximum(DAY_OF_MONTH, 22)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkGreatestMinimum(DAY_OF_MONTH, 5)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } cal.set(1970, JANUARY, 10); if (!cal.checkActualMinimum(DAY_OF_MONTH, 5)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkActualMaximum(DAY_OF_MONTH, 31)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } } /** * 6459836: (cal) GregorianCalendar set method provides wrong result */ + @Test public void Test6459836() { int hour = 13865672; Koyomi gc1 = new Koyomi(); @@ -297,19 +298,20 @@ public void Test6459836() { gc1.set(1, JANUARY, 1, 0, 0, 0); gc1.set(HOUR_OF_DAY, hour); if (!gc1.checkDate(1582, OCTOBER, 4)) { - errln("test case 1: " + gc1.getMessage()); + fail("test case 1: " + gc1.getMessage()); } gc1.clear(); gc1.set(1, JANUARY, 1, 0, 0, 0); gc1.set(HOUR_OF_DAY, hour + 24); if (!gc1.checkDate(1582, OCTOBER, 15)) { - errln("test case 2: " + gc1.getMessage()); + fail("test case 2: " + gc1.getMessage()); } } /** * 6549953 (cal) WEEK_OF_YEAR and DAY_OF_YEAR calculation problems around Gregorian cutover */ + @Test public void Test6549953() { Koyomi cal = new Koyomi(); @@ -319,13 +321,13 @@ public void Test6549953() { cal.checkFieldValue(WEEK_OF_YEAR, 42); cal.checkFieldValue(DAY_OF_WEEK, FRIDAY); if (!cal.checkDate(1582, OCTOBER, 29)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } cal.clear(); cal.set(1582, OCTOBER, 1); cal.set(DAY_OF_YEAR, 292); if (!cal.checkDate(1582, OCTOBER, 29)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } } diff --git a/test/jdk/java/util/Calendar/JulianTest.java b/test/jdk/java/util/Calendar/JulianTest.java index bd7105bce89..4311dab1e3b 100644 --- a/test/jdk/java/util/Calendar/JulianTest.java +++ b/test/jdk/java/util/Calendar/JulianTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,20 +25,21 @@ * @test * @bug 5029449 * @summary Tests for the Julian calendar system (before the Gregorian cutover) - * @library /java/text/testlib + * @run junit JulianTest */ import static java.util.GregorianCalendar.*; -public class JulianTest extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new JulianTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class JulianTest { /* * 5029449: Regression: GregorianCalendar produces wrong Julian calendar dates in BC 1 */ + @Test public void Test5029449() { Koyomi cal = new Koyomi(); cal.clear(); @@ -46,7 +47,7 @@ public void Test5029449() { // Date should be BC 1/12/31 if (!cal.checkFieldValue(ERA, BC) || !cal.checkDate(1, DECEMBER, 31)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } } diff --git a/test/jdk/java/util/Calendar/NonLenientTest.java b/test/jdk/java/util/Calendar/NonLenientTest.java index 357cf0e95c0..58b22215bf2 100644 --- a/test/jdk/java/util/Calendar/NonLenientTest.java +++ b/test/jdk/java/util/Calendar/NonLenientTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,7 +25,7 @@ * @test * @bug 4147269 4266783 4726030 * @summary Make sure that validation is adequate in non-lenient mode. - * @library /java/text/testlib + * @run junit/othervm NonLenientTest */ import java.util.Date; @@ -35,22 +35,22 @@ import static java.util.Calendar.*; -public class NonLenientTest extends IntlTest { +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeAll; - public static void main(String[] args) throws Exception { - Locale reservedLocale = Locale.getDefault(); - TimeZone reservedTimeZone = TimeZone.getDefault(); - try { - Locale.setDefault(Locale.US); - TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")); - new NonLenientTest().run(args); - } finally { - // restore the reserved locale and time zone - Locale.setDefault(reservedLocale); - TimeZone.setDefault(reservedTimeZone); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class NonLenientTest { + + // Change JVM default Locale and TimeZone + @BeforeAll + static void initAll() { + Locale.setDefault(Locale.US); + TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")); } + + @Test public void TestValidationInNonLenient() { Koyomi cal = getNonLenient(); @@ -122,6 +122,7 @@ public void TestValidationInNonLenient() { /** * 4266783: java.util.GregorianCalendar: incorrect validation in non-lenient */ + @Test public void Test4266783() { Koyomi cal = getNonLenient(); // 2003/1 has up to 5 weeks. @@ -135,6 +136,7 @@ public void Test4266783() { /** * 4726030: GregorianCalendar doesn't check invalid dates in non-lenient */ + @Test public void Test4726030() { Koyomi cal = getNonLenient(); // Default year is 1970 in GregorianCalendar which isn't a leap year. @@ -146,6 +148,7 @@ public void Test4726030() { /** * 4147269: java.util.GregorianCalendar.computeTime() works wrong when lenient is false */ + @Test public void Test4147269() { Koyomi calendar = getNonLenient(); Date date = (new GregorianCalendar(1996, 0, 3)).getTime(); @@ -157,7 +160,7 @@ public void Test4147269() { calendar.set(field, value); try { calendar.computeTime(); // call method under test - errln("Test failed with field " + Koyomi.getFieldName(field) + fail("Test failed with field " + Koyomi.getFieldName(field) + "\n\tdate before: " + date + "\n\tdate after: " + calendar.getTime() + "\n\tvalue: " + value + " (max = " + max + ")"); @@ -172,7 +175,7 @@ public void Test4147269() { calendar.set(field, value); try { calendar.computeTime(); // call method under test - errln("Test failed with field " + Koyomi.getFieldName(field) + fail("Test failed with field " + Koyomi.getFieldName(field) + "\n\tdate before: " + date + "\n\tdate after: " + calendar.getTime() + "\n\tvalue: " + value + " (min = " + min + ")"); @@ -187,7 +190,7 @@ void validate(Koyomi cal, String desc) { try { cal.complete(); - errln(desc + " should throw IllegalArgumentException in non-lenient."); + fail(desc + " should throw IllegalArgumentException in non-lenient."); } catch (IllegalArgumentException e) { } @@ -198,14 +201,14 @@ void validate(Koyomi cal, String desc) { int[] afterFields = cal.getFields(); for (int i = 0; i < FIELD_COUNT; i++) { if (cal.isSet(i) && originalFields[i] != afterFields[i]) { - errln(" complete() modified fields[" + Koyomi.getFieldName(i) + "] got " + fail(" complete() modified fields[" + Koyomi.getFieldName(i) + "] got " + afterFields[i] + ", expected " + originalFields[i]); } } // In non-lenient, set state of fields shouldn't be modified. int afterSetFields = cal.getSetStateFields(); if (setFields != afterSetFields) { - errln(" complate() modified set states: before 0x" + toHex(setFields) + fail(" complate() modified set states: before 0x" + toHex(setFields) + ", after 0x" + toHex(afterSetFields)); } } diff --git a/test/jdk/java/util/Calendar/bug4243802.java b/test/jdk/java/util/Calendar/bug4243802.java index a2361317abb..499b7e45772 100644 --- a/test/jdk/java/util/Calendar/bug4243802.java +++ b/test/jdk/java/util/Calendar/bug4243802.java @@ -24,8 +24,9 @@ /* * @test * @bug 4243802 - * @summary confirm that Calendar.setTimeInMillis() and getTimeInMillis() - * can be called from a user program. They used to be protected methods. + * @summary confirm that Calendar.setTimeInMillis() and + * getTimeInMillis() can be called from a user program. (They used to + * be protected methods.) * @run junit bug4243802 */ @@ -35,17 +36,17 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; - import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class bug4243802 { + // Save JVM default Locale and TimeZone private static final TimeZone savedTz = TimeZone.getDefault(); private static final Locale savedLocale = Locale.getDefault(); - // Save JVM default Locale and TimeZone + // Set custom JVM default Locale and TimeZone @BeforeAll static void initAll() { Locale.setDefault(Locale.US); @@ -68,10 +69,8 @@ static void tearDownAll() { public void setCalendarWithoutDateTest() { Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); - cal1.clear(); cal2.clear(); - cal1.set(2001, Calendar.JANUARY, 25, 1, 23, 45); // Build the second calendar using the getTimeInMillis of the first cal2.setTimeInMillis(cal1.getTimeInMillis()); diff --git a/test/jdk/java/util/Calendar/bug4316678.java b/test/jdk/java/util/Calendar/bug4316678.java index b455f51e067..f6bd4b87cae 100644 --- a/test/jdk/java/util/Calendar/bug4316678.java +++ b/test/jdk/java/util/Calendar/bug4316678.java @@ -46,9 +46,11 @@ public class bug4316678 { private static final String serializedData = "bug4316678.ser"; + + // Save JVM default TimeZone private static final TimeZone savedTz = TimeZone.getDefault(); - // Save JVM default Locale and TimeZone + // Set custom JVM default TimeZone @BeforeAll static void initAll() { TimeZone.setDefault(TimeZone.getTimeZone("PST")); diff --git a/test/jdk/java/util/Calendar/bug4372743.java b/test/jdk/java/util/Calendar/bug4372743.java index da7d20e5cd0..193ad53d813 100644 --- a/test/jdk/java/util/Calendar/bug4372743.java +++ b/test/jdk/java/util/Calendar/bug4372743.java @@ -61,15 +61,16 @@ public class bug4372743 { + // Save JVM default timezone private static final TimeZone savedTz = TimeZone.getDefault(); - // Save JVM default Locale and TimeZone + // Set custom JVM default timezone @BeforeAll static void initAll() { TimeZone.setDefault(TimeZone.getTimeZone("PST")); } - // Restore JVM default Locale and TimeZone + // Restore JVM default timezone @AfterAll static void tearDownAll() { TimeZone.setDefault(savedTz); diff --git a/test/jdk/java/util/Calendar/bug4409072.java b/test/jdk/java/util/Calendar/bug4409072.java index af5ef02c349..617550fe1aa 100644 --- a/test/jdk/java/util/Calendar/bug4409072.java +++ b/test/jdk/java/util/Calendar/bug4409072.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,25 +26,26 @@ * @bug 4409072 * @summary tests for set(), add(), and roll() with various week parameters. * @library /java/text/testlib - * @run main bug4409072 + * @run junit bug4409072 */ import java.util.*; import static java.util.Calendar.*; -public class bug4409072 extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new bug4409072().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class bug4409072 { /* Confirm some public methods' behavior in Calendar. * (e.g. add(), roll(), set()) */ + @Test public void Test4409072() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -411,7 +412,7 @@ void testSet() { if (cal.get(WEEK_OF_YEAR) != 22) { noerror = false; - errln("Failed : set(WEEK_OF_YEAR=22)" + + fail("Failed : set(WEEK_OF_YEAR=22)" + " *** get(WEEK_OF_YEAR=" + cal.get(WEEK_OF_YEAR) + ")" + ", got " + (month+1)+"/"+date+"/"+year + @@ -420,7 +421,7 @@ void testSet() { ", FirstDOW=" + dow); } else if ((year != y) || (month != m) || (date != d)) { noerror = false; - errln("Failed : set(WEEK_OF_YEAR=22)" + + fail("Failed : set(WEEK_OF_YEAR=22)" + " got " + (month+1)+"/"+date+"/"+year + ", expected " + (m+1)+"/"+d+"/"+y + ", MinFirstDOW=" + minDow + @@ -446,7 +447,7 @@ void testSet() { if ((year != y) || (month != m) || (date != d)) { noerror = false; - errln("Failed : set(WEEK_OF_MONTH=1)" + + fail("Failed : set(WEEK_OF_MONTH=1)" + " got " + (month+1)+"/"+date+"/"+year + ", expected " + (m+1)+"/"+d+"/"+y + ", MinFirstDOW=" + minDow + @@ -470,7 +471,7 @@ void testSet() { if (cal.get(WEEK_OF_YEAR) != 1) { noerror = false; - errln("Failed : set(WEEK_OF_YEAR=1)" + + fail("Failed : set(WEEK_OF_YEAR=1)" + " *** get(WEEK_OF_YEAR=" + cal.get(WEEK_OF_YEAR) + ")" + ", got " + (month+1)+"/"+date+"/"+year + @@ -479,7 +480,7 @@ void testSet() { ", FirstDOW=" + dow); } else if ((year != y) || (month != m) || (date != d)) { noerror = false; - errln("Failed : set(WEEK_OF_YEAR=1)" + + fail("Failed : set(WEEK_OF_YEAR=1)" + " got " + (month+1)+"/"+date+"/"+year + ", expected " + (m+1)+"/"+d+"/"+y + ", MinFirstDOW=" + minDow + @@ -490,7 +491,7 @@ void testSet() { } if (noerror) { - logln("Passed : set() test"); + System.out.println("Passed : set() test"); } } @@ -525,7 +526,7 @@ void testAdd() { if ((year != 2006) || (month != 0) || (date != 25)) { noerror = false; - errln("Failed : add(WEEK_OF_YEAR+1)" + + fail("Failed : add(WEEK_OF_YEAR+1)" + " got " + (month+1)+"/"+date+"/"+year + ", expected 1/25/2006" + ", MinFirstDOW=" + minDow + @@ -542,7 +543,7 @@ void testAdd() { date = cal.get(DATE); if ((oldWOY - newWOY) != 3) { - errln("Failed : add(WEEK_OF_YEAR-1)" + + fail("Failed : add(WEEK_OF_YEAR-1)" + " got " + (month+1)+"/"+date+"/"+year + ", expected 11/16/2005" + ", MinFirstDOW=" + minDow + @@ -550,7 +551,7 @@ void testAdd() { ", WEEK_OF_YEAR=" + newWOY + " should be " + (oldWOY-3)); } else if ((year != 2005) || (month != 10) || (date != 16)) { - errln("Failed : add(-1)" + + fail("Failed : add(-1)" + " got " + (month+1)+"/"+date+"/"+year + ", expected 11/16/2005" + ", MinFirstDOW=" + minDow + @@ -560,7 +561,7 @@ void testAdd() { } if (noerror) { - logln("Passed : add() test"); + System.out.println("Passed : add() test"); } } @@ -622,7 +623,7 @@ void testRoll() { if ((year != y) || (month != m) || (date != d)) { noerror = false; - errln("Failed : roll(WEEK_OF_MONTH-1)" + + fail("Failed : roll(WEEK_OF_MONTH-1)" + " got " + (month+1) + "/" + date + "/" + year + ", expected " + (m+1) + "/" + d + "/" + y + ", MinFirstDOW=" + minDow + @@ -649,7 +650,7 @@ void testRoll() { if ((year != y) || (month != m) || (date != d)) { noerror = false; - errln("Failed : roll(WEEK_OF_YEAR+1)" + + fail("Failed : roll(WEEK_OF_YEAR+1)" + " got " + (month+1) + "/" + date + "/" + year + ", expected " + (m+1) + "/" + d + "/" + y + ", MinFirstDOW=" + minDow + @@ -670,7 +671,7 @@ void testRoll() { if ((year != y) || (month != m) || (date != d)) { noerror = false; - errln("Failed : roll(WEEK_OF_YEAR-1)" + + fail("Failed : roll(WEEK_OF_YEAR-1)" + " got " + (month+1)+"/"+date+"/"+year + ", expected " + (m+1)+"/"+d+"/"+y + ", MinFirstDOW=" + minDow + @@ -680,7 +681,7 @@ void testRoll() { } if (noerror) { - logln("Passed : roll() test"); + System.out.println("Passed : roll() test"); } } } diff --git a/test/jdk/java/util/Date/DateRegression.java b/test/jdk/java/util/Date/DateRegression.java index 70d8a5bf706..8fe89d9d59b 100644 --- a/test/jdk/java/util/Date/DateRegression.java +++ b/test/jdk/java/util/Date/DateRegression.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,21 +24,22 @@ /* * @test * @bug 4023247 4027685 4032037 4072029 4073003 4118010 4120606 4133833 4136916 6274757 6314387 - * @library /java/text/testlib + * @run junit DateRegression */ import java.util.*; -@SuppressWarnings("deprecation") -public class DateRegression extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new DateRegression().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +@SuppressWarnings("deprecation") +public class DateRegression { /** * @bug 4023247 */ + @Test public void Test4023247() { Date d1 = new Date(0); Date d2 = new Date(0); @@ -58,46 +59,49 @@ public void Test4023247() { d2.setSeconds(0); if (d1.hashCode() != d2.hashCode()) - errln("Fail: Date hashCode misbehaves"); + fail("Fail: Date hashCode misbehaves"); } /** * @bug 4027685 */ + @Test public void Test4027685() { // Should be 01/16/97 00:00:00 Date nite = new Date("16-JAN-97 12:00 AM"); // Should be 01/16/97 12:00:00 Date noon = new Date("16-JAN-97 12:00 PM"); - logln("Midnight = " + nite + ", Noon = " + noon); + System.out.println("Midnight = " + nite + ", Noon = " + noon); if (!nite.equals(new Date(97, Calendar.JANUARY, 16, 0, 0)) || !noon.equals(new Date(97, Calendar.JANUARY, 16, 12, 0))) - errln("Fail: Nite/Noon confused"); + fail("Fail: Nite/Noon confused"); } /** * @bug 4032037 */ + @Test public void Test4032037() { Date ref = new Date(97, 1, 10); Date d = new Date(Date.parse("2/10/97")); - logln("Date.parse(2/10/97) => " + d); - if (!d.equals(ref)) errln("Fail: Want " + ref + " Got " + d); + System.out.println("Date.parse(2/10/97) => " + d); + if (!d.equals(ref)) fail("Fail: Want " + ref + " Got " + d); d = new Date(Date.parse("10 feb 1997")); - logln("Date.parse(10 feb 1997) => " + d); - if (!d.equals(ref)) errln("Fail: Want " + ref + " Got " + d); + System.out.println("Date.parse(10 feb 1997) => " + d); + if (!d.equals(ref)) fail("Fail: Want " + ref + " Got " + d); d = new Date("2/10/97"); - logln("Date(2/10/97) => " + d); - if (!d.equals(ref)) errln("Fail: Want " + ref + " Got " + d); + System.out.println("Date(2/10/97) => " + d); + if (!d.equals(ref)) fail("Fail: Want " + ref + " Got " + d); d = new Date("10 feb 1997"); - logln("Date(10 feb 1997) => " + d); - if (!d.equals(ref)) errln("Fail: Want " + ref + " Got " + d); + System.out.println("Date(10 feb 1997) => " + d); + if (!d.equals(ref)) fail("Fail: Want " + ref + " Got " + d); } /** * @bug 4072029 */ + @Test public void Test4072029() { TimeZone saveZone = TimeZone.getDefault(); @@ -110,7 +114,7 @@ public void Test4072029() { if (!s.equals(s2) || Math.abs(now.getTime() - now2.getTime()) > 60000 /*one min*/) { - errln("Fail: Roundtrip toString/parse"); + fail("Fail: Roundtrip toString/parse"); } } finally { @@ -121,16 +125,17 @@ public void Test4072029() { /** * @bug 4073003 */ + @Test public void Test4073003() { Date d = new Date(Date.parse("01/02/1984")); if (!d.equals(new Date(84, 0, 2))) - errln("Fail: Want 1/2/1984 Got " + d); + fail("Fail: Want 1/2/1984 Got " + d); d = new Date(Date.parse("02/03/2012")); if (!d.equals(new Date(112, 1, 3))) - errln("Fail: Want 2/3/2012 Got " + d); + fail("Fail: Want 2/3/2012 Got " + d); d = new Date(Date.parse("03/04/15")); if (!d.equals(new Date(115, 2, 4))) - errln("Fail: Want 3/4/2015 Got " + d); + fail("Fail: Want 3/4/2015 Got " + d); } /** @@ -140,26 +145,28 @@ public void Test4073003() { * NOTE: This turned out to be a user error (passing in 2000 instead * of 2000-1900 to the Date constructor). */ + @Test public void Test4118010() { Date d=new java.util.Date(2000-1900, Calendar.FEBRUARY, 29); int m=d.getMonth(); int date=d.getDate(); if (m != Calendar.FEBRUARY || date != 29) - errln("Fail: Want Feb 29, got " + d); + fail("Fail: Want Feb 29, got " + d); } /** * @bug 4120606 * Date objects share state after cloning. */ + @Test public void Test4120606() { Date d = new Date(98, Calendar.JUNE, 24); d.setMonth(Calendar.MAY); Date e = (Date)d.clone(); d.setMonth(Calendar.FEBRUARY); if (e.getMonth() != Calendar.MAY) { - errln("Cloned Date objects share state"); + fail("Cloned Date objects share state"); } } @@ -168,11 +175,12 @@ public void Test4120606() { * Date constructor crashes with parameters out of range, when it should * normalize. */ + @Test public void Test4133833() { Date date = new java.util.Date(12,15,19); Date exp = new Date(1913-1900, Calendar.APRIL, 19); if (!date.equals(exp)) - errln("Fail: Want " + exp + + fail("Fail: Want " + exp + "; got " + date); } @@ -181,15 +189,17 @@ public void Test4133833() { * Date.toString() throws exception in 1.2b4-E * CANNOT REPRODUCE this bug */ + @Test public void Test4136916() { Date time = new Date(); - logln(time.toString()); + System.out.println(time.toString()); } /** * @bug 6274757 * Date getTime and toString interaction for some time values */ + @Test public void Test6274757() { TimeZone savedTz = TimeZone.getDefault(); try { @@ -199,11 +209,11 @@ public void Test6274757() { Calendar jdkCal = Calendar.getInstance(jdkGMT); jdkCal.clear(); jdkCal.set(1582, Calendar.OCTOBER, 15); - logln("JDK time: " + jdkCal.getTime().getTime() ); - logln("JDK time (str): " + jdkCal.getTime() ); - logln("Day of month: " + jdkCal.get(Calendar.DAY_OF_MONTH)); + System.out.println("JDK time: " + jdkCal.getTime().getTime() ); + System.out.println("JDK time (str): " + jdkCal.getTime() ); + System.out.println("Day of month: " + jdkCal.get(Calendar.DAY_OF_MONTH)); Date co = jdkCal.getTime(); - logln("Change over (Oct 15 1582) = " + co + " (" + + System.out.println("Change over (Oct 15 1582) = " + co + " (" + co.getTime() + ")"); long a = jdkCal.getTime().getTime(); Date c = jdkCal.getTime(); @@ -211,9 +221,9 @@ public void Test6274757() { long b = c.getTime(); if (a != b) { - errln("ERROR: " + a + " != " + b); + fail("ERROR: " + a + " != " + b); } else { - logln(a + " = " + b); + System.out.println(a + " = " + b); } } finally { TimeZone.setDefault(savedTz); @@ -224,16 +234,17 @@ public void Test6274757() { * @bug 6314387 * JCK6.0: api/java_util/Date/index.html#misc fails, mustang */ + @Test public void Test6314387() { Date d = new Date(Long.MAX_VALUE); int y = d.getYear(); if (y != 292277094) { - errln("yesr: got " + y + ", expected 292277094"); + fail("yesr: got " + y + ", expected 292277094"); } d = new Date(Long.MIN_VALUE); y = d.getYear(); if (y != 292267155) { - errln("yesr: got " + y + ", expected 292267155"); + fail("yesr: got " + y + ", expected 292267155"); } } } diff --git a/test/jdk/java/util/Date/DateTest.java b/test/jdk/java/util/Date/DateTest.java index 98392760ba3..6740cb16faa 100644 --- a/test/jdk/java/util/Date/DateTest.java +++ b/test/jdk/java/util/Date/DateTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,23 +25,24 @@ * @test * @bug 4143459 * @summary test Date - * @library /java/text/testlib + * @run junit DateTest */ import java.text.*; import java.util.*; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + @SuppressWarnings("deprecation") -public class DateTest extends IntlTest +public class DateTest { - public static void main(String[] args) throws Exception { - new DateTest().run(args); - } - /** * @bug 4143459 * Warning: Use TestDefaultZone() for complete testing of this bug. */ + @Test public void TestDefaultZoneLite() { // Note: This test is redundant with TestDefaultZone(). It was added by // request to provide a short&sweet test for this bug. It does not test @@ -57,7 +58,7 @@ public void TestDefaultZoneLite() { d.setHours(6); TimeZone.setDefault(TimeZone.getTimeZone("PST")); if (d.getHours() != 22) { - errln("Fail: Date.setHours()/getHours() ignoring default zone"); + fail("Fail: Date.setHours()/getHours() ignoring default zone"); } } finally { TimeZone.setDefault(save); } @@ -66,6 +67,7 @@ public void TestDefaultZoneLite() { /** * @bug 4143459 */ + @Test public void TestDefaultZone() { // Various problems can creep up, with the current implementation of Date, // when the default zone is changed. @@ -87,7 +89,7 @@ public void TestDefaultZone() { // sub-object (most Date objects), and a Date object with a Calendar // sub-object. We make two passes to cover the two cases. for (int pass=0; pass<2; ++pass) { - logln(pass == 0 ? "Normal Date object" : "Date with Calendar sub-object"); + System.out.println(pass == 0 ? "Normal Date object" : "Date with Calendar sub-object"); TimeZone.setDefault(GMT); d = new Date(refstr); @@ -96,7 +98,7 @@ public void TestDefaultZone() { d.setYear(d.getYear()); } if (d.getTime() != ref.getTime()) { - errln("FAIL: new Date(\"" + refstr + "\") x GMT -> " + d + + fail("FAIL: new Date(\"" + refstr + "\") x GMT -> " + d + " " + d.getTime() + " ms"); } @@ -104,7 +106,7 @@ public void TestDefaultZone() { d.getDay(), d.getHours(), d.getTimezoneOffset() }; for (int i=0; i PER_LOOP_LIMIT) - logln("WARNING: Date constructor/getYear slower than " + + System.out.println("WARNING: Date constructor/getYear slower than " + PER_LOOP_LIMIT + " ms"); } static double PER_LOOP_LIMIT = 3.0; @@ -150,6 +153,7 @@ public void TestPerformance592() /** * Verify that the Date(String) constructor works. */ + @Test public void TestParseOfGMT() { Date OUT = null; @@ -164,7 +168,7 @@ public void TestParseOfGMT() // logln("PASS"); } else { - errln( "Expected: " + + fail( "Expected: " + new Date( expectedVal ) + ": " + expectedVal + @@ -178,56 +182,58 @@ public void TestParseOfGMT() // Check out Date's behavior with large negative year values; bug 664 // As of the fix to bug 4056585, Date should work correctly with // large negative years. + @Test public void TestDateNegativeYears() { Date d1= new Date(80,-1,2); - logln(d1.toString()); + System.out.println(d1.toString()); d1= new Date(-80,-1,2); - logln(d1.toString()); + System.out.println(d1.toString()); boolean e = false; try { d1= new Date(-800000,-1,2); - logln(d1.toString()); + System.out.println(d1.toString()); } catch (IllegalArgumentException ex) { e = true; } - if (e) errln("FAIL: Saw exception for year -800000"); - else logln("Pass: No exception for year -800000"); + if (e) fail("FAIL: Saw exception for year -800000"); + else System.out.println("Pass: No exception for year -800000"); } // Verify the behavior of Date + @Test public void TestDate480() { TimeZone save = TimeZone.getDefault(); try { TimeZone.setDefault(TimeZone.getTimeZone("PST")); Date d1=new java.util.Date(97,8,13,10,8,13); - logln("d = "+d1); + System.out.println("d = "+d1); Date d2=new java.util.Date(97,8,13,30,8,13); // 20 hours later - logln("d+20h = "+d2); + System.out.println("d+20h = "+d2); double delta = (d2.getTime() - d1.getTime()) / 3600000; - logln("delta = " + delta + "h"); + System.out.println("delta = " + delta + "h"); - if (delta != 20.0) errln("Expected delta of 20; got " + delta); + if (delta != 20.0) fail("Expected delta of 20; got " + delta); Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(1997,8,13,10,8,13); Date t1 = cal.getTime(); - logln("d = "+t1); + System.out.println("d = "+t1); cal.clear(); cal.set(1997,8,13,30,8,13); // 20 hours later Date t2 = cal.getTime(); - logln("d+20h = "+t2); + System.out.println("d+20h = "+t2); double delta2 = (t2.getTime() - t1.getTime()) / 3600000; - logln("delta = " + delta2 + "h"); + System.out.println("delta = " + delta2 + "h"); - if (delta != 20.0) errln("Expected delta of 20; got " + delta2); + if (delta != 20.0) fail("Expected delta of 20; got " + delta2); } finally { TimeZone.setDefault(save); diff --git a/test/jdk/java/util/Date/TimestampTest.java b/test/jdk/java/util/Date/TimestampTest.java index 950f0a5fb91..06bcab22dad 100644 --- a/test/jdk/java/util/Date/TimestampTest.java +++ b/test/jdk/java/util/Date/TimestampTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,23 +26,24 @@ * @bug 5008227 * @summary Make sure that changes to the Date class don't break java.sql.Timestamp. * @modules java.sql - * @library /java/text/testlib + * @run junit TimestampTest */ import java.util.*; import java.sql.Timestamp; -public class TimestampTest extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new TimestampTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class TimestampTest { /** * 5008227: java.sql.Timestamp.after() is not returning correct result * * Test before(), after(), equals(), compareTo() and getTime(). */ + @Test public void Test5008227() { long t = System.currentTimeMillis(); Timestamp ts1 = new Timestamp(t), ts2 = new Timestamp(t); @@ -88,28 +89,28 @@ private void compareTimestamps(Timestamp ts1, Timestamp ts2, int expected) { boolean expectedResult = expected > 0; boolean result = ts1.after(ts2); if (result != expectedResult) { - errln("ts1.after(ts2) returned " + result + fail("ts1.after(ts2) returned " + result + ". (ts1=" + ts1 + ", ts2=" + ts2 + ")"); } expectedResult = expected < 0; result = ts1.before(ts2); if (result != expectedResult) { - errln("ts1.before(ts2) returned " + result + fail("ts1.before(ts2) returned " + result + ". (ts1=" + ts1 + ", ts2=" + ts2 + ")"); } expectedResult = expected == 0; result = ts1.equals(ts2); if (result != expectedResult) { - errln("ts1.equals(ts2) returned " + result + fail("ts1.equals(ts2) returned " + result + ". (ts1=" + ts1 + ", ts2=" + ts2 + ")"); } int x = ts1.compareTo(ts2); int y = (x > 0) ? 1 : (x < 0) ? -1 : 0; if (y != expected) { - errln("ts1.compareTo(ts2) returned " + x + ", expected " + fail("ts1.compareTo(ts2) returned " + x + ", expected " + relation(expected, "") + "0" + ". (ts1=" + ts1 + ", ts2=" + ts2 + ")"); } @@ -122,7 +123,7 @@ private void compareTimestamps(Timestamp ts1, Timestamp ts2, int expected) { z = (n1 > n2) ? 1 : (n1 < n2) ? -1 : 0; } if (z != expected) { - errln("ts1.getTime() " + relation(z, "==") + " ts2.getTime(), expected " + fail("ts1.getTime() " + relation(z, "==") + " ts2.getTime(), expected " + relation(expected, "==") + ". (ts1=" + ts1 + ", ts2=" + ts2 + ")"); } diff --git a/test/jdk/java/util/Locale/LegacyCodesClassInvariant.java b/test/jdk/java/util/Locale/LegacyCodesClassInvariant.java index b69070854c5..8eb11639c87 100644 --- a/test/jdk/java/util/Locale/LegacyCodesClassInvariant.java +++ b/test/jdk/java/util/Locale/LegacyCodesClassInvariant.java @@ -20,13 +20,14 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + /* - @test - @bug 4184873 - @summary test that locale invariants are preserved across serialization - @library /java/text/testlib - @run main LegacyCodesClassInvariant -*/ + * @test + * @bug 4184873 + * @summary test that locale invariants are preserved across serialization. + * @run junit LegacyCodesClassInvariant + */ + /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. @@ -63,23 +64,19 @@ import java.io.File; import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; import java.util.Locale; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + /** * A Locale can never contain the following language codes: he, yi or id. */ -public class LegacyCodesClassInvariant extends IntlTest { - public static void main(String[] args) throws Exception { - if (args.length == 1 && args[0].equals("prepTest")) { - prepTest(); - } else { - new LegacyCodesClassInvariant().run(args); - } - } - +public class LegacyCodesClassInvariant { + @Test public void testIt() throws Exception { verify("he"); verify("yi"); @@ -92,17 +89,12 @@ private void verify(String lang) { if (in != null) { final Locale loc = (Locale)in.readObject(); final Locale expected = new Locale(lang, "XX"); - if (!(expected.equals(loc))) { - errln("Locale didn't maintain invariants for: "+lang); - errln(" got: "+loc); - errln(" excpeted: "+expected); - } else { - logln("Locale "+lang+" worked"); - } + assertEquals(expected, loc, + "Locale didn't maintain invariants for: "+lang); in.close(); } } catch (Exception e) { - errln(e.toString()); + fail(e.toString()); } } @@ -111,30 +103,8 @@ private ObjectInputStream getStream(String lang) { final File f = new File(System.getProperty("test.src", "."), "LegacyCodesClassInvariant_"+lang); return new ObjectInputStream(new FileInputStream(f)); } catch (Exception e) { - errln(e.toString()); + fail(e.toString()); return null; } } - - /** - * Create serialized output files of the test locales. After they are created, these test - * files should be corrupted (by hand) to contain invalid locale name values. - */ - private static void prepTest() { - outputLocale("he"); - outputLocale("yi"); - outputLocale("id"); - } - - private static void outputLocale(String lang) { - try { - ObjectOutputStream out = new ObjectOutputStream( - new FileOutputStream("LegacyCodesClassInvariant_"+lang)); - out.writeObject(new Locale(lang, "XX")); - out.close(); - } catch (Exception e) { - System.out.println(e); - } - } - } diff --git a/test/jdk/java/util/Locale/LocaleEnhanceTest.java b/test/jdk/java/util/Locale/LocaleEnhanceTest.java index 29c8d29ebd8..54c45031cbf 100644 --- a/test/jdk/java/util/Locale/LocaleEnhanceTest.java +++ b/test/jdk/java/util/Locale/LocaleEnhanceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,24 +41,20 @@ import java.util.Locale.Builder; import java.util.Set; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + /** * @test * @bug 6875847 6992272 7002320 7015500 7023613 7032820 7033504 7004603 * 7044019 8008577 8176853 8255086 8263202 * @summary test API changes to Locale - * @library /java/text/testlib * @modules jdk.localedata * @compile LocaleEnhanceTest.java - * @run main/othervm -Djava.locale.providers=JRE,SPI -esa LocaleEnhanceTest + * @run junit/othervm -Djava.locale.providers=JRE,SPI -esa LocaleEnhanceTest */ -public class LocaleEnhanceTest extends IntlTest { - - public static void main(String[] args) throws Exception { - List argList = new ArrayList(); - argList.addAll(Arrays.asList(args)); - argList.add("-nothrow"); - new LocaleEnhanceTest().run(argList.toArray(new String[argList.size()])); - } +public class LocaleEnhanceTest { public LocaleEnhanceTest() { } @@ -83,6 +79,7 @@ public LocaleEnhanceTest() { * Ensure that Builder builds locales that have the expected * tag and java6 ID. Note the odd cases for the ID. */ + @Test public void testCreateLocaleCanonicalValid() { String[] valids = { "en-Latn-US-NewYork", "en_US_NewYork_#Latn", @@ -131,7 +128,7 @@ public void testCreateLocaleCanonicalValid() { assertEquals(msg + "id", id, l.toString()); } catch (IllegalArgumentException e) { - errln(msg + e.getMessage()); + fail(msg + e.getMessage()); } } } @@ -146,6 +143,7 @@ public void testCreateLocaleCanonicalValid() { * Note that 'New' and 'York' are invalid BCP47 variant subtags * because they are too short. */ + @Test public void testCreateLocaleMultipleVariants() { String[] valids = { @@ -188,7 +186,7 @@ public void testCreateLocaleMultipleVariants() { assertEquals(msg + "id", id, l.toString()); } catch (IllegalArgumentException e) { - errln(msg + e.getMessage()); + fail(msg + e.getMessage()); } } } @@ -197,6 +195,7 @@ public void testCreateLocaleMultipleVariants() { * Ensure that all these invalid formats are not recognized by * forLanguageTag. */ + @Test public void testCreateLocaleCanonicalInvalidSeparator() { String[] invalids = { // trailing separator @@ -240,6 +239,7 @@ public void testCreateLocaleCanonicalInvalidSeparator() { * Ensure that all current locale ids parse. Use DateFormat as a proxy * for all current locale ids. */ + @Test public void testCurrentLocales() { Locale[] locales = java.text.DateFormat.getAvailableLocales(); Builder builder = new Builder(); @@ -266,6 +266,7 @@ public void testCurrentLocales() { /** * Ensure that all icu locale ids parse. */ + @Test public void testIcuLocales() throws Exception { BufferedReader br = new BufferedReader( new InputStreamReader( @@ -282,6 +283,7 @@ public void testIcuLocales() throws Exception { /// Compatibility tests /// + @Test public void testConstructor() { // all the old weirdness still holds, no new weirdness String[][] tests = { @@ -320,6 +322,7 @@ public void testConstructor() { /// Locale API tests. /// + @Test public void testGetScript() { // forLanguageTag normalizes case Locale locale = Locale.forLanguageTag("und-latn"); @@ -334,6 +337,7 @@ public void testGetScript() { assertEquals("script is empty string", "", locale.getScript()); } + @Test public void testGetExtension() { // forLanguageTag does NOT normalize to hyphen Locale locale = Locale.forLanguageTag("und-a-some_ex-tension"); @@ -354,6 +358,7 @@ public void testGetExtension() { assertEquals("x", "y-z-blork", locale.getExtension('x')); } + @Test public void testGetExtensionKeys() { Locale locale = Locale.forLanguageTag("und-a-xx-yy-b-zz-ww"); Set result = locale.getExtensionKeys(); @@ -363,7 +368,7 @@ public void testGetExtensionKeys() { // result is not mutable try { result.add('x'); - errln("expected exception on add to extension key set"); + fail("expected exception on add to extension key set"); } catch (UnsupportedOperationException e) { // ok @@ -374,6 +379,7 @@ public void testGetExtensionKeys() { assertTrue("empty result", locale.getExtensionKeys().isEmpty()); } + @Test public void testGetUnicodeLocaleAttributes() { Locale locale = Locale.forLanguageTag("en-US-u-abc-def"); Set attributes = locale.getUnicodeLocaleAttributes(); @@ -386,6 +392,7 @@ public void testGetUnicodeLocaleAttributes() { assertTrue("empty attributes", attributes.isEmpty()); } + @Test public void testGetUnicodeLocaleType() { Locale locale = Locale.forLanguageTag("und-u-co-japanese-nu-thai"); assertEquals("collation", "japanese", locale.getUnicodeLocaleType("co")); @@ -413,6 +420,7 @@ public void testGetUnicodeLocaleType() { new ExpectNPE() { public void call() { Locale.forLanguageTag("").getUnicodeLocaleType(null); }}; } + @Test public void testGetUnicodeLocaleKeys() { Locale locale = Locale.forLanguageTag("und-u-co-japanese-nu-thai"); Set result = locale.getUnicodeLocaleKeys(); @@ -422,13 +430,14 @@ public void testGetUnicodeLocaleKeys() { // result is not modifiable try { result.add("frobozz"); - errln("expected exception when add to locale key set"); + fail("expected exception when add to locale key set"); } catch (UnsupportedOperationException e) { // ok } } + @Test public void testPrivateUseExtension() { Locale locale = Locale.forLanguageTag("x-y-x-blork-"); assertEquals("blork", "y-x-blork", locale.getExtension(Locale.PRIVATE_USE_EXTENSION)); @@ -437,6 +446,7 @@ public void testPrivateUseExtension() { assertEquals("no privateuse", null, locale.getExtension(Locale.PRIVATE_USE_EXTENSION)); } + @Test public void testToLanguageTag() { // lots of normalization to test here // test locales created using the constructor @@ -502,6 +512,7 @@ public void testToLanguageTag() { } + @Test public void testForLanguageTag() { // forLanguageTag implements the 'Language-Tag' production of // BCP47, so it handles private use and legacy language tags, @@ -589,7 +600,7 @@ public void testForLanguageTag() { assertEquals(msg, test[2], locale.toLanguageTag()); } catch (IllegalArgumentException e) { - errln(msg + " caught exception: " + e); + fail(msg + " caught exception: " + e); } } @@ -607,6 +618,7 @@ public void testForLanguageTag() { assertEquals("Duplicated Unicode locake key followed by an extension", "1234", locale.getExtension('c')); } + @Test public void testGetDisplayScript() { Locale latnLocale = Locale.forLanguageTag("und-latn"); Locale hansLocale = Locale.forLanguageTag("und-hans"); @@ -624,6 +636,7 @@ public void testGetDisplayScript() { Locale.setDefault(oldLocale); } + @Test public void testGetDisplayScriptWithLocale() { Locale latnLocale = Locale.forLanguageTag("und-latn"); Locale hansLocale = Locale.forLanguageTag("und-hans"); @@ -635,6 +648,7 @@ public void testGetDisplayScriptWithLocale() { assertEquals("hans DE", "Vereinfachte Chinesische Schrift", hansLocale.getDisplayScript(Locale.GERMANY)); } + @Test public void testGetDisplayName() { final Locale[] testLocales = { Locale.ROOT, @@ -688,6 +702,7 @@ public void testGetDisplayName() { /// Builder tests /// + @Test public void testBuilderSetLocale() { Builder builder = new Builder(); Builder lenientBuilder = new Builder(); @@ -730,6 +745,7 @@ public void call() { }; } + @Test public void testBuilderSetLanguageTag() { String source = "eN-LaTn-Us-NewYork-A-Xx-B-Yy-X-1-2-3"; String target = "en-Latn-US-NewYork-a-xx-b-yy-x-1-2-3"; @@ -747,6 +763,7 @@ public void testBuilderSetLanguageTag() { new BuilderILE() { public void call() { b.setLanguageTag("und-u-nu-thai-NU-chinese-xx-1234"); }}; } + @Test public void testBuilderSetLanguage() { // language is normalized to lower case String source = "eN"; @@ -792,6 +809,7 @@ public void testBuilderSetLanguage() { assertEquals("eng", "eng", result); } + @Test public void testBuilderSetScript() { // script is normalized to title case String source = "lAtN"; @@ -828,6 +846,7 @@ public void testBuilderSetScript() { assertEquals("4alpha", "Wxyz", builder.setScript("wxyz").build().getScript()); } + @Test public void testBuilderSetRegion() { // region is normalized to upper case String source = "uS"; @@ -865,6 +884,7 @@ public void testBuilderSetRegion() { assertEquals("3digit", "000", builder.setRegion("000").build().getCountry()); } + @Test public void testBuilderSetVariant() { // Variant case is not normalized in lenient variant mode String source = "NewYork"; @@ -917,6 +937,7 @@ public void testBuilderSetVariant() { new BuilderILE("abcde-fg") { public void call() { b.setVariant(arg); }}; } + @Test public void testBuilderSetExtension() { // upper case characters are normalized to lower case final char sourceKey = 'a'; @@ -1007,6 +1028,7 @@ public void testBuilderSetExtension() { assertEquals("duplicate keys", "und-u-nu-thai-xx-1234", result); } + @Test public void testBuilderAddUnicodeLocaleAttribute() { Builder builder = new Builder(); Locale locale = builder @@ -1038,6 +1060,7 @@ public void testBuilderAddUnicodeLocaleAttribute() { new BuilderILE("invalid attribute") { public void call() { b.addUnicodeLocaleAttribute("ca"); }}; } + @Test public void testBuildersetUnicodeLocaleKeyword() { // Note: most behavior is tested in testBuilderSetExtension Builder builder = new Builder(); @@ -1081,6 +1104,7 @@ public void testBuildersetUnicodeLocaleKeyword() { new BuilderILE("ab", "abcdefghi") { public void call() { b.setUnicodeLocaleKeyword("ab", arg); }}; } + @Test public void testBuilderPrivateUseExtension() { // normalizes hyphens to underscore, case to lower String source = "c-B-a"; @@ -1096,6 +1120,7 @@ public void testBuilderPrivateUseExtension() { new BuilderILE("a--b") { public void call() { b.setExtension(Locale.PRIVATE_USE_EXTENSION, arg); }}; } + @Test public void testBuilderClear() { String monster = "en-latn-US-NewYork-a-bb-cc-u-co-japanese-x-z-y-x-x"; Builder builder = new Builder(); @@ -1108,14 +1133,17 @@ public void testBuilderClear() { assertEquals("clear", "und", result); } + @Test public void testBuilderRemoveUnicodeAttribute() { // tested in testBuilderAddUnicodeAttribute } + @Test public void testBuilderBuild() { // tested in other test methods } + @Test public void testSerialize() { final Locale[] testLocales = { Locale.ROOT, @@ -1161,11 +1189,12 @@ public void testSerialize() { assertEquals("roundtrip " + locale, locale, o); } catch (Exception e) { - errln(locale + " encountered exception:" + e.getLocalizedMessage()); + fail(locale + " encountered exception:" + e.getLocalizedMessage()); } } } + @Test public void testDeserialize6() { final String TESTFILEPREFIX = "java6locale_"; @@ -1184,10 +1213,10 @@ public void testDeserialize6() { } if (dataDir == null) { - errln("'dataDir' is null. serialized.data.dir Property value is "+dataDirName); + fail("'dataDir' is null. serialized.data.dir Property value is "+dataDirName); return; } else if (!dataDir.isDirectory()) { - errln("'dataDir' is not a directory. dataDir: "+dataDir.toString()); + fail("'dataDir' is not a directory. dataDir: "+dataDir.toString()); return; } @@ -1219,11 +1248,12 @@ public void testDeserialize6() { Object o = ois.readObject(); assertEquals("Deserialize Java 6 Locale " + locale, o, locale); } catch (Exception e) { - errln("Exception while reading " + testfile.getAbsolutePath() + " - " + e.getMessage()); + fail("Exception while reading " + testfile.getAbsolutePath() + " - " + e.getMessage()); } } } + @Test public void testBug7002320() { // forLanguageTag() and Builder.setLanguageTag(String) // should add a location extension for following two cases. @@ -1267,6 +1297,7 @@ public void testBug7002320() { } } + @Test public void testBug7023613() { String[][] testdata = { {"en-Latn", "en__#Latn"}, @@ -1286,6 +1317,7 @@ public void testBug7023613() { /* * 7033504: (lc) incompatible behavior change for ja_JP_JP and th_TH_TH locales */ + @Test public void testBug7033504() { checkCalendar(new Locale("ja", "JP", "jp"), "java.util.GregorianCalendar"); checkCalendar(new Locale("ja", "jp", "jp"), "java.util.GregorianCalendar"); @@ -1318,13 +1350,13 @@ private void checkDigit(Locale loc, Character expected) { private void assertTrue(String msg, boolean v) { if (!v) { - errln(msg + ": expected true"); + fail(msg + ": expected true"); } } private void assertFalse(String msg, boolean v) { if (v) { - errln(msg + ": expected false"); + fail(msg + ": expected false"); } } @@ -1336,7 +1368,7 @@ private void assertEquals(String msg, Object e, Object v) { if (v != null) { v = "'" + v + "'"; } - errln(msg + ": expected " + e + " but got " + v); + fail(msg + ": expected " + e + " but got " + v); } } @@ -1345,19 +1377,19 @@ private void assertNotEquals(String msg, Object e, Object v) { if (e != null) { e = "'" + e + "'"; } - errln(msg + ": expected not equal " + e); + fail(msg + ": expected not equal " + e); } } private void assertNull(String msg, Object o) { if (o != null) { - errln(msg + ": expected null but got '" + o + "'"); + fail(msg + ": expected null but got '" + o + "'"); } } private void assertNotNull(String msg, Object o) { if (o == null) { - errln(msg + ": expected non null"); + fail(msg + ": expected non null"); } } @@ -1383,7 +1415,7 @@ public void run() { if (failMsg != null) { String msg = message(); msg = msg == null ? "" : msg + " "; - errln(msg + failMsg); + fail(msg + failMsg); } } diff --git a/test/jdk/java/util/Locale/LocaleTest.java b/test/jdk/java/util/Locale/LocaleTest.java index 7facfd393ca..f12d899fde2 100644 --- a/test/jdk/java/util/Locale/LocaleTest.java +++ b/test/jdk/java/util/Locale/LocaleTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,10 +27,9 @@ * 4147315 4147317 4147552 4335196 4778440 4940539 5010672 6475525 6544471 6627549 * 6786276 7066203 7085757 8008577 8030696 8170840 8255086 8263202 * @summary test Locales - * @library /java/text/testlib * @modules jdk.localedata - * @run main/othervm -Djava.locale.providers=COMPAT,SPI LocaleTest - * @run main/othervm -Djava.locale.providers=COMPAT,SPI -Djava.locale.useOldISOCodes=true LocaleTest + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI LocaleTest + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI -Djava.locale.useOldISOCodes=true LocaleTest */ /* * This file is available under and governed by the GNU General Public @@ -86,7 +85,11 @@ import java.util.Locale; import java.util.MissingResourceException; -public class LocaleTest extends IntlTest { +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class LocaleTest { public LocaleTest() { } @@ -191,52 +194,50 @@ public LocaleTest() { { "English (United States)", "French (France)", "Croatian (Croatia)", "Greek (Greece)", "Norwegian (Norway,Nynorsk)", "Italian", "xx (YY)" }, }; - public static void main(String[] args) throws Exception { - new LocaleTest().run(args); - } - + @Test public void TestBasicGetters() { for (int i = 0; i <= MAX_LOCALES; i++) { Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i], dataTable[VAR][i]); - logln("Testing " + testLocale + "..."); + System.out.println("Testing " + testLocale + "..."); if (!testLocale.getLanguage().equals(dataTable[LANG][i])) { - errln(" Language code mismatch: " + testLocale.getLanguage() + " versus " + fail(" Language code mismatch: " + testLocale.getLanguage() + " versus " + dataTable[LANG][i]); } if (!testLocale.getCountry().equals(dataTable[CTRY][i])) { - errln(" Country code mismatch: " + testLocale.getCountry() + " versus " + fail(" Country code mismatch: " + testLocale.getCountry() + " versus " + dataTable[CTRY][i]); } if (!testLocale.getVariant().equals(dataTable[VAR][i])) { - errln(" Variant code mismatch: " + testLocale.getVariant() + " versus " + fail(" Variant code mismatch: " + testLocale.getVariant() + " versus " + dataTable[VAR][i]); } if (!testLocale.toString().equals(dataTable[NAME][i])) { - errln(" Locale name mismatch: " + testLocale.toString() + " versus " + fail(" Locale name mismatch: " + testLocale.toString() + " versus " + dataTable[NAME][i]); } } - logln("Same thing without variant codes..."); + System.out.println("Same thing without variant codes..."); for (int i = 0; i <= MAX_LOCALES; i++) { Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i]); - logln("Testing " + testLocale + "..."); + System.out.println("Testing " + testLocale + "..."); if (!testLocale.getLanguage().equals(dataTable[LANG][i])) { - errln(" Language code mismatch: " + testLocale.getLanguage() + " versus " + fail(" Language code mismatch: " + testLocale.getLanguage() + " versus " + dataTable[LANG][i]); } if (!testLocale.getCountry().equals(dataTable[CTRY][i])) { - errln(" Country code mismatch: " + testLocale.getCountry() + " versus " + fail(" Country code mismatch: " + testLocale.getCountry() + " versus " + dataTable[CTRY][i]); } if (!testLocale.getVariant().equals("")) { - errln(" Variant code mismatch: " + testLocale.getVariant() + " versus \"\""); + fail(" Variant code mismatch: " + testLocale.getVariant() + " versus \"\""); } } } + @Test public void TestSimpleResourceInfo() { for (int i = 0; i <= MAX_LOCALES; i++) { if (dataTable[LANG][i].equals("xx")) { @@ -244,20 +245,20 @@ public void TestSimpleResourceInfo() { } Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i], dataTable[VAR][i]); - logln("Testing " + testLocale + "..."); + System.out.println("Testing " + testLocale + "..."); if (!testLocale.getISO3Language().equals(dataTable[LANG3][i])) { - errln(" ISO-3 language code mismatch: " + testLocale.getISO3Language() + fail(" ISO-3 language code mismatch: " + testLocale.getISO3Language() + " versus " + dataTable[LANG3][i]); } if (!testLocale.getISO3Country().equals(dataTable[CTRY3][i])) { - errln(" ISO-3 country code mismatch: " + testLocale.getISO3Country() + fail(" ISO-3 country code mismatch: " + testLocale.getISO3Country() + " versus " + dataTable[CTRY3][i]); } /* // getLCID() is currently private if (!String.valueOf(testLocale.getLCID()).equals(dataTable[LCID][i])) - errln(" LCID mismatch: " + testLocale.getLCID() + " versus " + fail(" LCID mismatch: " + testLocale.getLCID() + " versus " + dataTable[LCID][i]); */ } @@ -269,6 +270,7 @@ public void TestSimpleResourceInfo() { * between 1.1.5 and 1.1.6, but I included a new test for it anyway) * @bug 4052440 Stop falling back to the default locale. */ + @Test public void TestDisplayNames() { Locale saveDefault = Locale.getDefault(); Locale english = new Locale("en", "US"); @@ -277,29 +279,29 @@ public void TestDisplayNames() { Locale greek = new Locale("el", "GR"); Locale.setDefault(english); - logln("With default = en_US..."); - logln(" In default locale..."); + System.out.println("With default = en_US..."); + System.out.println(" In default locale..."); doTestDisplayNames(null, DLANG_EN, false); - logln(" In locale = en_US..."); + System.out.println(" In locale = en_US..."); doTestDisplayNames(english, DLANG_EN, false); - logln(" In locale = fr_FR..."); + System.out.println(" In locale = fr_FR..."); doTestDisplayNames(french, DLANG_FR, false); - logln(" In locale = hr_HR..."); + System.out.println(" In locale = hr_HR..."); doTestDisplayNames(croatian, DLANG_HR, false); - logln(" In locale = el_GR..."); + System.out.println(" In locale = el_GR..."); doTestDisplayNames(greek, DLANG_EL, false); Locale.setDefault(french); - logln("With default = fr_FR..."); - logln(" In default locale..."); + System.out.println("With default = fr_FR..."); + System.out.println(" In default locale..."); doTestDisplayNames(null, DLANG_FR, true); - logln(" In locale = en_US..."); + System.out.println(" In locale = en_US..."); doTestDisplayNames(english, DLANG_EN, true); - logln(" In locale = fr_FR..."); + System.out.println(" In locale = fr_FR..."); doTestDisplayNames(french, DLANG_FR, true); - logln(" In locale = hr_HR..."); + System.out.println(" In locale = hr_HR..."); doTestDisplayNames(croatian, DLANG_HR, true); - logln(" In locale = el_GR..."); + System.out.println(" In locale = el_GR..."); doTestDisplayNames(greek, DLANG_EL, true); Locale.setDefault(saveDefault); @@ -309,14 +311,14 @@ private void doTestDisplayNames(Locale inLocale, int compareIndex, boolean defau String language = Locale.getDefault().getLanguage(); if (defaultIsFrench && !language.equals("fr")) { - errln("Default locale should be French, but it's really " + language); + fail("Default locale should be French, but it's really " + language); } else if (!defaultIsFrench && !language.equals("en")) { - errln("Default locale should be English, but it's really " + language); + fail("Default locale should be English, but it's really " + language); } for (int i = 0; i <= MAX_LOCALES; i++) { Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i], dataTable[VAR][i]); - logln(" Testing " + testLocale + "..."); + System.out.println(" Testing " + testLocale + "..."); String testLang; String testCtry; @@ -373,20 +375,21 @@ private void doTestDisplayNames(Locale inLocale, int compareIndex, boolean defau } if (!testLang.equals(expectedLang)) { - errln("Display language mismatch: " + testLang + " versus " + expectedLang); + fail("Display language mismatch: " + testLang + " versus " + expectedLang); } if (!testCtry.equals(expectedCtry)) { - errln("Display country mismatch: " + testCtry + " versus " + expectedCtry); + fail("Display country mismatch: " + testCtry + " versus " + expectedCtry); } if (!testVar.equals(expectedVar)) { - errln("Display variant mismatch: " + testVar + " versus " + expectedVar); + fail("Display variant mismatch: " + testVar + " versus " + expectedVar); } if (!testName.equals(expectedName)) { - errln("Display name mismatch: " + testName + " versus " + expectedName); + fail("Display name mismatch: " + testName + " versus " + expectedName); } } } + @Test public void TestSimpleObjectStuff() { Locale test1 = new Locale("aa", "AA"); Locale test2 = new Locale("aa", "AA"); @@ -394,19 +397,19 @@ public void TestSimpleObjectStuff() { Locale test4 = new Locale("zz", "ZZ"); if (test1 == test2 || test1 == test3 || test1 == test4 || test2 == test3) { - errln("Some of the test variables point to the same locale!"); + fail("Some of the test variables point to the same locale!"); } if (test3 == null) { - errln("clone() failed to produce a valid object!"); + fail("clone() failed to produce a valid object!"); } if (!test1.equals(test2) || !test1.equals(test3) || !test2.equals(test3)) { - errln("clone() or equals() failed: objects that should compare equal don't"); + fail("clone() or equals() failed: objects that should compare equal don't"); } if (test1.equals(test4) || test2.equals(test4) || test3.equals(test4)) { - errln("equals() failed: objects that shouldn't compare equal do"); + fail("equals() failed: objects that shouldn't compare equal do"); } int hash1 = test1.hashCode(); @@ -414,13 +417,14 @@ public void TestSimpleObjectStuff() { int hash3 = test3.hashCode(); if (hash1 != hash2 || hash1 != hash3 || hash2 != hash3) { - errln("hashCode() failed: objects that should have the same hash code don't"); + fail("hashCode() failed: objects that should have the same hash code don't"); } } /** * @bug 4011756 4011380 */ + @Test public void TestISO3Fallback() { Locale test = new Locale("xx", "YY", ""); boolean gotException = false; @@ -432,7 +436,7 @@ public void TestISO3Fallback() { gotException = true; } if (!gotException) { - errln("getISO3Language() on xx_YY returned " + result + " instead of throwing an exception"); + fail("getISO3Language() on xx_YY returned " + result + " instead of throwing an exception"); } gotException = false; @@ -442,13 +446,14 @@ public void TestISO3Fallback() { gotException = true; } if (!gotException) { - errln("getISO3Country() on xx_YY returned " + result + " instead of throwing an exception"); + fail("getISO3Country() on xx_YY returned " + result + " instead of throwing an exception"); } } /** * @bug 4106155 4118587 7066203 7085757 */ + @Test public void TestGetLangsAndCountries() { // It didn't seem right to just do an exhaustive test of everything here, so I check // for the following things: @@ -463,7 +468,7 @@ public void TestGetLangsAndCountries() { "he", "id", "iu", "ug", "yi", "za"}; if (test.length != 188) { - errln("Expected getISOLanguages() to return 188 languages; it returned " + test.length); + fail("Expected getISOLanguages() to return 188 languages; it returned " + test.length); } else { for (int i = 0; i < spotCheck1.length; i++) { int j; @@ -473,19 +478,19 @@ public void TestGetLangsAndCountries() { } } if (j == test.length || !test[j].equals(spotCheck1[i])) { - errln("Couldn't find " + spotCheck1[i] + " in language list."); + fail("Couldn't find " + spotCheck1[i] + " in language list."); } } } for (int i = 0; i < test.length; i++) { if (!test[i].equals(test[i].toLowerCase())) { - errln(test[i] + " is not all lower case."); + fail(test[i] + " is not all lower case."); } if (test[i].length() != 2) { - errln(test[i] + " is not two characters long."); + fail(test[i] + " is not two characters long."); } if (i > 0 && test[i].compareTo(test[i - 1]) <= 0) { - errln(test[i] + " appears in an out-of-order position in the list."); + fail(test[i] + " appears in an out-of-order position in the list."); } } @@ -494,7 +499,7 @@ public void TestGetLangsAndCountries() { if (test.length != 249) { - errln("Expected getISOCountries to return 249 countries; it returned " + test.length); + fail("Expected getISOCountries to return 249 countries; it returned " + test.length); } else { for (int i = 0; i < spotCheck2.length; i++) { int j; @@ -504,19 +509,19 @@ public void TestGetLangsAndCountries() { } } if (j == test.length || !test[j].equals(spotCheck2[i])) { - errln("Couldn't find " + spotCheck2[i] + " in country list."); + fail("Couldn't find " + spotCheck2[i] + " in country list."); } } } for (int i = 0; i < test.length; i++) { if (!test[i].equals(test[i].toUpperCase())) { - errln(test[i] + " is not all upper case."); + fail(test[i] + " is not all upper case."); } if (test[i].length() != 2) { - errln(test[i] + " is not two characters long."); + fail(test[i] + " is not two characters long."); } if (i > 0 && test[i].compareTo(test[i - 1]) <= 0) { - errln(test[i] + " appears in an out-of-order position in the list."); + fail(test[i] + " appears in an out-of-order position in the list."); } } } @@ -531,28 +536,29 @@ void Test4126880() { test[0] = "SUCKER!!!"; test = Locale.getISOCountries(); if (test[0].equals("SUCKER!!!")) { - errln("Changed internal country code list!"); + fail("Changed internal country code list!"); } test = Locale.getISOLanguages(); test[0] = "HAHAHAHA!!!"; test = Locale.getISOLanguages(); if (test[0].equals("HAHAHAHA!!!")) { // Fixed typo - errln("Changes internal language code list!"); + fail("Changes internal language code list!"); } } /** * @bug 4107014 */ + @Test public void TestGetAvailableLocales() { Locale[] locales = Locale.getAvailableLocales(); if (locales == null || locales.length == 0) { - errln("Locale.getAvailableLocales() returned no installed locales!"); + fail("Locale.getAvailableLocales() returned no installed locales!"); } else { - logln("Locale.getAvailableLocales() returned a list of " + locales.length + " locales."); + System.out.println("Locale.getAvailableLocales() returned a list of " + locales.length + " locales."); for (int i = 0; i < locales.length; i++) { - logln(locales[i].toString()); + System.out.println(locales[i].toString()); } } } @@ -560,11 +566,12 @@ public void TestGetAvailableLocales() { /** * @bug 4135316 */ + @Test public void TestBug4135316() { Locale[] locales1 = Locale.getAvailableLocales(); Locale[] locales2 = Locale.getAvailableLocales(); if (locales1 == locales2) { - errln("Locale.getAvailableLocales() doesn't clone its internal storage!"); + fail("Locale.getAvailableLocales() doesn't clone its internal storage!"); } } @@ -573,27 +580,28 @@ public void TestBug4135316() { */ /* test commented out pending API-change approval + @Test public void TestGetLanguagesForCountry() { String[] languages = Locale.getLanguagesForCountry("US"); if (!searchStringArrayFor("en", languages)) - errln("Didn't get en as a language for US"); + fail("Didn't get en as a language for US"); languages = Locale.getLanguagesForCountry("FR"); if (!searchStringArrayFor("fr", languages)) - errln("Didn't get fr as a language for FR"); + fail("Didn't get fr as a language for FR"); languages = Locale.getLanguagesForCountry("CH"); if (!searchStringArrayFor("fr", languages)) - errln("Didn't get fr as a language for CH"); + fail("Didn't get fr as a language for CH"); if (!searchStringArrayFor("it", languages)) - errln("Didn't get it as a language for CH"); + fail("Didn't get it as a language for CH"); if (!searchStringArrayFor("de", languages)) - errln("Didn't get de as a language for CH"); + fail("Didn't get de as a language for CH"); languages = Locale.getLanguagesForCountry("JP"); if (!searchStringArrayFor("ja", languages)) - errln("Didn't get ja as a language for JP"); + fail("Didn't get ja as a language for JP"); } */ @@ -606,6 +614,7 @@ private boolean searchStringArrayFor(String s, String[] array) { /** * @bug 4110613 */ + @Test public void TestSerialization() throws ClassNotFoundException, OptionalDataException, IOException, StreamCorruptedException { ObjectOutputStream ostream; @@ -626,13 +635,14 @@ public void TestSerialization() throws ClassNotFoundException, OptionalDataExcep Locale test2 = (Locale) (istream.readObject()); if (!test1.equals(test2) || test1.hashCode() != test2.hashCode()) { - errln("Locale failed to deserialize correctly."); + fail("Locale failed to deserialize correctly."); } } /** * @bug 4118587 */ + @Test public void TestSimpleDisplayNames() { // This test is different from TestDisplayNames because TestDisplayNames checks // fallback behavior, combination of language and country names to form locale @@ -645,7 +655,7 @@ public void TestSimpleDisplayNames() { for (int i = 0; i < languageCodes.length; i++) { String test = (new Locale(languageCodes[i], "", "")).getDisplayLanguage(Locale.US); if (!test.equals(languageNames[i])) { - errln("Got wrong display name for " + languageCodes[i] + ": Expected \"" + fail("Got wrong display name for " + languageCodes[i] + ": Expected \"" + languageNames[i] + "\", got \"" + test + "\"."); } } @@ -654,6 +664,7 @@ public void TestSimpleDisplayNames() { /** * @bug 4118595 */ + @Test public void TestUninstalledISO3Names() { // This test checks to make sure getISO3Language and getISO3Country work right // even for locales that are not installed. @@ -663,7 +674,7 @@ public void TestUninstalledISO3Names() { for (int i = 0; i < iso2Languages.length; i++) { String test = (new Locale(iso2Languages[i], "", "")).getISO3Language(); if (!test.equals(iso3Languages[i])) { - errln("Got wrong ISO3 code for " + iso2Languages[i] + ": Expected \"" + fail("Got wrong ISO3 code for " + iso2Languages[i] + ": Expected \"" + iso3Languages[i] + "\", got \"" + test + "\"."); } } @@ -674,7 +685,7 @@ public void TestUninstalledISO3Names() { for (int i = 0; i < iso2Countries.length; i++) { String test = (new Locale("", iso2Countries[i], "")).getISO3Country(); if (!test.equals(iso3Countries[i])) { - errln("Got wrong ISO3 code for " + iso2Countries[i] + ": Expected \"" + fail("Got wrong ISO3 code for " + iso2Countries[i] + ": Expected \"" + iso3Countries[i] + "\", got \"" + test + "\"."); } } @@ -683,6 +694,7 @@ public void TestUninstalledISO3Names() { /** * @bug 4052404 4778440 8263202 */ + @Test public void TestChangedISO639Codes() { Locale hebrewOld = new Locale("iw", "IL", ""); Locale hebrewNew = new Locale("he", "IL", ""); @@ -693,28 +705,28 @@ public void TestChangedISO639Codes() { if ("true".equalsIgnoreCase(System.getProperty("java.locale.useOldISOCodes"))) { if (!hebrewNew.getLanguage().equals("iw")) { - errln("Got back wrong language code for new Hebrew: expected \"iw\", got \"" + fail("Got back wrong language code for new Hebrew: expected \"iw\", got \"" + hebrewNew.getLanguage() + "\""); } if (!yiddishNew.getLanguage().equals("ji")) { - errln("Got back wrong language code for new Yiddish: expected \"ji\", got \"" + fail("Got back wrong language code for new Yiddish: expected \"ji\", got \"" + yiddishNew.getLanguage() + "\""); } if (!indonesianNew.getLanguage().equals("in")) { - errln("Got back wrong language code for new Indonesian: expected \"in\", got \"" + fail("Got back wrong language code for new Indonesian: expected \"in\", got \"" + indonesianNew.getLanguage() + "\""); } } else { if (!hebrewOld.getLanguage().equals("he")) { - errln("Got back wrong language code for old Hebrew: expected \"he\", got \"" + fail("Got back wrong language code for old Hebrew: expected \"he\", got \"" + hebrewNew.getLanguage() + "\""); } if (!yiddishOld.getLanguage().equals("yi")) { - errln("Got back wrong language code for old Yiddish: expected \"yi\", got \"" + fail("Got back wrong language code for old Yiddish: expected \"yi\", got \"" + yiddishNew.getLanguage() + "\""); } if (!indonesianOld.getLanguage().equals("id")) { - errln("Got back wrong language code for old Indonesian: expected \"id\", got \"" + fail("Got back wrong language code for old Indonesian: expected \"id\", got \"" + indonesianNew.getLanguage() + "\""); } } @@ -738,6 +750,7 @@ public void TestChangedISO639Codes() { * 1999-11-19 joconner * */ + @Test public void TestAtypicalLocales() { Locale[] localesToTest = { new Locale("de", "CA"), new Locale("ja", "ZA"), @@ -783,27 +796,27 @@ public void TestAtypicalLocales() { for (int i = 0; i < localesToTest.length; i++) { String name = localesToTest[i].getDisplayName(Locale.US); - logln(name); + System.out.println(name); if (!name.equals(englishDisplayNames[i])) { - errln("Lookup in English failed: expected \"" + englishDisplayNames[i] + fail("Lookup in English failed: expected \"" + englishDisplayNames[i] + "\", got \"" + name + "\""); } } for (int i = 0; i < localesToTest.length; i++) { String name = localesToTest[i].getDisplayName(new Locale("es", "ES")); - logln(name); + System.out.println(name); if (!name.equals(spanishDisplayNames[i])) { - errln("Lookup in Spanish failed: expected \"" + spanishDisplayNames[i] + fail("Lookup in Spanish failed: expected \"" + spanishDisplayNames[i] + "\", got \"" + name + "\""); } } for (int i = 0; i < localesToTest.length; i++) { String name = localesToTest[i].getDisplayName(Locale.FRANCE); - logln(name); + System.out.println(name); if (!name.equals(frenchDisplayNames[i])) { - errln("Lookup in French failed: expected \"" + frenchDisplayNames[i] + fail("Lookup in French failed: expected \"" + frenchDisplayNames[i] + "\", got \"" + name + "\""); } } @@ -815,6 +828,7 @@ public void TestAtypicalLocales() { /** * @bug 4126371 */ + @Test public void TestNullDefault() { // why on earth anyone would ever try to do this is beyond me, but we should // definitely make sure we don't let them @@ -826,10 +840,10 @@ public void TestNullDefault() { gotException = true; } if (Locale.getDefault() == null) { - errln("Locale.getDefault() allowed us to set default to NULL!"); + fail("Locale.getDefault() allowed us to set default to NULL!"); } if (!gotException) { - errln("Trying to set default locale to NULL didn't throw exception!"); + fail("Trying to set default locale to NULL didn't throw exception!"); } } @@ -838,15 +852,16 @@ public void TestNullDefault() { * This would be better tested by the LocaleDataTest. Will move it when I * get the LocaleDataTest working again. */ + @Test public void TestThaiCurrencyFormat() { DecimalFormat thaiCurrency = (DecimalFormat) NumberFormat.getCurrencyInstance( new Locale("th", "TH")); if (!thaiCurrency.getPositivePrefix().equals("\u0e3f")) { - errln("Thai currency prefix wrong: expected \"\u0e3f\", got \"" + fail("Thai currency prefix wrong: expected \"\u0e3f\", got \"" + thaiCurrency.getPositivePrefix() + "\""); } if (!thaiCurrency.getPositiveSuffix().equals("")) { - errln("Thai currency suffix wrong: expected \"\", got \"" + fail("Thai currency suffix wrong: expected \"\", got \"" + thaiCurrency.getPositiveSuffix() + "\""); } } @@ -864,6 +879,7 @@ public void TestThaiCurrencyFormat() { * DON'T ASSUME: Any specific countries support the Euro. Instead, * iterate through all locales. */ + @Test public void TestEuroSupport() { final String EURO_VARIANT = "EURO"; final String EURO_CURRENCY = "\u20AC"; // Look for this string in formatted Euro currency @@ -877,10 +893,10 @@ public void TestEuroSupport() { String neg = nf.format(-271828.182845); if (pos.indexOf(EURO_CURRENCY) >= 0 && neg.indexOf(EURO_CURRENCY) >= 0) { - logln("Ok: " + loc.toString() + System.out.println("Ok: " + loc.toString() + ": " + pos + " / " + neg); } else { - errln("Fail: " + loc.toString() + fail("Fail: " + loc.toString() + " formats without " + EURO_CURRENCY + ": " + pos + " / " + neg + "\n*** THIS FAILURE MAY ONLY MEAN THAT LOCALE DATA HAS CHANGED ***"); @@ -893,6 +909,7 @@ public void TestEuroSupport() { * @bug 4139504 * toString() doesn't work with language_VARIANT. */ + @Test public void TestToString() { Object[] DATA = { new Locale("xx", "", ""), "xx", @@ -907,7 +924,7 @@ public void TestToString() { Locale loc = (Locale) DATA[i]; String fmt = (String) DATA[i + 1]; if (!loc.toString().equals(fmt)) { - errln("Fail: Locale.toString(" + fmt + ")=>" + loc); + fail("Fail: Locale.toString(" + fmt + ")=>" + loc); } } } @@ -917,6 +934,7 @@ public void TestToString() { * Currency symbol in zh is wrong. We will test this at the NumberFormat * end to test the whole pipe. */ + @Test public void Test4105828() { Locale[] LOC = {Locale.CHINESE, new Locale("zh", "CN", ""), new Locale("zh", "TW", ""), new Locale("zh", "HK", "")}; @@ -924,7 +942,7 @@ public void Test4105828() { NumberFormat fmt = NumberFormat.getPercentInstance(LOC[i]); String result = fmt.format(1); if (!result.equals("100%")) { - errln("Percent for " + LOC[i] + " should be 100%, got " + result); + fail("Percent for " + LOC[i] + " should be 100%, got " + result); } } } @@ -945,6 +963,7 @@ public void Test4105828() { * is that something is wrong with the font mapping subsystem, but we can't * test that here. */ + @Test public void Test4139940() { Locale mylocale = new Locale("hu", "", ""); @SuppressWarnings("deprecation") @@ -954,7 +973,7 @@ public void Test4139940() { // Make sure that o circumflex (\u00F4) is NOT there, and // o double acute (\u0151) IS. if (str.indexOf('\u0151') < 0 || str.indexOf('\u00F4') >= 0) { - errln("Fail: Monday in Hungarian is wrong"); + fail("Fail: Monday in Hungarian is wrong"); } } @@ -962,10 +981,11 @@ public void Test4139940() { * @bug 4143951 * Russian first day of week should be Monday. Confirmed. */ + @Test public void Test4143951() { Calendar cal = Calendar.getInstance(new Locale("ru", "", "")); if (cal.getFirstDayOfWeek() != Calendar.MONDAY) { - errln("Fail: First day of week in Russia should be Monday"); + fail("Fail: First day of week in Russia should be Monday"); } } @@ -974,6 +994,7 @@ public void Test4143951() { * java.util.Locale.getISO3Country() works wrong for non ISO-3166 codes. * Should throw an exception for unknown locales */ + @Test public void Test4147315() { // Try with codes that are the wrong length but happen to match text // at a valid offset in the mapping table @@ -982,7 +1003,7 @@ public void Test4147315() { try { String result = locale.getISO3Country(); - errln("ERROR: getISO3Country() returns: " + result + fail("ERROR: getISO3Country() returns: " + result + " for locale '" + locale + "' rather than exception"); } catch (MissingResourceException e) { } @@ -994,6 +1015,7 @@ public void Test4147315() { * Should throw an exception for unknown locales, except they have three * letter language codes. */ + @Test public void Test4147317() { // Try a three letter language code, and check whether it is // returned as is. @@ -1001,7 +1023,7 @@ public void Test4147317() { String result = locale.getISO3Language(); if (!result.equals("aaa")) { - errln("ERROR: getISO3Language() returns: " + result + fail("ERROR: getISO3Language() returns: " + result + " for locale '" + locale + "' rather than returning it as is"); } @@ -1012,7 +1034,7 @@ public void Test4147317() { try { result = locale.getISO3Language(); - errln("ERROR: getISO3Language() returns: " + result + fail("ERROR: getISO3Language() returns: " + result + " for locale '" + locale + "' rather than exception"); } catch (MissingResourceException e) { } @@ -1021,6 +1043,7 @@ public void Test4147317() { /* * @bug 4147552 4778440 8030696 */ + @Test public void Test4147552() { Locale[] locales = {new Locale("no", "NO"), new Locale("no", "NO", "B"), new Locale("no", "NO", "NY"), new Locale("nb", "NO"), @@ -1037,11 +1060,11 @@ public void Test4147552() { for (int i = 0; i < locales.length; i++) { Locale loc = locales[i]; if (!loc.getDisplayName(Locale.US).equals(englishDisplayNames[i])) { - errln("English display-name mismatch: expected " + fail("English display-name mismatch: expected " + englishDisplayNames[i] + ", got " + loc.getDisplayName()); } if (!loc.getDisplayName(loc).equals(norwegianDisplayNames[i])) { - errln("Norwegian display-name mismatch: expected " + fail("Norwegian display-name mismatch: expected " + norwegianDisplayNames[i] + ", got " + loc.getDisplayName(loc)); } @@ -1051,11 +1074,12 @@ public void Test4147552() { /* * @bug 8030696 */ + @Test public void Test8030696() { List av = Arrays.asList(Locale.getAvailableLocales()); if (!av.contains(new Locale("nb", "NO")) || !av.contains(new Locale("nn", "NO"))) { - errln("\"nb-NO\" and/or \"nn-NO\" locale(s) not returned from getAvailableLocales()."); + fail("\"nb-NO\" and/or \"nn-NO\" locale(s) not returned from getAvailableLocales()."); } } diff --git a/test/jdk/java/util/TimeZone/Bug4322313.java b/test/jdk/java/util/TimeZone/Bug4322313.java index a65a87149b9..d3c87b50595 100644 --- a/test/jdk/java/util/TimeZone/Bug4322313.java +++ b/test/jdk/java/util/TimeZone/Bug4322313.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,14 +27,18 @@ * @summary Make sure that new implementation of custom time zone * support for TimeZone.getTimeZone() works correctly and the * getDisplayName() methods are locale independent. - * @library /java/text/testlib + * @run junit Bug4322313 */ import java.io.*; import java.text.*; import java.util.*; -public class Bug4322313 extends IntlTest { +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class Bug4322313 { private static final int MPM = 60 * 1000; /* Milliseconds per minute */ private static final Object[][] VALIDS = { /* given ID rawOffset normalized ID */ @@ -106,7 +110,7 @@ void Test4322313() { "\"] Invalid TimeZone ID, expected:" + VALIDS[k][2] + ", got:" + tz.getID() + ", " + tz); } else { - logln("\tPassed [Locale=" + + System.out.println("\tPassed [Locale=" + locale + ", \"" + VALIDS[k][0] + "\"] Valid TimeZone ID, got:" + VALIDS[k][2]); } @@ -119,7 +123,7 @@ void Test4322313() { "\"] Invalid RawOffset, expected:" + VALIDS[k][1] + ", got:" + offset + ", " + tz); } else { - logln("\tPassed [Locale=" + + System.out.println("\tPassed [Locale=" + locale + ", \"" + VALIDS[k][0] + "\"] Vaild RawOffset, got:" + offset); } @@ -132,7 +136,7 @@ void Test4322313() { "\"] DSTSavings should be zero, got:" + offset + ", " + tz); } else { - logln("\tPassed [Locale=" + + System.out.println("\tPassed [Locale=" + locale + ", \"" + VALIDS[k][0] + "\"] DSTSavings is zero."); } @@ -150,7 +154,7 @@ void Test4322313() { "\"] Invalid TimeZone ID, expected:GMT, got:" + tz.getID() + ", " + tz); } else { - logln("\tPassed [Locale=" + + System.out.println("\tPassed [Locale=" + locale + ", \"" + INVALIDS[k] + "\"] Valid TimeZone ID, got:" + tz.getID()); } @@ -163,7 +167,7 @@ void Test4322313() { "\"] RawOffset should be zero, got:" + offset + ", " + tz); } else { - logln("\tPassed [Locale=" + + System.out.println("\tPassed [Locale=" + locale + ", \"" + INVALIDS[k] + "\"] RawOffset is zero."); } @@ -176,7 +180,7 @@ void Test4322313() { "\"] DSTSavings should be zero, got:" + offset + ", " + tz); } else { - logln("\tPassed [Locale=" + + System.out.println("\tPassed [Locale=" + locale + ", \"" + INVALIDS[k] + "\"] DSTSavings is zero."); } @@ -218,13 +222,10 @@ void Test4322313() { TimeZone.setDefault(savedTimeZone); } if (err) { - errln("TimeZone.getTimeZone() test failed"); + fail("TimeZone.getTimeZone() test failed"); } else { - logln("TimeZone.getTimeZone() test passed"); + System.out.println("TimeZone.getTimeZone() test passed"); } } - public static void main (String[] args) throws Exception { - new Bug4322313().run(args); - } } diff --git a/test/jdk/java/util/TimeZone/Bug6329116.java b/test/jdk/java/util/TimeZone/Bug6329116.java index 32105881194..6e85fe8cb5b 100644 --- a/test/jdk/java/util/TimeZone/Bug6329116.java +++ b/test/jdk/java/util/TimeZone/Bug6329116.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,27 +27,24 @@ * 7039469 7090843 7103108 7103405 7158483 8008577 8059206 8064560 8072042 * 8077685 8151876 8166875 8169191 8170316 8176044 * @summary Make sure that timezone short display names are idenical to Olson's data. - * @library /java/text/testlib - * @build Bug6329116 TextFileReader - * @run main/othervm -Djava.locale.providers=COMPAT,SPI Bug6329116 + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI Bug6329116 */ import java.io.*; import java.text.*; import java.util.*; -public class Bug6329116 extends IntlTest { +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class Bug6329116 { static Locale[] locales = Locale.getAvailableLocales(); static String[] timezones = TimeZone.getAvailableIDs(); - public static void main(String[] args) throws IOException { - if (bug6329116()) { - throw new RuntimeException("At least one timezone display name is incorrect."); - } - } - - static boolean bug6329116() throws IOException { + @Test + public void bug6329116() throws IOException { boolean err = false; HashMap aliasTable = new HashMap<>(); @@ -200,7 +197,9 @@ static boolean bug6329116() throws IOException { } } - return err; + if (err) { + fail("At least one timezone display name is incorrect."); + } } static boolean useLocalzedShortDisplayName(TimeZone tz, diff --git a/test/jdk/java/util/TimeZone/TimeZoneBoundaryTest.java b/test/jdk/java/util/TimeZone/TimeZoneBoundaryTest.java index a1d44ea080d..c70ccc204de 100644 --- a/test/jdk/java/util/TimeZone/TimeZoneBoundaryTest.java +++ b/test/jdk/java/util/TimeZone/TimeZoneBoundaryTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,18 +23,26 @@ /* * @test - * @library /java/text/testlib * @summary test Time Zone Boundary + * @run junit TimeZoneBoundaryTest */ -import java.text.*; -import java.util.*; +import java.text.DateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.SimpleTimeZone; +import java.util.TimeZone; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; /** * A test which discovers the boundaries of DST programmatically and verifies * that they are correct. */ -public class TimeZoneBoundaryTest extends IntlTest +public class TimeZoneBoundaryTest { static final int ONE_SECOND = 1000; static final int ONE_MINUTE = 60*ONE_SECOND; @@ -57,10 +65,6 @@ public class TimeZoneBoundaryTest extends IntlTest static final long AUSTRALIA_1997_BEG = 877797000000L; static final long AUSTRALIA_1997_END = 859653000000L; - public static void main(String[] args) throws Exception { - new TimeZoneBoundaryTest().run(args); - } - /** * Date.toString().substring() Boundary Test * Look for a DST changeover to occur within 6 months of the given Date. @@ -75,7 +79,7 @@ void findDaylightBoundaryUsingDate(Date d, String startMode, long expectedBounda if (d.toString().indexOf(startMode) == -1) { - logln("Error: " + startMode + " not present in " + d); + System.out.println("Error: " + startMode + " not present in " + d); } // Use a binary search, assuming that we have a Standard @@ -98,15 +102,15 @@ void findDaylightBoundaryUsingDate(Date d, String startMode, long expectedBounda } } - logln("Date Before: " + showDate(min)); - logln("Date After: " + showDate(max)); + System.out.println("Date Before: " + showDate(min)); + System.out.println("Date After: " + showDate(max)); long mindelta = expectedBoundary - min; long maxdelta = max - expectedBoundary; if (mindelta >= 0 && mindelta <= INTERVAL && mindelta >= 0 && mindelta <= INTERVAL) - logln("PASS: Expected boundary at " + expectedBoundary); + System.out.println("PASS: Expected boundary at " + expectedBoundary); else - errln("FAIL: Expected boundary at " + expectedBoundary); + fail("FAIL: Expected boundary at " + expectedBoundary); } void findDaylightBoundaryUsingTimeZone(Date d, boolean startsInDST, long expectedBoundary) @@ -128,14 +132,14 @@ void findDaylightBoundaryUsingTimeZone(Date d, boolean startsInDST, if (tz.inDaylightTime(d) != startsInDST) { - errln("FAIL: " + tz.getID() + " inDaylightTime(" + + fail("FAIL: " + tz.getID() + " inDaylightTime(" + d + ") != " + startsInDST); startsInDST = !startsInDST; // Flip over; find the apparent value } if (tz.inDaylightTime(new Date(max)) == startsInDST) { - errln("FAIL: " + tz.getID() + " inDaylightTime(" + + fail("FAIL: " + tz.getID() + " inDaylightTime(" + (new Date(max)) + ") != " + (!startsInDST)); return; } @@ -154,16 +158,16 @@ void findDaylightBoundaryUsingTimeZone(Date d, boolean startsInDST, } } - logln(tz.getID() + " Before: " + showDate(min, tz)); - logln(tz.getID() + " After: " + showDate(max, tz)); + System.out.println(tz.getID() + " Before: " + showDate(min, tz)); + System.out.println(tz.getID() + " After: " + showDate(max, tz)); long mindelta = expectedBoundary - min; long maxdelta = max - expectedBoundary; if (mindelta >= 0 && mindelta <= INTERVAL && mindelta >= 0 && mindelta <= INTERVAL) - logln("PASS: Expected boundary at " + expectedBoundary); + System.out.println("PASS: Expected boundary at " + expectedBoundary); else - errln("FAIL: Expected boundary at " + expectedBoundary); + fail("FAIL: Expected boundary at " + expectedBoundary); } private static String showDate(long l) @@ -209,23 +213,23 @@ void verifyDST(Date d, TimeZone time_zone, boolean expUseDaylightTime, boolean expInDaylightTime, int expZoneOffset, int expDSTOffset) { - logln("-- Verifying time " + d + + System.out.println("-- Verifying time " + d + " in zone " + time_zone.getID()); if (time_zone.inDaylightTime(d) == expInDaylightTime) - logln("PASS: inDaylightTime = " + time_zone.inDaylightTime(d)); + System.out.println("PASS: inDaylightTime = " + time_zone.inDaylightTime(d)); else - errln("FAIL: inDaylightTime = " + time_zone.inDaylightTime(d)); + fail("FAIL: inDaylightTime = " + time_zone.inDaylightTime(d)); if (time_zone.useDaylightTime() == expUseDaylightTime) - logln("PASS: useDaylightTime = " + time_zone.useDaylightTime()); + System.out.println("PASS: useDaylightTime = " + time_zone.useDaylightTime()); else - errln("FAIL: useDaylightTime = " + time_zone.useDaylightTime()); + fail("FAIL: useDaylightTime = " + time_zone.useDaylightTime()); if (time_zone.getRawOffset() == expZoneOffset) - logln("PASS: getRawOffset() = " + expZoneOffset/(double)ONE_HOUR); + System.out.println("PASS: getRawOffset() = " + expZoneOffset/(double)ONE_HOUR); else - errln("FAIL: getRawOffset() = " + time_zone.getRawOffset()/(double)ONE_HOUR + + fail("FAIL: getRawOffset() = " + time_zone.getRawOffset()/(double)ONE_HOUR + "; expected " + expZoneOffset/(double)ONE_HOUR); GregorianCalendar gc = new GregorianCalendar(time_zone); @@ -237,13 +241,14 @@ void verifyDST(Date d, TimeZone time_zone, gc.get(gc.SECOND)) * 1000 + gc.get(gc.MILLISECOND)); if (offset == expDSTOffset) - logln("PASS: getOffset() = " + offset/(double)ONE_HOUR); + System.out.println("PASS: getOffset() = " + offset/(double)ONE_HOUR); else - errln("FAIL: getOffset() = " + offset/(double)ONE_HOUR + + fail("FAIL: getOffset() = " + offset/(double)ONE_HOUR + "; expected " + expDSTOffset/(double)ONE_HOUR); } @SuppressWarnings("deprecation") + @Test public void TestBoundaries() { TimeZone pst = TimeZone.getTimeZone("PST"); @@ -263,19 +268,19 @@ public void TestBoundaries() inDST ? -7*ONE_HOUR : -8*ONE_HOUR); } - logln("========================================"); + System.out.println("========================================"); findDaylightBoundaryUsingDate(new Date(97,0,1), "PST", PST_1997_BEG); - logln("========================================"); + System.out.println("========================================"); findDaylightBoundaryUsingDate(new Date(97,6,1), "PDT", PST_1997_END); // Southern hemisphere test - logln("========================================"); + System.out.println("========================================"); TimeZone z = TimeZone.getTimeZone(AUSTRALIA); findDaylightBoundaryUsingTimeZone(new Date(97,0,1), true, AUSTRALIA_1997_END, z); - logln("========================================"); + System.out.println("========================================"); findDaylightBoundaryUsingTimeZone(new Date(97,0,1), false, PST_1997_BEG); - logln("========================================"); + System.out.println("========================================"); findDaylightBoundaryUsingTimeZone(new Date(97,6,1), true, PST_1997_END); } finally { TimeZone.setDefault(save); @@ -297,7 +302,7 @@ void testUsingBinarySearch(SimpleTimeZone tz, Date d, long expectedBoundary) if (tz.inDaylightTime(new Date(max)) == startsInDST) { - logln("Error: inDaylightTime(" + (new Date(max)) + ") != " + (!startsInDST)); + System.out.println("Error: inDaylightTime(" + (new Date(max)) + ") != " + (!startsInDST)); } while ((max - min) > INTERVAL) @@ -313,121 +318,50 @@ void testUsingBinarySearch(SimpleTimeZone tz, Date d, long expectedBoundary) } } - logln("Binary Search Before: " + showDate(min)); - logln("Binary Search After: " + showDate(max)); + System.out.println("Binary Search Before: " + showDate(min)); + System.out.println("Binary Search After: " + showDate(max)); long mindelta = expectedBoundary - min; long maxdelta = max - expectedBoundary; if (mindelta >= 0 && mindelta <= INTERVAL && mindelta >= 0 && mindelta <= INTERVAL) - logln("PASS: Expected boundary at " + expectedBoundary); + System.out.println("PASS: Expected boundary at " + expectedBoundary); else - errln("FAIL: Expected boundary at " + expectedBoundary); + fail("FAIL: Expected boundary at " + expectedBoundary); } - /* - static void testUsingMillis(Date d, boolean startsInDST) - { - long millis = d.getTime(); - long max = millis + (long)(370 * ONE_DAY); // A year plus extra - - boolean lastDST = startsInDST; - while (millis < max) - { - cal.setTime(new Date(millis)); - boolean inDaylight = cal.inDaylightTime(); - - if (inDaylight != lastDST) - { - logln("Switch " + (inDaylight ? "into" : "out of") - + " DST at " + (new Date(millis))); - lastDST = inDaylight; - } - - millis += 15*ONE_MINUTE; - } - } - */ - /** * Test new rule formats. */ @SuppressWarnings("deprecation") - public void TestNewRules() - { - //logln(Locale.getDefault().getDisplayName()); - //logln(TimeZone.getDefault().getID()); - //logln(new Date(0)); - - if (true) - { - // Doesn't matter what the default TimeZone is here, since we - // are creating our own TimeZone objects. - - SimpleTimeZone tz; - - logln("-----------------------------------------------------------------"); - logln("Aug 2ndTues .. Mar 15"); - tz = new SimpleTimeZone(-8*ONE_HOUR, "Test_1", - Calendar.AUGUST, 2, Calendar.TUESDAY, 2*ONE_HOUR, - Calendar.MARCH, 15, 0, 2*ONE_HOUR); - //logln(tz.toString()); - logln("========================================"); - testUsingBinarySearch(tz, new Date(97,0,1), 858416400000L); - logln("========================================"); - testUsingBinarySearch(tz, new Date(97,6,1), 871380000000L); - - logln("-----------------------------------------------------------------"); - logln("Apr Wed>=14 .. Sep Sun<=20"); - tz = new SimpleTimeZone(-8*ONE_HOUR, "Test_2", - Calendar.APRIL, 14, -Calendar.WEDNESDAY, 2*ONE_HOUR, - Calendar.SEPTEMBER, -20, -Calendar.SUNDAY, 2*ONE_HOUR); - //logln(tz.toString()); - logln("========================================"); - testUsingBinarySearch(tz, new Date(97,0,1), 861184800000L); - logln("========================================"); - testUsingBinarySearch(tz, new Date(97,6,1), 874227600000L); - } - - /* - if (true) - { - logln("========================================"); - logln("Stepping using millis"); - testUsingMillis(new Date(97,0,1), false); - } - - if (true) - { - logln("========================================"); - logln("Stepping using fields"); - testUsingFields(1997, false); - } - - if (false) - { - cal.clear(); - cal.set(1997, 3, 5, 10, 0); - // cal.inDaylightTime(); - logln("Date = " + cal.getTime()); - logln("Millis = " + cal.getTime().getTime()/3600000); - } - */ + @Test + public void TestNewRules() { + // Doesn't matter what the default TimeZone is here, since we + // are creating our own TimeZone objects. + + SimpleTimeZone tz; + + System.out.println("-----------------------------------------------------------------"); + System.out.println("Aug 2ndTues .. Mar 15"); + tz = new SimpleTimeZone(-8*ONE_HOUR, "Test_1", + Calendar.AUGUST, 2, Calendar.TUESDAY, 2*ONE_HOUR, + Calendar.MARCH, 15, 0, 2*ONE_HOUR); + System.out.println("========================================"); + testUsingBinarySearch(tz, new Date(97,0,1), 858416400000L); + System.out.println("========================================"); + testUsingBinarySearch(tz, new Date(97,6,1), 871380000000L); + + System.out.println("-----------------------------------------------------------------"); + System.out.println("Apr Wed>=14 .. Sep Sun<=20"); + tz = new SimpleTimeZone(-8*ONE_HOUR, "Test_2", + Calendar.APRIL, 14, -Calendar.WEDNESDAY, 2*ONE_HOUR, + Calendar.SEPTEMBER, -20, -Calendar.SUNDAY, 2*ONE_HOUR); + System.out.println("========================================"); + testUsingBinarySearch(tz, new Date(97,0,1), 861184800000L); + System.out.println("========================================"); + testUsingBinarySearch(tz, new Date(97,6,1), 874227600000L); } - //---------------------------------------------------------------------- - //---------------------------------------------------------------------- - //---------------------------------------------------------------------- - // Long Bug - //---------------------------------------------------------------------- - //---------------------------------------------------------------------- - //---------------------------------------------------------------------- - - //public void Test3() - //{ - // findDaylightBoundaryUsingTimeZone(new Date(97,6,1), true); - //} - /** * Find boundaries by stepping. */ @@ -439,15 +373,15 @@ void findBoundariesStepwise(int year, long interval, TimeZone z, int expectedCha long limit = time + ONE_YEAR + ONE_DAY; boolean lastState = z.inDaylightTime(d); int changes = 0; - logln("-- Zone " + z.getID() + " starts in " + year + " with DST = " + lastState); - logln("useDaylightTime = " + z.useDaylightTime()); + System.out.println("-- Zone " + z.getID() + " starts in " + year + " with DST = " + lastState); + System.out.println("useDaylightTime = " + z.useDaylightTime()); while (time < limit) { d.setTime(time); boolean state = z.inDaylightTime(d); if (state != lastState) { - logln((state ? "Entry " : "Exit ") + + System.out.println((state ? "Entry " : "Exit ") + "at " + d); lastState = state; ++changes; @@ -456,23 +390,24 @@ void findBoundariesStepwise(int year, long interval, TimeZone z, int expectedCha } if (changes == 0) { - if (!lastState && !z.useDaylightTime()) logln("No DST"); - else errln("FAIL: Timezone<" + z.getID() + "> DST all year, or no DST with true useDaylightTime"); + if (!lastState && !z.useDaylightTime()) System.out.println("No DST"); + else fail("FAIL: Timezone<" + z.getID() + "> DST all year, or no DST with true useDaylightTime"); } else if (changes != 2) { - errln("FAIL: Timezone<" + z.getID() + "> " + changes + " changes seen; should see 0 or 2"); + fail("FAIL: Timezone<" + z.getID() + "> " + changes + " changes seen; should see 0 or 2"); } else if (!z.useDaylightTime()) { - errln("FAIL: Timezone<" + z.getID() + "> useDaylightTime false but 2 changes seen"); + fail("FAIL: Timezone<" + z.getID() + "> useDaylightTime false but 2 changes seen"); } if (changes != expectedChanges) { - errln("FAIL: Timezone<" + z.getID() + "> " + changes + " changes seen; expected " + expectedChanges); + fail("FAIL: Timezone<" + z.getID() + "> " + changes + " changes seen; expected " + expectedChanges); } } + @Test public void TestStepwise() { findBoundariesStepwise(1997, ONE_DAY, TimeZone.getTimeZone("ACT"), 0); diff --git a/test/jdk/java/util/TimeZone/TimeZoneRegression.java b/test/jdk/java/util/TimeZone/TimeZoneRegression.java index 3dabbe49119..6343279689f 100644 --- a/test/jdk/java/util/TimeZone/TimeZoneRegression.java +++ b/test/jdk/java/util/TimeZone/TimeZoneRegression.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,42 +27,44 @@ * 4154525 4154537 4154542 4154650 4159922 4162593 4173604 4176686 4184229 4208960 * 4966229 6433179 6851214 8007520 8008577 * @library /java/text/testlib - * @run main/othervm -Djava.locale.providers=COMPAT,SPI TimeZoneRegression + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI TimeZoneRegression */ import java.util.*; import java.io.*; import java.text.*; -public class TimeZoneRegression extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new TimeZoneRegression().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class TimeZoneRegression { + @Test public void Test4073209() { TimeZone z1 = TimeZone.getTimeZone("PST"); TimeZone z2 = TimeZone.getTimeZone("PST"); if (z1 == z2) { - errln("Fail: TimeZone should return clones"); + fail("Fail: TimeZone should return clones"); } } @SuppressWarnings("deprecation") + @Test public void Test4073215() { SimpleTimeZone z = new SimpleTimeZone(0, "GMT"); if (z.useDaylightTime()) { - errln("Fail: Fix test to start with non-DST zone"); + fail("Fail: Fix test to start with non-DST zone"); } z.setStartRule(Calendar.FEBRUARY, 1, Calendar.SUNDAY, 0); z.setEndRule(Calendar.MARCH, -1, Calendar.SUNDAY, 0); if (!z.useDaylightTime()) { - errln("Fail: DST not active"); + fail("Fail: DST not active"); } if (z.inDaylightTime(new Date(97, Calendar.JANUARY, 31)) || !z.inDaylightTime(new Date(97, Calendar.MARCH, 1)) || z.inDaylightTime(new Date(97, Calendar.MARCH, 31))) { - errln("Fail: DST not working as expected"); + fail("Fail: DST not working as expected"); } } @@ -74,6 +76,7 @@ public void Test4073215() { * day of end 0:59 AM STD = display name 1:59 AM DT * 1:00 AM STD = display name 1:00 AM ST */ + @Test public void Test4084933() { // test both SimpleTimeZone and ZoneInfo objects. // @since 1.4 @@ -113,10 +116,11 @@ private void sub4084933(TimeZone tz) { offset3 != SToffset || offset4 != DToffset || offset5 != DToffset || offset6 != SToffset || offset7 != SToffset || offset8 != SToffset) - errln("Fail: TimeZone misbehaving"); { + fail("Fail: TimeZone misbehaving"); { } } + @Test public void Test4096952() { String[] ZONES = { "GMT", "MET", "IST" }; boolean pass = true; @@ -124,7 +128,7 @@ public void Test4096952() { for (int i=0; i max) max = ids.length; - logln(hname + ' ' + ids.length + + System.out.println(hname + ' ' + ids.length + ((ids.length > 0) ? (" e.g. " + ids[0]) : "")); } catch (Exception e) { - errln(hname + ' ' + "Fail: " + e); + fail(hname + ' ' + "Fail: " + e); } } - logln("Maximum zones per offset = " + max); + System.out.println("Maximum zones per offset = " + max); } + @Test public void Test4151429() { try { TimeZone tz = TimeZone.getTimeZone("GMT"); String name = tz.getDisplayName(true, Integer.MAX_VALUE, Locale.getDefault()); - errln("IllegalArgumentException not thrown by TimeZone.getDisplayName()"); + fail("IllegalArgumentException not thrown by TimeZone.getDisplayName()"); } catch(IllegalArgumentException e) {} } @@ -373,6 +381,7 @@ public void Test4151429() { * SimpleTimeZone accepts illegal DST savings values. These values * must be non-zero. There is no upper limit at this time. */ + @Test public void Test4154525() { final int GOOD = 1, BAD = 0; int[] DATA = { @@ -404,15 +413,15 @@ public void Test4154525() { break; } if (valid) { - logln("Pass: DST savings of " + savings + " accepted by " + method); + System.out.println("Pass: DST savings of " + savings + " accepted by " + method); } else { - errln("Fail: DST savings of " + savings + " accepted by " + method); + fail("Fail: DST savings of " + savings + " accepted by " + method); } } catch (IllegalArgumentException e) { if (valid) { - errln("Fail: DST savings of " + savings + " to " + method + " gave " + e); + fail("Fail: DST savings of " + savings + " to " + method + " gave " + e); } else { - logln("Pass: DST savings of " + savings + " to " + method + " gave " + e); + System.out.println("Pass: DST savings of " + savings + " to " + method + " gave " + e); } } } @@ -423,6 +432,7 @@ public void Test4154525() { * SimpleTimeZone.hasSameRules() doesn't work for zones with no DST * and different DST parameters. */ + @Test public void Test4154537() { // tz1 and tz2 have no DST and different rule parameters SimpleTimeZone tz1 = new SimpleTimeZone(0, "1", 0, 0, 0, 0, 2, 0, 0, 0); @@ -435,15 +445,15 @@ public void Test4154537() { if (tz1.useDaylightTime() || tz2.useDaylightTime() || !tza.useDaylightTime() || !tzA.useDaylightTime() || !tzb.useDaylightTime()) { - errln("Test is broken -- rewrite it"); + fail("Test is broken -- rewrite it"); } if (!tza.hasSameRules(tzA) || tza.hasSameRules(tzb)) { - errln("Fail: hasSameRules() broken for zones with rules"); + fail("Fail: hasSameRules() broken for zones with rules"); } if (!tz1.hasSameRules(tz2)) { - errln("Fail: hasSameRules() returns false for zones without rules"); - errln("zone 1 = " + tz1); - errln("zone 2 = " + tz2); + fail("Fail: hasSameRules() returns false for zones without rules"); + fail("zone 1 = " + tz1); + fail("zone 2 = " + tz2); } } @@ -451,6 +461,7 @@ public void Test4154537() { * SimpleTimeZone constructors, setStartRule(), and setEndRule() don't * check for out-of-range arguments. */ + @Test public void Test4154542() { final int GOOD = 1; final int BAD = 0; @@ -496,7 +507,7 @@ public void Test4154542() { ex = e; } if ((ex == null) != shouldBeGood) { - errln("setStartRule(month=" + month + ", day=" + day + + fail("setStartRule(month=" + month + ", day=" + day + ", dayOfWeek=" + dayOfWeek + ", time=" + time + (shouldBeGood ? (") should work but throws " + ex) : ") should fail but doesn't")); @@ -509,7 +520,7 @@ public void Test4154542() { ex = e; } if ((ex == null) != shouldBeGood) { - errln("setEndRule(month=" + month + ", day=" + day + + fail("setEndRule(month=" + month + ", day=" + day + ", dayOfWeek=" + dayOfWeek + ", time=" + time + (shouldBeGood ? (") should work but throws " + ex) : ") should fail but doesn't")); @@ -524,7 +535,7 @@ public void Test4154542() { ex = e; } if ((ex == null) != shouldBeGood) { - errln("SimpleTimeZone(month=" + month + ", day=" + day + + fail("SimpleTimeZone(month=" + month + ", day=" + day + ", dayOfWeek=" + dayOfWeek + ", time=" + time + (shouldBeGood ? (", ) should work but throws " + ex) : ", ) should fail but doesn't")); @@ -539,7 +550,7 @@ public void Test4154542() { ex = e; } if ((ex == null) != shouldBeGood) { - errln("SimpleTimeZone(, month=" + month + ", day=" + day + + fail("SimpleTimeZone(, month=" + month + ", day=" + day + ", dayOfWeek=" + dayOfWeek + ", time=" + time + (shouldBeGood ? (") should work but throws " + ex) : ") should fail but doesn't")); @@ -550,6 +561,7 @@ public void Test4154542() { /** * SimpleTimeZone.getOffset accepts illegal arguments. */ + @Test public void Test4154650() { final int GOOD=1, BAD=0; final int GOOD_ERA=GregorianCalendar.AD, GOOD_YEAR=1998, GOOD_MONTH=Calendar.AUGUST; @@ -594,7 +606,7 @@ public void Test4154650() { e = ex; } if (good != (e == null)) { - errln("Fail: getOffset(" + + fail("Fail: getOffset(" + DATA[i+1] + ", " + DATA[i+2] + ", " + DATA[i+3] + ", " + DATA[i+4] + ", " + DATA[i+5] + ", " + DATA[i+6] + (good ? (") threw " + e) : ") accepts invalid args")); @@ -605,6 +617,7 @@ public void Test4154650() { /** * TimeZone constructors allow null IDs. */ + @Test public void Test4159922() { TimeZone z = null; @@ -612,38 +625,38 @@ public void Test4159922() { // allow null. try { z = TimeZone.getTimeZone((String)null); - errln("FAIL: Null allowed in getTimeZone"); + fail("FAIL: Null allowed in getTimeZone"); } catch (NullPointerException e) {} z = TimeZone.getTimeZone("GMT"); try { z.getDisplayName(false, TimeZone.SHORT, null); - errln("FAIL: Null allowed in getDisplayName(3)"); + fail("FAIL: Null allowed in getDisplayName(3)"); } catch (NullPointerException e) {} try { z.getDisplayName(null); - errln("FAIL: Null allowed in getDisplayName(1)"); + fail("FAIL: Null allowed in getDisplayName(1)"); } catch (NullPointerException e) {} try { if (z.hasSameRules(null)) { - errln("FAIL: hasSameRules returned true"); + fail("FAIL: hasSameRules returned true"); } } catch (NullPointerException e) { - errln("FAIL: Null NOT allowed in hasSameRules"); + fail("FAIL: Null NOT allowed in hasSameRules"); } try { z.inDaylightTime(null); - errln("FAIL: Null allowed in inDaylightTime"); + fail("FAIL: Null allowed in inDaylightTime"); } catch (NullPointerException e) {} try { z.setID(null); - errln("FAIL: Null allowed in setID"); + fail("FAIL: Null allowed in setID"); } catch (NullPointerException e) {} TimeZone save = TimeZone.getDefault(); try { TimeZone.setDefault(null); } catch (NullPointerException e) { - errln("FAIL: Null NOT allowed in setDefault"); + fail("FAIL: Null NOT allowed in setDefault"); } finally { TimeZone.setDefault(save); } @@ -652,15 +665,15 @@ public void Test4159922() { SimpleTimeZone s = null; try { s = new SimpleTimeZone(0, null); - errln("FAIL: Null allowed in SimpleTimeZone(2)"); + fail("FAIL: Null allowed in SimpleTimeZone(2)"); } catch (NullPointerException e) {} try { s = new SimpleTimeZone(0, null, 0, 1, 0, 0, 0, 1, 0, 0); - errln("FAIL: Null allowed in SimpleTimeZone(10)"); + fail("FAIL: Null allowed in SimpleTimeZone(10)"); } catch (NullPointerException e) {} try { s = new SimpleTimeZone(0, null, 0, 1, 0, 0, 0, 1, 0, 0, 1000); - errln("FAIL: Null allowed in SimpleTimeZone(11)"); + fail("FAIL: Null allowed in SimpleTimeZone(11)"); } catch (NullPointerException e) {} } @@ -669,6 +682,7 @@ public void Test4159922() { * transitions at midnight correctly. */ @SuppressWarnings("deprecation") + @Test public void Test4162593() { SimpleDateFormat fmt = new SimpleDateFormat("z", Locale.US); final int ONE_HOUR = 60*60*1000; @@ -711,18 +725,18 @@ public void Test4162593() { Date d = new Date(p[0], p[1], p[2], p[3], p[4]); boolean transitionExpected = ((Boolean)DATA[j+2]).booleanValue(); - logln(tz.getID() + ":"); + System.out.println(tz.getID() + ":"); for (int i=0; i<4; ++i) { zone[i] = fmt.format(d); - logln("" + i + ": " + d); + System.out.println("" + i + ": " + d); d = new Date(d.getTime() + ONE_HOUR); } if (zone[0].equals(zone[1]) && (zone[1].equals(zone[2]) != transitionExpected) && zone[2].equals(zone[3])) { - logln("Ok: transition " + transitionExpected); + System.out.println("Ok: transition " + transitionExpected); } else { - errln("Fail: boundary transition incorrect"); + fail("Fail: boundary transition incorrect"); } } } @@ -736,6 +750,7 @@ public void Test4162593() { /** * TimeZone broken in last hour of year */ + @Test public void Test4173604() { // test both SimpleTimeZone and ZoneInfo objects. // @since 1.4 @@ -748,7 +763,7 @@ private void sub4173604(TimeZone pst) { int o23 = pst.getOffset(1, 1998, 11, 31, Calendar.THURSDAY, 23*60*60*1000); int o00 = pst.getOffset(1, 1999, 0, 1, Calendar.FRIDAY, 0); if (o22 != o23 || o22 != o00) { - errln("Offsets should be the same (for PST), but got: " + + fail("Offsets should be the same (for PST), but got: " + "12/31 22:00 " + o22 + ", 12/31 23:00 " + o23 + ", 01/01 00:00 " + o00); @@ -767,12 +782,12 @@ private void sub4173604(TimeZone pst) { ++transitions; Calendar t = (Calendar)cal.clone(); t.add(Calendar.MINUTE, -delta); - logln(t.getTime() + " " + t.get(Calendar.DST_OFFSET)); - logln(cal.getTime() + " " + (lastDST=cal.get(Calendar.DST_OFFSET))); + System.out.println(t.getTime() + " " + t.get(Calendar.DST_OFFSET)); + System.out.println(cal.getTime() + " " + (lastDST=cal.get(Calendar.DST_OFFSET))); } } if (transitions != 4) { - errln("Saw " + transitions + " transitions; should have seen 4"); + fail("Saw " + transitions + " transitions; should have seen 4"); } } @@ -780,6 +795,7 @@ private void sub4173604(TimeZone pst) { * getDisplayName doesn't work with unusual savings/offsets. */ @SuppressWarnings("deprecation") + @Test public void Test4176686() { // Construct a zone that does not observe DST but // that does have a DST savings (which should be ignored). @@ -827,7 +843,7 @@ public void Test4176686() { for (int i=0; i " + DATA[i+1] + ", exp " + DATA[i+2]); + fail("FAIL: " + DATA[i] + " -> " + DATA[i+1] + ", exp " + DATA[i+2]); } } } @@ -835,57 +851,58 @@ public void Test4176686() { /** * SimpleTimeZone allows invalid DOM values. */ + @Test public void Test4184229() { SimpleTimeZone zone = null; try { zone = new SimpleTimeZone(0, "A", 0, -1, 0, 0, 0, 0, 0, 0); - errln("Failed. No exception has been thrown for DOM -1 startDay"); + fail("Failed. No exception has been thrown for DOM -1 startDay"); } catch(IllegalArgumentException e) { - logln("(a) " + e.getMessage()); + System.out.println("(a) " + e.getMessage()); } try { zone = new SimpleTimeZone(0, "A", 0, 0, 0, 0, 0, -1, 0, 0); - errln("Failed. No exception has been thrown for DOM -1 endDay"); + fail("Failed. No exception has been thrown for DOM -1 endDay"); } catch(IllegalArgumentException e) { - logln("(b) " + e.getMessage()); + System.out.println("(b) " + e.getMessage()); } try { zone = new SimpleTimeZone(0, "A", 0, -1, 0, 0, 0, 0, 0, 0, 1000); - errln("Failed. No exception has been thrown for DOM -1 startDay +savings"); + fail("Failed. No exception has been thrown for DOM -1 startDay +savings"); } catch(IllegalArgumentException e) { - logln("(c) " + e.getMessage()); + System.out.println("(c) " + e.getMessage()); } try { zone = new SimpleTimeZone(0, "A", 0, 0, 0, 0, 0, -1, 0, 0, 1000); - errln("Failed. No exception has been thrown for DOM -1 endDay +savings"); + fail("Failed. No exception has been thrown for DOM -1 endDay +savings"); } catch(IllegalArgumentException e) { - logln("(d) " + e.getMessage()); + System.out.println("(d) " + e.getMessage()); } // Make a valid constructor call for subsequent tests. zone = new SimpleTimeZone(0, "A", 0, 1, 0, 0, 0, 1, 0, 0); try { zone.setStartRule(0, -1, 0, 0); - errln("Failed. No exception has been thrown for DOM -1 setStartRule +savings"); + fail("Failed. No exception has been thrown for DOM -1 setStartRule +savings"); } catch(IllegalArgumentException e) { - logln("(e) " + e.getMessage()); + System.out.println("(e) " + e.getMessage()); } try { zone.setStartRule(0, -1, 0); - errln("Failed. No exception has been thrown for DOM -1 setStartRule"); + fail("Failed. No exception has been thrown for DOM -1 setStartRule"); } catch(IllegalArgumentException e) { - logln("(f) " + e.getMessage()); + System.out.println("(f) " + e.getMessage()); } try { zone.setEndRule(0, -1, 0, 0); - errln("Failed. No exception has been thrown for DOM -1 setEndRule +savings"); + fail("Failed. No exception has been thrown for DOM -1 setEndRule +savings"); } catch(IllegalArgumentException e) { - logln("(g) " + e.getMessage()); + System.out.println("(g) " + e.getMessage()); } try { zone.setEndRule(0, -1, 0); - errln("Failed. No exception has been thrown for DOM -1 setEndRule"); + fail("Failed. No exception has been thrown for DOM -1 setEndRule"); } catch(IllegalArgumentException e) { - logln("(h) " + e.getMessage()); + System.out.println("(h) " + e.getMessage()); } } @@ -893,6 +910,7 @@ public void Test4184229() { * SimpleTimeZone.getOffset() throws IllegalArgumentException when to get * of 2/29/1996 (leap day). */ + @Test public void Test4208960 () { // test both SimpleTimeZone and ZoneInfo objects. // @since 1.4 @@ -905,14 +923,14 @@ private void sub4208960(TimeZone tz) { int offset = tz.getOffset(GregorianCalendar.AD, 1996, Calendar.FEBRUARY, 29, Calendar.THURSDAY, 0); } catch (IllegalArgumentException e) { - errln("FAILED: to get TimeZone.getOffset(2/29/96)"); + fail("FAILED: to get TimeZone.getOffset(2/29/96)"); } try { int offset = tz.getOffset(GregorianCalendar.AD, 1997, Calendar.FEBRUARY, 29, Calendar.THURSDAY, 0); - errln("FAILED: TimeZone.getOffset(2/29/97) expected to throw Exception."); + fail("FAILED: TimeZone.getOffset(2/29/97) expected to throw Exception."); } catch (IllegalArgumentException e) { - logln("got IllegalArgumentException"); + System.out.println("got IllegalArgumentException"); } } @@ -921,6 +939,7 @@ private void sub4208960(TimeZone tz) { * sun.util.calendar.ZoneInfo doesn't clone properly. */ @SuppressWarnings("deprecation") + @Test public void Test4966229() { TimeZone savedTZ = TimeZone.getDefault(); try { @@ -945,7 +964,7 @@ public void Test4966229() { cal2.setTime(d); int hourOfDay = cal2.get(cal.HOUR_OF_DAY); if (hourOfDay != expectedHourOfDay) { - errln("wrong hour of day: got: " + hourOfDay + fail("wrong hour of day: got: " + hourOfDay + ", expected: " + expectedHourOfDay); } } finally { @@ -956,6 +975,7 @@ public void Test4966229() { /** * 6433179: (tz) Incorrect DST end for America/Winnipeg and Canada/Central in 2038+ */ + @Test public void Test6433179() { // Use the old America/Winnipeg rule for testing. Note that // startMode is WALL_TIME for testing. It's actually @@ -974,7 +994,7 @@ public void Test6433179() { cal.set(cal.DAY_OF_WEEK_IN_MONTH, -1); cal.add(Calendar.HOUR_OF_DAY, 2); if (cal.get(cal.DST_OFFSET) == 0) { - errln("Should still be in DST."); + fail("Should still be in DST."); } } diff --git a/test/jdk/java/util/TimeZone/TimeZoneTest.java b/test/jdk/java/util/TimeZone/TimeZoneTest.java index 8e5d403f87b..ec2326293fd 100644 --- a/test/jdk/java/util/TimeZone/TimeZoneTest.java +++ b/test/jdk/java/util/TimeZone/TimeZoneTest.java @@ -27,8 +27,8 @@ * 8008577 8077685 8098547 8133321 8138716 8148446 8151876 8159684 8166875 8181157 * 8228469 8274407 8305113 * @modules java.base/sun.util.resources - * @library /java/text/testlib * @summary test TimeZone + * @run junit TimeZoneTest */ import java.io.*; @@ -36,14 +36,14 @@ import java.util.*; import sun.util.resources.LocaleData; -public class TimeZoneTest extends IntlTest +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class TimeZoneTest { static final int millisPerHour = 3600000; - public static void main(String[] args) throws Exception { - new TimeZoneTest().run(args); - } - /** * Bug 4130885 * Certain short zone IDs, used since 1.1.x, are incorrect. @@ -99,6 +99,7 @@ public static void main(String[] args) throws Exception { * else. E.g., EST usually indicates the US Eastern zone, so it cannot be * used for Brazil (BET). */ + @Test public void TestShortZoneIDs() throws Exception { ZoneDescriptor[] JDK_116_REFERENCE_LIST = { @@ -153,10 +154,10 @@ public void TestShortZoneIDs() throws Exception { ZoneDescriptor referenceZone = JDK_116_REFERENCE_LIST[i]; ZoneDescriptor currentZone = hash.get(referenceZone.getID()); if (referenceZone.equals(currentZone)) { - logln("ok " + referenceZone); + System.out.println("ok " + referenceZone); } else { - errln("Fail: Expected " + referenceZone + + fail("Fail: Expected " + referenceZone + "; got " + currentZone); } } @@ -238,6 +239,7 @@ static final String formatMinutes(int min) { * ID "Custom" is no longer used for TimeZone objects created with * a custom time zone ID, such as "GMT-8". See 4322313. */ + @Test public void TestCustomParse() throws Exception { Object[] DATA = { // ID Expected offset in minutes @@ -261,7 +263,7 @@ public void TestCustomParse() throws Exception { Integer exp = (Integer)DATA[i+1]; TimeZone zone = TimeZone.getTimeZone(id); if (zone.getID().equals("GMT")) { - logln(id + " -> generic GMT"); + System.out.println(id + " -> generic GMT"); // When TimeZone.getTimeZone() can't parse the id, it // returns GMT -- a dubious practice, but required for // backward compatibility. @@ -273,7 +275,7 @@ public void TestCustomParse() throws Exception { else { int ioffset = zone.getRawOffset()/60000; String offset = formatMinutes(ioffset); - logln(id + " -> " + zone.getID() + " GMT" + offset); + System.out.println(id + " -> " + zone.getID() + " GMT" + offset); if (exp == null) { throw new Exception("Expected parse failure for " + id + ", got offset of " + offset + @@ -300,12 +302,13 @@ else if (ioffset != exp.intValue()) { * 4/21/98 - make smarter, so the test works if the ext resources * are present or not. */ + @Test public void TestDisplayName() { TimeZone zone = TimeZone.getTimeZone("PST"); String name = zone.getDisplayName(Locale.ENGLISH); - logln("PST->" + name); + System.out.println("PST->" + name); if (!name.equals("Pacific Standard Time")) - errln("Fail: Expected \"Pacific Standard Time\""); + fail("Fail: Expected \"Pacific Standard Time\""); //***************************************************************** // THE FOLLOWING LINES MUST BE UPDATED IF THE LOCALE DATA CHANGES @@ -324,7 +327,7 @@ public void TestDisplayName() { ((Integer)DATA[i+1]).intValue(), Locale.ENGLISH); if (!name.equals(DATA[i+2])) - errln("Fail: Expected " + DATA[i+2] + "; got " + name); + fail("Fail: Expected " + DATA[i+2] + "; got " + name); } // Make sure that we don't display the DST name by constructing a fake @@ -332,11 +335,11 @@ public void TestDisplayName() { SimpleTimeZone zone2 = new SimpleTimeZone(0, "PST"); zone2.setStartRule(Calendar.JANUARY, 1, 0); zone2.setEndRule(Calendar.DECEMBER, 31, 0); - logln("Modified PST inDaylightTime->" + zone2.inDaylightTime(new Date())); + System.out.println("Modified PST inDaylightTime->" + zone2.inDaylightTime(new Date())); name = zone2.getDisplayName(Locale.ENGLISH); - logln("Modified PST->" + name); + System.out.println("Modified PST->" + name); if (!name.equals("Pacific Standard Time")) - errln("Fail: Expected \"Pacific Standard Time\""); + fail("Fail: Expected \"Pacific Standard Time\""); // Make sure we get the default display format for Locales // with no display name data. @@ -347,7 +350,7 @@ public void TestDisplayName() { // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES //***************************************************************** - logln("PST(zh_CN)->" + name); + System.out.println("PST(zh_CN)->" + name); // Now be smart -- check to see if zh resource is even present. // If not, we expect the en fallback behavior. @@ -359,9 +362,9 @@ public void TestDisplayName() { boolean noZH = enRB == zhRB; if (noZH) { - logln("Warning: Not testing the zh_CN behavior because resource is absent"); + System.out.println("Warning: Not testing the zh_CN behavior because resource is absent"); if (!name.equals("Pacific Standard Time")) - errln("Fail: Expected Pacific Standard Time"); + fail("Fail: Expected Pacific Standard Time"); } else if (!name.equals("Pacific Standard Time") && !name.equals("\u592a\u5e73\u6d0b\u6807\u51c6\u65f6\u95f4") && @@ -370,48 +373,49 @@ else if (!name.equals("Pacific Standard Time") && !name.equals("GMT-8:00") && !name.equals("GMT-0800") && !name.equals("GMT-800")) { - errln("Fail: Expected GMT-08:00 or something similar"); - errln("************************************************************"); - errln("THE ABOVE FAILURE MAY JUST MEAN THE LOCALE DATA HAS CHANGED"); - errln("************************************************************"); + fail("Fail: Expected GMT-08:00 or something similar\n" + + "************************************************************\n" + + "THE ABOVE FAILURE MAY JUST MEAN THE LOCALE DATA HAS CHANGED\n" + + "************************************************************\n"); } // Now try a non-existent zone zone2 = new SimpleTimeZone(90*60*1000, "xyzzy"); name = zone2.getDisplayName(Locale.ENGLISH); - logln("GMT+90min->" + name); + System.out.println("GMT+90min->" + name); if (!name.equals("GMT+01:30") && !name.equals("GMT+1:30") && !name.equals("GMT+0130") && !name.equals("GMT+130")) - errln("Fail: Expected GMT+01:30 or something similar"); + fail("Fail: Expected GMT+01:30 or something similar"); } + @Test public void TestGenericAPI() { String id = "NewGMT"; int offset = 12345; SimpleTimeZone zone = new SimpleTimeZone(offset, id); if (zone.useDaylightTime()) { - errln("FAIL: useDaylightTime should return false"); + fail("FAIL: useDaylightTime should return false"); } TimeZone zoneclone = (TimeZone)zone.clone(); if (!zoneclone.equals(zone)) { - errln("FAIL: clone or operator== failed"); + fail("FAIL: clone or operator== failed"); } zoneclone.setID("abc"); if (zoneclone.equals(zone)) { - errln("FAIL: clone or operator!= failed"); + fail("FAIL: clone or operator!= failed"); } zoneclone = (TimeZone)zone.clone(); if (!zoneclone.equals(zone)) { - errln("FAIL: clone or operator== failed"); + fail("FAIL: clone or operator== failed"); } zoneclone.setRawOffset(45678); if (zoneclone.equals(zone)) { - errln("FAIL: clone or operator!= failed"); + fail("FAIL: clone or operator!= failed"); } TimeZone saveDefault = TimeZone.getDefault(); @@ -419,10 +423,10 @@ public void TestGenericAPI() { TimeZone.setDefault(zone); TimeZone defaultzone = TimeZone.getDefault(); if (defaultzone == zone) { - errln("FAIL: Default object is identical, not clone"); + fail("FAIL: Default object is identical, not clone"); } if (!defaultzone.equals(zone)) { - errln("FAIL: Default object is not equal"); + fail("FAIL: Default object is not equal"); } } finally { @@ -431,13 +435,14 @@ public void TestGenericAPI() { } @SuppressWarnings("deprecation") + @Test public void TestRuleAPI() { // ErrorCode status = ZERO_ERROR; int offset = (int)(60*60*1000*1.75); // Pick a weird offset SimpleTimeZone zone = new SimpleTimeZone(offset, "TestZone"); - if (zone.useDaylightTime()) errln("FAIL: useDaylightTime should return false"); + if (zone.useDaylightTime()) fail("FAIL: useDaylightTime should return false"); // Establish our expected transition times. Do this with a non-DST // calendar with the (above) declared local offset. @@ -465,18 +470,18 @@ public void TestRuleAPI() long expMarchOne = 636251400000L; if (marchOne != expMarchOne) { - errln("FAIL: Expected start computed as " + marchOne + + fail("FAIL: Expected start computed as " + marchOne + " = " + new Date(marchOne)); - logln(" Should be " + expMarchOne + + System.out.println(" Should be " + expMarchOne + " = " + new Date(expMarchOne)); } long expJulyOne = 646793100000L; if (julyOne != expJulyOne) { - errln("FAIL: Expected start computed as " + julyOne + + fail("FAIL: Expected start computed as " + julyOne + " = " + new Date(julyOne)); - logln(" Should be " + expJulyOne + + System.out.println(" Should be " + expJulyOne + " = " + new Date(expJulyOne)); } @@ -487,15 +492,15 @@ public void TestRuleAPI() if (zone.inDaylightTime(new Date(marchOne - 1000)) || !zone.inDaylightTime(new Date(marchOne))) - errln("FAIL: Start rule broken"); + fail("FAIL: Start rule broken"); if (!zone.inDaylightTime(new Date(julyOne - 1000)) || zone.inDaylightTime(new Date(julyOne))) - errln("FAIL: End rule broken"); + fail("FAIL: End rule broken"); zone.setStartYear(1991); if (zone.inDaylightTime(new Date(marchOne)) || zone.inDaylightTime(new Date(julyOne - 1000))) - errln("FAIL: Start year broken"); + fail("FAIL: Start year broken"); // failure(status, "TestRuleAPI"); // delete gc; @@ -508,7 +513,7 @@ void testUsingBinarySearch(SimpleTimeZone tz, long min, long max, long expectedB boolean startsInDST = tz.inDaylightTime(new Date(min)); // if (failure(status, "SimpleTimeZone::inDaylightTime")) return; if (tz.inDaylightTime(new Date(max)) == startsInDST) { - logln("Error: inDaylightTime(" + new Date(max) + ") != " + (!startsInDST)); + System.out.println("Error: inDaylightTime(" + new Date(max) + ") != " + (!startsInDST)); return; } // if (failure(status, "SimpleTimeZone::inDaylightTime")) return; @@ -522,52 +527,54 @@ void testUsingBinarySearch(SimpleTimeZone tz, long min, long max, long expectedB } // if (failure(status, "SimpleTimeZone::inDaylightTime")) return; } - logln("Binary Search Before: " + min + " = " + new Date(min)); - logln("Binary Search After: " + max + " = " + new Date(max)); + System.out.println("Binary Search Before: " + min + " = " + new Date(min)); + System.out.println("Binary Search After: " + max + " = " + new Date(max)); long mindelta = expectedBoundary - min; long maxdelta = max - expectedBoundary; if (mindelta >= 0 && mindelta <= INTERVAL && mindelta >= 0 && mindelta <= INTERVAL) - logln("PASS: Expected bdry: " + expectedBoundary + " = " + new Date(expectedBoundary)); + System.out.println("PASS: Expected bdry: " + expectedBoundary + " = " + new Date(expectedBoundary)); else - errln("FAIL: Expected bdry: " + expectedBoundary + " = " + new Date(expectedBoundary)); + fail("FAIL: Expected bdry: " + expectedBoundary + " = " + new Date(expectedBoundary)); } static final int INTERVAL = 100; // Bug 006; verify the offset for a specific zone. + @Test public void TestPRTOffset() { TimeZone tz = TimeZone.getTimeZone( "PRT" ); if( tz == null ) { - errln( "FAIL: TimeZone(PRT) is null" ); + fail( "FAIL: TimeZone(PRT) is null" ); } else{ if (tz.getRawOffset() != (-4*millisPerHour)) - errln("FAIL: Offset for PRT should be -4"); + fail("FAIL: Offset for PRT should be -4"); } } // Test various calls @SuppressWarnings("deprecation") + @Test public void TestVariousAPI518() { TimeZone time_zone = TimeZone.getTimeZone("PST"); Date d = new Date(97, Calendar.APRIL, 30); - logln("The timezone is " + time_zone.getID()); + System.out.println("The timezone is " + time_zone.getID()); if (time_zone.inDaylightTime(d) != true) - errln("FAIL: inDaylightTime returned false"); + fail("FAIL: inDaylightTime returned false"); if (time_zone.useDaylightTime() != true) - errln("FAIL: useDaylightTime returned false"); + fail("FAIL: useDaylightTime returned false"); if (time_zone.getRawOffset() != -8*millisPerHour) - errln( "FAIL: getRawOffset returned wrong value"); + fail( "FAIL: getRawOffset returned wrong value"); GregorianCalendar gc = new GregorianCalendar(); gc.setTime(d); @@ -575,10 +582,11 @@ public void TestVariousAPI518() gc.get(gc.DAY_OF_MONTH), gc.get(gc.DAY_OF_WEEK), 0) != -7*millisPerHour) - errln("FAIL: getOffset returned wrong value"); + fail("FAIL: getOffset returned wrong value"); } // Test getAvailableID API + @Test public void TestGetAvailableIDs913() { StringBuffer buf = new StringBuffer("TimeZone.getAvailableIDs() = { "); @@ -589,7 +597,7 @@ public void TestGetAvailableIDs913() buf.append(s[i]); } buf.append(" };"); - logln(buf.toString()); + System.out.println(buf.toString()); buf.setLength(0); buf.append("TimeZone.getAvailableIDs(GMT+02:00) = { "); @@ -600,31 +608,32 @@ public void TestGetAvailableIDs913() buf.append(s[i]); } buf.append(" };"); - logln(buf.toString()); + System.out.println(buf.toString()); TimeZone tz = TimeZone.getTimeZone("PST"); if (tz != null) - logln("getTimeZone(PST) = " + tz.getID()); + System.out.println("getTimeZone(PST) = " + tz.getID()); else - errln("FAIL: getTimeZone(PST) = null"); + fail("FAIL: getTimeZone(PST) = null"); tz = TimeZone.getTimeZone("America/Los_Angeles"); if (tz != null) - logln("getTimeZone(America/Los_Angeles) = " + tz.getID()); + System.out.println("getTimeZone(America/Los_Angeles) = " + tz.getID()); else - errln("FAIL: getTimeZone(PST) = null"); + fail("FAIL: getTimeZone(PST) = null"); // Bug 4096694 tz = TimeZone.getTimeZone("NON_EXISTENT"); if (tz == null) - errln("FAIL: getTimeZone(NON_EXISTENT) = null"); + fail("FAIL: getTimeZone(NON_EXISTENT) = null"); else if (!tz.getID().equals("GMT")) - errln("FAIL: getTimeZone(NON_EXISTENT) = " + tz.getID()); + fail("FAIL: getTimeZone(NON_EXISTENT) = " + tz.getID()); } /** * Bug 4107276 */ + @Test public void TestDSTSavings() { // It might be better to find a way to integrate this test into the main TimeZone // tests above, but I don't have time to figure out how to do this (or if it's @@ -634,43 +643,44 @@ public void TestDSTSavings() { (int)(0.5 * millisPerHour)); if (tz.getRawOffset() != -5 * millisPerHour) - errln("Got back a raw offset of " + (tz.getRawOffset() / millisPerHour) + + fail("Got back a raw offset of " + (tz.getRawOffset() / millisPerHour) + " hours instead of -5 hours."); if (!tz.useDaylightTime()) - errln("Test time zone should use DST but claims it doesn't."); + fail("Test time zone should use DST but claims it doesn't."); if (tz.getDSTSavings() != 0.5 * millisPerHour) - errln("Set DST offset to 0.5 hour, but got back " + (tz.getDSTSavings() / + fail("Set DST offset to 0.5 hour, but got back " + (tz.getDSTSavings() / millisPerHour) + " hours instead."); int offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.JANUARY, 1, Calendar.THURSDAY, 10 * millisPerHour); if (offset != -5 * millisPerHour) - errln("The offset for 10 AM, 1/1/98 should have been -5 hours, but we got " + fail("The offset for 10 AM, 1/1/98 should have been -5 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.JUNE, 1, Calendar.MONDAY, 10 * millisPerHour); if (offset != -4.5 * millisPerHour) - errln("The offset for 10 AM, 6/1/98 should have been -4.5 hours, but we got " + fail("The offset for 10 AM, 6/1/98 should have been -4.5 hours, but we got " + (offset / millisPerHour) + " hours."); tz.setDSTSavings(millisPerHour); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.JANUARY, 1, Calendar.THURSDAY, 10 * millisPerHour); if (offset != -5 * millisPerHour) - errln("The offset for 10 AM, 1/1/98 should have been -5 hours, but we got " + fail("The offset for 10 AM, 1/1/98 should have been -5 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.JUNE, 1, Calendar.MONDAY, 10 * millisPerHour); if (offset != -4 * millisPerHour) - errln("The offset for 10 AM, 6/1/98 (with a 1-hour DST offset) should have been -4 hours, but we got " + fail("The offset for 10 AM, 6/1/98 (with a 1-hour DST offset) should have been -4 hours, but we got " + (offset / millisPerHour) + " hours."); } /** * Bug 4107570 */ + @Test public void TestAlternateRules() { // Like TestDSTSavings, this test should probably be integrated somehow with the main // test at the top of this class, but I didn't have time to figure out how to do that. @@ -685,25 +695,25 @@ public void TestAlternateRules() { int offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.MARCH, 5, Calendar.THURSDAY, 10 * millisPerHour); if (offset != -5 * millisPerHour) - errln("The offset for 10AM, 3/5/98 should have been -5 hours, but we got " + fail("The offset for 10AM, 3/5/98 should have been -5 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.MARCH, 15, Calendar.SUNDAY, 10 * millisPerHour); if (offset != -4 * millisPerHour) - errln("The offset for 10AM, 3/15/98 should have been -4 hours, but we got " + fail("The offset for 10AM, 3/15/98 should have been -4 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.OCTOBER, 15, Calendar.THURSDAY, 10 * millisPerHour); if (offset != -4 * millisPerHour) - errln("The offset for 10AM, 10/15/98 should have been -4 hours, but we got " + fail("The offset for 10AM, 10/15/98 should have been -4 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.OCTOBER, 25, Calendar.SUNDAY, 10 * millisPerHour); if (offset != -5 * millisPerHour) - errln("The offset for 10AM, 10/25/98 should have been -5 hours, but we got " + fail("The offset for 10AM, 10/25/98 should have been -5 hours, but we got " + (offset / millisPerHour) + " hours."); // test the day-of-week-after-day-in-month API @@ -713,25 +723,25 @@ public void TestAlternateRules() { offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.MARCH, 11, Calendar.WEDNESDAY, 10 * millisPerHour); if (offset != -5 * millisPerHour) - errln("The offset for 10AM, 3/11/98 should have been -5 hours, but we got " + fail("The offset for 10AM, 3/11/98 should have been -5 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.MARCH, 14, Calendar.SATURDAY, 10 * millisPerHour); if (offset != -4 * millisPerHour) - errln("The offset for 10AM, 3/14/98 should have been -4 hours, but we got " + fail("The offset for 10AM, 3/14/98 should have been -4 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.OCTOBER, 15, Calendar.THURSDAY, 10 * millisPerHour); if (offset != -4 * millisPerHour) - errln("The offset for 10AM, 10/15/98 should have been -4 hours, but we got " + fail("The offset for 10AM, 10/15/98 should have been -4 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.OCTOBER, 17, Calendar.SATURDAY, 10 * millisPerHour); if (offset != -5 * millisPerHour) - errln("The offset for 10AM, 10/17/98 should have been -5 hours, but we got " + fail("The offset for 10AM, 10/17/98 should have been -5 hours, but we got " + (offset / millisPerHour) + " hours."); } } diff --git a/test/jdk/java/util/TimeZone/TransitionTest.java b/test/jdk/java/util/TimeZone/TransitionTest.java index 5f012d09d72..fb3e42cf17e 100644 --- a/test/jdk/java/util/TimeZone/TransitionTest.java +++ b/test/jdk/java/util/TimeZone/TransitionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,8 +24,8 @@ /* * @test * @bug 4278609 4761696 - * @library /java/text/testlib * @summary Make sure to handle DST transition ending at 0:00 January 1. + * @run junit TransitionTest */ import java.text.SimpleDateFormat; @@ -36,12 +36,13 @@ import java.util.SimpleTimeZone; import java.util.TimeZone; -public class TransitionTest extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new TransitionTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class TransitionTest { + @Test public void Test4278609() { SimpleTimeZone tz = new SimpleTimeZone(0, "MyTimeZone", /* DST start day: August, 1, 0:00 */ @@ -77,7 +78,7 @@ public void Test4278609() { SimpleDateFormat format = new SimpleDateFormat("dd MMM HH:mm:ss zzz", Locale.US); format.setTimeZone(tz); - errln("Wrong DST transition: " + tz + fail("Wrong DST transition: " + tz + "\na date just after DST = " + format.format(date) + "\ngetOffset = " + offset); } @@ -88,6 +89,7 @@ public void Test4278609() { * * Derived from JCK test cases some of which specify wrong day of week values. */ + @Test public void Test4761696() { GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT")); @@ -121,7 +123,7 @@ public void Test4761696() { long endTime = cal.getTimeInMillis() + rawOffset; long expectedOffset = (localtime < endTime) ? rawOffset + saving : rawOffset; if (offset != expectedOffset) { - errln("test#1: wrong offset: got "+offset+", expected="+expectedOffset); + fail("test#1: wrong offset: got "+offset+", expected="+expectedOffset); } // test#2 @@ -150,7 +152,7 @@ public void Test4761696() { endTime = cal.getTimeInMillis() + rawOffset; expectedOffset = (localtime < endTime) ? rawOffset + saving : rawOffset; if (offset != expectedOffset) { - errln("Wrong offset: got "+offset+", expected="+expectedOffset); + fail("Wrong offset: got "+offset+", expected="+expectedOffset); } rawOffset = 43200000; @@ -179,7 +181,7 @@ public void Test4761696() { endTime = cal.getTimeInMillis() + rawOffset; expectedOffset = (localtime < endTime) ? rawOffset + saving : rawOffset; if (offset != expectedOffset) { - errln("test#2: wrong offset: got "+offset+", expected="+expectedOffset); + fail("test#2: wrong offset: got "+offset+", expected="+expectedOffset); } // test#3 @@ -209,7 +211,7 @@ public void Test4761696() { endTime = cal.getTimeInMillis() + rawOffset; expectedOffset = (localtime < endTime) ? rawOffset + saving : rawOffset; if (offset != expectedOffset) { - errln("test#3: wrong offset: got "+offset+", expected="+expectedOffset); + fail("test#3: wrong offset: got "+offset+", expected="+expectedOffset); } // test#4 @@ -243,7 +245,7 @@ public void Test4761696() { long startTime = cal.getTimeInMillis() + rawOffset; expectedOffset = (localtime >= startTime) ? rawOffset + saving : rawOffset; if (offset != expectedOffset) { - errln("test#4: wrong offset: got "+offset+", expected="+expectedOffset); + fail("test#4: wrong offset: got "+offset+", expected="+expectedOffset); } // test#5 @@ -272,7 +274,7 @@ public void Test4761696() { endTime = cal.getTimeInMillis() + rawOffset; expectedOffset = (localtime < endTime) ? rawOffset + saving : rawOffset; if (offset != expectedOffset) { - errln("test#5: wrong offset: got "+offset+", expected="+expectedOffset); + fail("test#5: wrong offset: got "+offset+", expected="+expectedOffset); } } diff --git a/test/jdk/sun/util/resources/TimeZone/IntlTest.java b/test/jdk/sun/util/resources/TimeZone/IntlTest.java deleted file mode 100644 index 137a610f3d9..00000000000 --- a/test/jdk/sun/util/resources/TimeZone/IntlTest.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.lang.reflect.*; -import java.util.Hashtable; -import java.util.Enumeration; -import java.util.Vector; -import java.io.*; -import java.text.*; - -/** - * IntlTest is a base class for tests that can be run conveniently from - * the command line as well as under the Java test harness. - *

- * Sub-classes implement a set of methods named Test. Each - * of these methods performs some test. Test methods should indicate - * errors by calling either err or errln. This will increment the - * errorCount field and may optionally print a message to the log. - * Debugging information may also be added to the log via the log - * and logln methods. These methods will add their arguments to the - * log only if the test is being run in verbose mode. - */ -public class IntlTest { - - //------------------------------------------------------------------------ - // Everything below here is boilerplate code that makes it possible - // to add a new test by simply adding a function to an existing class - //------------------------------------------------------------------------ - - protected IntlTest() { - // Create a hashtable containing all the test methods. - testMethods = new Hashtable(); - Method[] methods = getClass().getDeclaredMethods(); - for( int i=0; i